chiark / gitweb /
systemctl: cache tty value before we open the pager
[elogind.git] / src / systemctl.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/reboot.h>
23 #include <stdio.h>
24 #include <getopt.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <sys/ioctl.h>
29 #include <termios.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <sys/socket.h>
33 #include <sys/stat.h>
34 #include <stddef.h>
35 #include <sys/prctl.h>
36 #include <dbus/dbus.h>
37
38 #include "log.h"
39 #include "util.h"
40 #include "macro.h"
41 #include "set.h"
42 #include "utmp-wtmp.h"
43 #include "special.h"
44 #include "initreq.h"
45 #include "strv.h"
46 #include "dbus-common.h"
47 #include "cgroup-show.h"
48 #include "cgroup-util.h"
49 #include "list.h"
50 #include "path-lookup.h"
51 #include "conf-parser.h"
52 #include "sd-daemon.h"
53 #include "shutdownd.h"
54 #include "exit-status.h"
55 #include "bus-errors.h"
56 #include "build.h"
57 #include "unit-name.h"
58 #include "pager.h"
59
60 static const char *arg_type = NULL;
61 static char **arg_property = NULL;
62 static bool arg_all = false;
63 static const char *arg_job_mode = "replace";
64 static bool arg_user = false;
65 static bool arg_global = false;
66 static bool arg_immediate = false;
67 static bool arg_no_block = false;
68 static bool arg_no_pager = false;
69 static bool arg_no_wtmp = false;
70 static bool arg_no_sync = false;
71 static bool arg_no_wall = false;
72 static bool arg_no_reload = false;
73 static bool arg_dry = false;
74 static bool arg_quiet = false;
75 static bool arg_full = false;
76 static bool arg_force = false;
77 static bool arg_defaults = false;
78 static bool arg_ask_password = false;
79 static bool arg_failed = false;
80 static char **arg_wall = NULL;
81 static const char *arg_kill_who = NULL;
82 static const char *arg_kill_mode = NULL;
83 static const char *arg_root = NULL;
84 static int arg_signal = SIGTERM;
85 static usec_t arg_when = 0;
86 static enum action {
87         ACTION_INVALID,
88         ACTION_SYSTEMCTL,
89         ACTION_HALT,
90         ACTION_POWEROFF,
91         ACTION_REBOOT,
92         ACTION_KEXEC,
93         ACTION_EXIT,
94         ACTION_RUNLEVEL2,
95         ACTION_RUNLEVEL3,
96         ACTION_RUNLEVEL4,
97         ACTION_RUNLEVEL5,
98         ACTION_RESCUE,
99         ACTION_EMERGENCY,
100         ACTION_DEFAULT,
101         ACTION_RELOAD,
102         ACTION_REEXEC,
103         ACTION_RUNLEVEL,
104         ACTION_CANCEL_SHUTDOWN,
105         _ACTION_MAX
106 } arg_action = ACTION_SYSTEMCTL;
107 static enum dot {
108         DOT_ALL,
109         DOT_ORDER,
110         DOT_REQUIRE
111 } arg_dot = DOT_ALL;
112 static enum transport {
113         TRANSPORT_NORMAL,
114         TRANSPORT_SSH,
115         TRANSPORT_POLKIT
116 } arg_transport = TRANSPORT_NORMAL;
117 static const char *arg_host = NULL;
118
119 static bool private_bus = false;
120
121 static pid_t agent_pid = 0;
122
123 static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
124
125 static bool on_tty(void) {
126         static int t = -1;
127
128         /* Note that this is invoked relatively early, before we start
129          * the pager. That means the value we return reflects whether
130          * we originally were started on a tty, not if we currently
131          * are. But this is intended, since we want colour and so on
132          * when run in our own pager. */
133
134         if (_unlikely_(t < 0))
135                 t = isatty(STDOUT_FILENO) > 0;
136
137         return t;
138 }
139
140 static void pager_open_if_enabled(void) {
141         on_tty();
142
143         if (!arg_no_pager)
144                 pager_open();
145 }
146
147 static void spawn_ask_password_agent(void) {
148         pid_t parent;
149
150         if (agent_pid > 0)
151                 return;
152
153         /* We check STDIN here, not STDOUT, since this is about input,
154          * not output */
155         if (!isatty(STDIN_FILENO))
156                 return;
157
158         if (!arg_ask_password)
159                 return;
160
161         if (arg_user)
162                 return;
163
164         parent = getpid();
165
166         /* Spawns a temporary TTY agent, making sure it goes away when
167          * we go away */
168
169         if ((agent_pid = fork()) < 0)
170                 return;
171
172         if (agent_pid == 0) {
173                 /* In the child */
174
175                 int fd;
176                 bool stdout_is_tty, stderr_is_tty;
177
178                 /* Make sure the agent goes away when the parent dies */
179                 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
180                         _exit(EXIT_FAILURE);
181
182                 /* Check whether our parent died before we were able
183                  * to set the death signal */
184                 if (getppid() != parent)
185                         _exit(EXIT_SUCCESS);
186
187                 /* Don't leak fds to the agent */
188                 close_all_fds(NULL, 0);
189
190                 stdout_is_tty = isatty(STDOUT_FILENO);
191                 stderr_is_tty = isatty(STDERR_FILENO);
192
193                 if (!stdout_is_tty || !stderr_is_tty) {
194                         /* Detach from stdout/stderr. and reopen
195                          * /dev/tty for them. This is important to
196                          * ensure that when systemctl is started via
197                          * popen() or a similar call that expects to
198                          * read EOF we actually do generate EOF and
199                          * not delay this indefinitely by because we
200                          * keep an unused copy of stdin around. */
201                         if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
202                                 log_error("Failed to open /dev/tty: %m");
203                                 _exit(EXIT_FAILURE);
204                         }
205
206                         if (!stdout_is_tty)
207                                 dup2(fd, STDOUT_FILENO);
208
209                         if (!stderr_is_tty)
210                                 dup2(fd, STDERR_FILENO);
211
212                         if (fd > 2)
213                                 close(fd);
214                 }
215
216                 execl(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
217
218                 log_error("Unable to execute agent: %m");
219                 _exit(EXIT_FAILURE);
220         }
221 }
222
223 static const char *ansi_highlight(bool b) {
224
225         if (!on_tty())
226                 return "";
227
228         return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
229 }
230
231 static const char *ansi_highlight_green(bool b) {
232
233         if (!on_tty())
234                 return "";
235
236         return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
237 }
238
239 static bool error_is_no_service(const DBusError *error) {
240         assert(error);
241
242         if (!dbus_error_is_set(error))
243                 return false;
244
245         if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
246                 return true;
247
248         if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
249                 return true;
250
251         return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
252 }
253
254 static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
255         assert(error);
256
257         if (!dbus_error_is_set(error))
258                 return r;
259
260         if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
261             dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
262             dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
263             dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
264                 return EXIT_NOPERMISSION;
265
266         if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
267                 return EXIT_NOTINSTALLED;
268
269         if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
270             dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
271                 return EXIT_NOTIMPLEMENTED;
272
273         if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
274                 return EXIT_NOTCONFIGURED;
275
276         if (r != 0)
277                 return r;
278
279         return EXIT_FAILURE;
280 }
281
282 static void warn_wall(enum action action) {
283         static const char *table[_ACTION_MAX] = {
284                 [ACTION_HALT]      = "The system is going down for system halt NOW!",
285                 [ACTION_REBOOT]    = "The system is going down for reboot NOW!",
286                 [ACTION_POWEROFF]  = "The system is going down for power-off NOW!",
287                 [ACTION_KEXEC]     = "The system is going down for kexec reboot NOW!",
288                 [ACTION_RESCUE]    = "The system is going down to rescue mode NOW!",
289                 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
290         };
291
292         if (arg_no_wall)
293                 return;
294
295         if (arg_wall) {
296                 char *p;
297
298                 if (!(p = strv_join(arg_wall, " "))) {
299                         log_error("Failed to join strings.");
300                         return;
301                 }
302
303                 if (*p) {
304                         utmp_wall(p, NULL);
305                         free(p);
306                         return;
307                 }
308
309                 free(p);
310         }
311
312         if (!table[action])
313                 return;
314
315         utmp_wall(table[action], NULL);
316 }
317
318 struct unit_info {
319         const char *id;
320         const char *description;
321         const char *load_state;
322         const char *active_state;
323         const char *sub_state;
324         const char *following;
325         const char *unit_path;
326         uint32_t job_id;
327         const char *job_type;
328         const char *job_path;
329 };
330
331 static int compare_unit_info(const void *a, const void *b) {
332         const char *d1, *d2;
333         const struct unit_info *u = a, *v = b;
334
335         d1 = strrchr(u->id, '.');
336         d2 = strrchr(v->id, '.');
337
338         if (d1 && d2) {
339                 int r;
340
341                 if ((r = strcasecmp(d1, d2)) != 0)
342                         return r;
343         }
344
345         return strcasecmp(u->id, v->id);
346 }
347
348 static bool output_show_unit(const struct unit_info *u) {
349         const char *dot;
350
351         if (arg_failed)
352                 return streq(u->active_state, "failed");
353
354         return (!arg_type || ((dot = strrchr(u->id, '.')) &&
355                               streq(dot+1, arg_type))) &&
356                 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
357 }
358
359 static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
360         unsigned active_len, sub_len, job_len, n_shown = 0;
361         const struct unit_info *u;
362
363         active_len = sizeof("ACTIVE")-1;
364         sub_len = sizeof("SUB")-1;
365         job_len = sizeof("JOB")-1;
366
367         for (u = unit_infos; u < unit_infos + c; u++) {
368                 if (!output_show_unit(u))
369                         continue;
370
371                 active_len = MAX(active_len, strlen(u->active_state));
372                 sub_len = MAX(sub_len, strlen(u->sub_state));
373                 if (u->job_id != 0)
374                         job_len = MAX(job_len, strlen(u->job_type));
375         }
376
377         if (on_tty()) {
378                 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
379                        active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
380                 if (columns() >= 80+12 || arg_full || !arg_no_pager)
381                         printf(" %s\n", "DESCRIPTION");
382                 else
383                         printf("\n");
384         }
385
386         for (u = unit_infos; u < unit_infos + c; u++) {
387                 char *e;
388                 int a = 0, b = 0;
389                 const char *on_loaded, *off_loaded;
390                 const char *on_active, *off_active;
391
392                 if (!output_show_unit(u))
393                         continue;
394
395                 n_shown++;
396
397                 if (!streq(u->load_state, "loaded") &&
398                     !streq(u->load_state, "banned")) {
399                         on_loaded = ansi_highlight(true);
400                         off_loaded = ansi_highlight(false);
401                 } else
402                         on_loaded = off_loaded = "";
403
404                 if (streq(u->active_state, "failed")) {
405                         on_active = ansi_highlight(true);
406                         off_active = ansi_highlight(false);
407                 } else
408                         on_active = off_active = "";
409
410                 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
411
412                 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
413                        e ? e : u->id,
414                        on_loaded, u->load_state, off_loaded,
415                        on_active, active_len, u->active_state,
416                        sub_len, u->sub_state, off_active,
417                        &a);
418
419                 free(e);
420
421                 a -= strlen(on_loaded) + strlen(off_loaded);
422                 a -= strlen(on_active) + strlen(off_active);
423
424                 if (u->job_id != 0)
425                         printf(" %-*s", job_len, u->job_type);
426                 else
427                         b = 1 + job_len;
428
429                 if (a + b + 1 < columns()) {
430                         if (u->job_id == 0)
431                                 printf(" %-*s", job_len, "");
432
433                         if (arg_full || !arg_no_pager)
434                                 printf(" %s", u->description);
435                         else
436                                 printf(" %.*s", columns() - a - b - 1, u->description);
437                 }
438
439                 fputs("\n", stdout);
440         }
441
442         if (on_tty()) {
443                 printf("\nLOAD   = Reflects whether the unit definition was properly loaded.\n"
444                        "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
445                        "SUB    = The low-level unit activation state, values depend on unit type.\n"
446                        "JOB    = Pending job for the unit.\n");
447
448                 if (arg_all)
449                         printf("\n%u units listed.\n", n_shown);
450                 else
451                         printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
452         }
453 }
454
455 static int list_units(DBusConnection *bus, char **args, unsigned n) {
456         DBusMessage *m = NULL, *reply = NULL;
457         DBusError error;
458         int r;
459         DBusMessageIter iter, sub, sub2;
460         unsigned c = 0, n_units = 0;
461         struct unit_info *unit_infos = NULL;
462
463         dbus_error_init(&error);
464
465         assert(bus);
466
467         pager_open_if_enabled();
468
469         if (!(m = dbus_message_new_method_call(
470                               "org.freedesktop.systemd1",
471                               "/org/freedesktop/systemd1",
472                               "org.freedesktop.systemd1.Manager",
473                               "ListUnits"))) {
474                 log_error("Could not allocate message.");
475                 return -ENOMEM;
476         }
477
478         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
479                 log_error("Failed to issue method call: %s", bus_error_message(&error));
480                 r = -EIO;
481                 goto finish;
482         }
483
484         if (!dbus_message_iter_init(reply, &iter) ||
485             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
486             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
487                 log_error("Failed to parse reply.");
488                 r = -EIO;
489                 goto finish;
490         }
491
492         dbus_message_iter_recurse(&iter, &sub);
493
494         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
495                 struct unit_info *u;
496
497                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
498                         log_error("Failed to parse reply.");
499                         r = -EIO;
500                         goto finish;
501                 }
502
503                 if (c >= n_units) {
504                         struct unit_info *w;
505
506                         n_units = MAX(2*c, 16);
507                         w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
508
509                         if (!w) {
510                                 log_error("Failed to allocate unit array.");
511                                 r = -ENOMEM;
512                                 goto finish;
513                         }
514
515                         unit_infos = w;
516                 }
517
518                 u = unit_infos+c;
519
520                 dbus_message_iter_recurse(&sub, &sub2);
521
522                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
523                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
524                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
525                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
526                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
527                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
528                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
529                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
530                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
531                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
532                         log_error("Failed to parse reply.");
533                         r = -EIO;
534                         goto finish;
535                 }
536
537                 dbus_message_iter_next(&sub);
538                 c++;
539         }
540
541         if (c > 0) {
542                 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
543                 output_units_list(unit_infos, c);
544         }
545
546         r = 0;
547
548 finish:
549         if (m)
550                 dbus_message_unref(m);
551
552         if (reply)
553                 dbus_message_unref(reply);
554
555         free(unit_infos);
556
557         dbus_error_free(&error);
558
559         return r;
560 }
561
562 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
563         static const char * const colors[] = {
564                 "Requires",              "[color=\"black\"]",
565                 "RequiresOverridable",   "[color=\"black\"]",
566                 "Requisite",             "[color=\"darkblue\"]",
567                 "RequisiteOverridable",  "[color=\"darkblue\"]",
568                 "Wants",                 "[color=\"darkgrey\"]",
569                 "Conflicts",             "[color=\"red\"]",
570                 "ConflictedBy",          "[color=\"red\"]",
571                 "After",                 "[color=\"green\"]"
572         };
573
574         const char *c = NULL;
575         unsigned i;
576
577         assert(name);
578         assert(prop);
579         assert(iter);
580
581         for (i = 0; i < ELEMENTSOF(colors); i += 2)
582                 if (streq(colors[i], prop)) {
583                         c = colors[i+1];
584                         break;
585                 }
586
587         if (!c)
588                 return 0;
589
590         if (arg_dot != DOT_ALL)
591                 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
592                         return 0;
593
594         switch (dbus_message_iter_get_arg_type(iter)) {
595
596         case DBUS_TYPE_ARRAY:
597
598                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
599                         DBusMessageIter sub;
600
601                         dbus_message_iter_recurse(iter, &sub);
602
603                         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
604                                 const char *s;
605
606                                 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
607                                 dbus_message_iter_get_basic(&sub, &s);
608                                 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
609
610                                 dbus_message_iter_next(&sub);
611                         }
612
613                         return 0;
614                 }
615         }
616
617         return 0;
618 }
619
620 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
621         DBusMessage *m = NULL, *reply = NULL;
622         const char *interface = "org.freedesktop.systemd1.Unit";
623         int r;
624         DBusError error;
625         DBusMessageIter iter, sub, sub2, sub3;
626
627         assert(bus);
628         assert(path);
629
630         dbus_error_init(&error);
631
632         if (!(m = dbus_message_new_method_call(
633                               "org.freedesktop.systemd1",
634                               path,
635                               "org.freedesktop.DBus.Properties",
636                               "GetAll"))) {
637                 log_error("Could not allocate message.");
638                 r = -ENOMEM;
639                 goto finish;
640         }
641
642         if (!dbus_message_append_args(m,
643                                       DBUS_TYPE_STRING, &interface,
644                                       DBUS_TYPE_INVALID)) {
645                 log_error("Could not append arguments to message.");
646                 r = -ENOMEM;
647                 goto finish;
648         }
649
650         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
651                 log_error("Failed to issue method call: %s", bus_error_message(&error));
652                 r = -EIO;
653                 goto finish;
654         }
655
656         if (!dbus_message_iter_init(reply, &iter) ||
657             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
658             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
659                 log_error("Failed to parse reply.");
660                 r = -EIO;
661                 goto finish;
662         }
663
664         dbus_message_iter_recurse(&iter, &sub);
665
666         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
667                 const char *prop;
668
669                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
670                         log_error("Failed to parse reply.");
671                         r = -EIO;
672                         goto finish;
673                 }
674
675                 dbus_message_iter_recurse(&sub, &sub2);
676
677                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
678                         log_error("Failed to parse reply.");
679                         r = -EIO;
680                         goto finish;
681                 }
682
683                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
684                         log_error("Failed to parse reply.");
685                         r = -EIO;
686                         goto finish;
687                 }
688
689                 dbus_message_iter_recurse(&sub2, &sub3);
690
691                 if (dot_one_property(name, prop, &sub3)) {
692                         log_error("Failed to parse reply.");
693                         r = -EIO;
694                         goto finish;
695                 }
696
697                 dbus_message_iter_next(&sub);
698         }
699
700         r = 0;
701
702 finish:
703         if (m)
704                 dbus_message_unref(m);
705
706         if (reply)
707                 dbus_message_unref(reply);
708
709         dbus_error_free(&error);
710
711         return r;
712 }
713
714 static int dot(DBusConnection *bus, char **args, unsigned n) {
715         DBusMessage *m = NULL, *reply = NULL;
716         DBusError error;
717         int r;
718         DBusMessageIter iter, sub, sub2;
719
720         dbus_error_init(&error);
721
722         assert(bus);
723
724         if (!(m = dbus_message_new_method_call(
725                               "org.freedesktop.systemd1",
726                               "/org/freedesktop/systemd1",
727                               "org.freedesktop.systemd1.Manager",
728                               "ListUnits"))) {
729                 log_error("Could not allocate message.");
730                 return -ENOMEM;
731         }
732
733         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
734                 log_error("Failed to issue method call: %s", bus_error_message(&error));
735                 r = -EIO;
736                 goto finish;
737         }
738
739         if (!dbus_message_iter_init(reply, &iter) ||
740             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
741             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
742                 log_error("Failed to parse reply.");
743                 r = -EIO;
744                 goto finish;
745         }
746
747         printf("digraph systemd {\n");
748
749         dbus_message_iter_recurse(&iter, &sub);
750         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
751                 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
752
753                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
754                         log_error("Failed to parse reply.");
755                         r = -EIO;
756                         goto finish;
757                 }
758
759                 dbus_message_iter_recurse(&sub, &sub2);
760
761                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
762                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
763                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
764                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
765                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
766                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
767                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
768                         log_error("Failed to parse reply.");
769                         r = -EIO;
770                         goto finish;
771                 }
772
773                 if ((r = dot_one(bus, id, unit_path)) < 0)
774                         goto finish;
775
776                 /* printf("\t\"%s\";\n", id); */
777                 dbus_message_iter_next(&sub);
778         }
779
780         printf("}\n");
781
782         log_info("   Color legend: black     = Requires\n"
783                  "                 dark blue = Requisite\n"
784                  "                 dark grey = Wants\n"
785                  "                 red       = Conflicts\n"
786                  "                 green     = After\n");
787
788         if (isatty(fileno(stdout)))
789                 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
790                            "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
791
792         r = 0;
793
794 finish:
795         if (m)
796                 dbus_message_unref(m);
797
798         if (reply)
799                 dbus_message_unref(reply);
800
801         dbus_error_free(&error);
802
803         return r;
804 }
805
806 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
807         DBusMessage *m = NULL, *reply = NULL;
808         DBusError error;
809         int r;
810         DBusMessageIter iter, sub, sub2;
811         unsigned k = 0;
812
813         dbus_error_init(&error);
814
815         assert(bus);
816
817         pager_open_if_enabled();
818
819         if (!(m = dbus_message_new_method_call(
820                               "org.freedesktop.systemd1",
821                               "/org/freedesktop/systemd1",
822                               "org.freedesktop.systemd1.Manager",
823                               "ListJobs"))) {
824                 log_error("Could not allocate message.");
825                 return -ENOMEM;
826         }
827
828         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
829                 log_error("Failed to issue method call: %s", bus_error_message(&error));
830                 r = -EIO;
831                 goto finish;
832         }
833
834         if (!dbus_message_iter_init(reply, &iter) ||
835             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
836             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
837                 log_error("Failed to parse reply.");
838                 r = -EIO;
839                 goto finish;
840         }
841
842         dbus_message_iter_recurse(&iter, &sub);
843
844         if (isatty(STDOUT_FILENO))
845                 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
846
847         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
848                 const char *name, *type, *state, *job_path, *unit_path;
849                 uint32_t id;
850                 char *e;
851
852                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
853                         log_error("Failed to parse reply.");
854                         r = -EIO;
855                         goto finish;
856                 }
857
858                 dbus_message_iter_recurse(&sub, &sub2);
859
860                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
861                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
862                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
863                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
864                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
865                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
866                         log_error("Failed to parse reply.");
867                         r = -EIO;
868                         goto finish;
869                 }
870
871                 e = arg_full ? NULL : ellipsize(name, 25, 33);
872                 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
873                 free(e);
874
875                 k++;
876
877                 dbus_message_iter_next(&sub);
878         }
879
880         if (isatty(STDOUT_FILENO))
881                 printf("\n%u jobs listed.\n", k);
882
883         r = 0;
884
885 finish:
886         if (m)
887                 dbus_message_unref(m);
888
889         if (reply)
890                 dbus_message_unref(reply);
891
892         dbus_error_free(&error);
893
894         return r;
895 }
896
897 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
898         DBusMessage *m = NULL, *reply = NULL;
899         DBusError error;
900         int r;
901         unsigned i;
902
903         dbus_error_init(&error);
904
905         assert(bus);
906         assert(args);
907
908         for (i = 1; i < n; i++) {
909
910                 if (!(m = dbus_message_new_method_call(
911                                       "org.freedesktop.systemd1",
912                                       "/org/freedesktop/systemd1",
913                                       "org.freedesktop.systemd1.Manager",
914                                       "LoadUnit"))) {
915                         log_error("Could not allocate message.");
916                         r = -ENOMEM;
917                         goto finish;
918                 }
919
920                 if (!dbus_message_append_args(m,
921                                               DBUS_TYPE_STRING, &args[i],
922                                               DBUS_TYPE_INVALID)) {
923                         log_error("Could not append arguments to message.");
924                         r = -ENOMEM;
925                         goto finish;
926                 }
927
928                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
929                         log_error("Failed to issue method call: %s", bus_error_message(&error));
930                         r = -EIO;
931                         goto finish;
932                 }
933
934                 dbus_message_unref(m);
935                 dbus_message_unref(reply);
936
937                 m = reply = NULL;
938         }
939
940         r = 0;
941
942 finish:
943         if (m)
944                 dbus_message_unref(m);
945
946         if (reply)
947                 dbus_message_unref(reply);
948
949         dbus_error_free(&error);
950
951         return r;
952 }
953
954 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
955         DBusMessage *m = NULL, *reply = NULL;
956         DBusError error;
957         int r;
958         unsigned i;
959
960         dbus_error_init(&error);
961
962         assert(bus);
963         assert(args);
964
965         if (n <= 1)
966                 return daemon_reload(bus, args, n);
967
968         for (i = 1; i < n; i++) {
969                 unsigned id;
970                 const char *path;
971
972                 if (!(m = dbus_message_new_method_call(
973                                       "org.freedesktop.systemd1",
974                                       "/org/freedesktop/systemd1",
975                                       "org.freedesktop.systemd1.Manager",
976                                       "GetJob"))) {
977                         log_error("Could not allocate message.");
978                         r = -ENOMEM;
979                         goto finish;
980                 }
981
982                 if ((r = safe_atou(args[i], &id)) < 0) {
983                         log_error("Failed to parse job id: %s", strerror(-r));
984                         goto finish;
985                 }
986
987                 assert_cc(sizeof(uint32_t) == sizeof(id));
988                 if (!dbus_message_append_args(m,
989                                               DBUS_TYPE_UINT32, &id,
990                                               DBUS_TYPE_INVALID)) {
991                         log_error("Could not append arguments to message.");
992                         r = -ENOMEM;
993                         goto finish;
994                 }
995
996                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
997                         log_error("Failed to issue method call: %s", bus_error_message(&error));
998                         r = -EIO;
999                         goto finish;
1000                 }
1001
1002                 if (!dbus_message_get_args(reply, &error,
1003                                            DBUS_TYPE_OBJECT_PATH, &path,
1004                                            DBUS_TYPE_INVALID)) {
1005                         log_error("Failed to parse reply: %s", bus_error_message(&error));
1006                         r = -EIO;
1007                         goto finish;
1008                 }
1009
1010                 dbus_message_unref(m);
1011                 if (!(m = dbus_message_new_method_call(
1012                                       "org.freedesktop.systemd1",
1013                                       path,
1014                                       "org.freedesktop.systemd1.Job",
1015                                       "Cancel"))) {
1016                         log_error("Could not allocate message.");
1017                         r = -ENOMEM;
1018                         goto finish;
1019                 }
1020
1021                 dbus_message_unref(reply);
1022                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1023                         log_error("Failed to issue method call: %s", bus_error_message(&error));
1024                         r = -EIO;
1025                         goto finish;
1026                 }
1027
1028                 dbus_message_unref(m);
1029                 dbus_message_unref(reply);
1030                 m = reply = NULL;
1031         }
1032
1033         r = 0;
1034
1035 finish:
1036         if (m)
1037                 dbus_message_unref(m);
1038
1039         if (reply)
1040                 dbus_message_unref(reply);
1041
1042         dbus_error_free(&error);
1043
1044         return r;
1045 }
1046
1047 static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1048         DBusMessage *m = NULL, *reply = NULL;
1049         dbus_bool_t b = FALSE;
1050         DBusMessageIter iter, sub;
1051         const char
1052                 *interface = "org.freedesktop.systemd1.Unit",
1053                 *property = "NeedDaemonReload",
1054                 *path;
1055
1056         /* We ignore all errors here, since this is used to show a warning only */
1057
1058         if (!(m = dbus_message_new_method_call(
1059                               "org.freedesktop.systemd1",
1060                               "/org/freedesktop/systemd1",
1061                               "org.freedesktop.systemd1.Manager",
1062                               "GetUnit")))
1063                 goto finish;
1064
1065         if (!dbus_message_append_args(m,
1066                                       DBUS_TYPE_STRING, &unit,
1067                                       DBUS_TYPE_INVALID))
1068                 goto finish;
1069
1070         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1071                 goto finish;
1072
1073         if (!dbus_message_get_args(reply, NULL,
1074                                    DBUS_TYPE_OBJECT_PATH, &path,
1075                                    DBUS_TYPE_INVALID))
1076                 goto finish;
1077
1078         dbus_message_unref(m);
1079         if (!(m = dbus_message_new_method_call(
1080                               "org.freedesktop.systemd1",
1081                               path,
1082                               "org.freedesktop.DBus.Properties",
1083                               "Get")))
1084                 goto finish;
1085
1086         if (!dbus_message_append_args(m,
1087                                       DBUS_TYPE_STRING, &interface,
1088                                       DBUS_TYPE_STRING, &property,
1089                                       DBUS_TYPE_INVALID)) {
1090                 goto finish;
1091         }
1092
1093         dbus_message_unref(reply);
1094         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1095                 goto finish;
1096
1097         if (!dbus_message_iter_init(reply, &iter) ||
1098             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1099                 goto finish;
1100
1101         dbus_message_iter_recurse(&iter, &sub);
1102
1103         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1104                 goto finish;
1105
1106         dbus_message_iter_get_basic(&sub, &b);
1107
1108 finish:
1109         if (m)
1110                 dbus_message_unref(m);
1111
1112         if (reply)
1113                 dbus_message_unref(reply);
1114
1115         return b;
1116 }
1117
1118 typedef struct WaitData {
1119         Set *set;
1120         char *result;
1121 } WaitData;
1122
1123 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1124         DBusError error;
1125         WaitData *d = data;
1126
1127         assert(connection);
1128         assert(message);
1129         assert(d);
1130
1131         dbus_error_init(&error);
1132
1133         log_debug("Got D-Bus request: %s.%s() on %s",
1134                   dbus_message_get_interface(message),
1135                   dbus_message_get_member(message),
1136                   dbus_message_get_path(message));
1137
1138         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1139                 log_error("Warning! D-Bus connection terminated.");
1140                 dbus_connection_close(connection);
1141
1142         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1143                 uint32_t id;
1144                 const char *path, *result;
1145                 dbus_bool_t success = true;
1146
1147                 if (dbus_message_get_args(message, &error,
1148                                           DBUS_TYPE_UINT32, &id,
1149                                           DBUS_TYPE_OBJECT_PATH, &path,
1150                                           DBUS_TYPE_STRING, &result,
1151                                           DBUS_TYPE_INVALID)) {
1152                         char *p;
1153
1154                         if ((p = set_remove(d->set, (char*) path)))
1155                                 free(p);
1156
1157                         if (*result)
1158                                 d->result = strdup(result);
1159
1160                         goto finish;
1161                 }
1162 #ifndef LEGACY
1163                 dbus_error_free(&error);
1164
1165                 if (dbus_message_get_args(message, &error,
1166                                           DBUS_TYPE_UINT32, &id,
1167                                           DBUS_TYPE_OBJECT_PATH, &path,
1168                                           DBUS_TYPE_BOOLEAN, &success,
1169                                           DBUS_TYPE_INVALID)) {
1170                         char *p;
1171
1172                         /* Compatibility with older systemd versions <
1173                          * 19 during upgrades. This should be dropped
1174                          * one day */
1175
1176                         if ((p = set_remove(d->set, (char*) path)))
1177                                 free(p);
1178
1179                         if (!success)
1180                                 d->result = strdup("failed");
1181
1182                         goto finish;
1183                 }
1184 #endif
1185
1186                 log_error("Failed to parse message: %s", bus_error_message(&error));
1187         }
1188
1189 finish:
1190         dbus_error_free(&error);
1191         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1192 }
1193
1194 static int enable_wait_for_jobs(DBusConnection *bus) {
1195         DBusError error;
1196
1197         assert(bus);
1198
1199         if (private_bus)
1200                 return 0;
1201
1202         dbus_error_init(&error);
1203         dbus_bus_add_match(bus,
1204                            "type='signal',"
1205                            "sender='org.freedesktop.systemd1',"
1206                            "interface='org.freedesktop.systemd1.Manager',"
1207                            "member='JobRemoved',"
1208                            "path='/org/freedesktop/systemd1'",
1209                            &error);
1210
1211         if (dbus_error_is_set(&error)) {
1212                 log_error("Failed to add match: %s", bus_error_message(&error));
1213                 dbus_error_free(&error);
1214                 return -EIO;
1215         }
1216
1217         /* This is slightly dirty, since we don't undo the match registrations. */
1218         return 0;
1219 }
1220
1221 static int wait_for_jobs(DBusConnection *bus, Set *s) {
1222         int r;
1223         WaitData d;
1224
1225         assert(bus);
1226         assert(s);
1227
1228         zero(d);
1229         d.set = s;
1230
1231         if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1232                 log_error("Failed to add filter.");
1233                 r = -ENOMEM;
1234                 goto finish;
1235         }
1236
1237         while (!set_isempty(s) &&
1238                dbus_connection_read_write_dispatch(bus, -1))
1239                 ;
1240
1241         if (!arg_quiet && d.result) {
1242                 if (streq(d.result, "timeout"))
1243                         log_error("Job timed out.");
1244                 else if (streq(d.result, "canceled"))
1245                         log_error("Job canceled.");
1246                 else if (streq(d.result, "dependency"))
1247                         log_error("A dependency job failed. See system logs for details.");
1248                 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
1249                         log_error("Job failed. See system logs and 'systemctl status' for details.");
1250         }
1251
1252         if (streq_ptr(d.result, "timeout"))
1253                 r = -ETIME;
1254         else if (streq_ptr(d.result, "canceled"))
1255                 r = -ECANCELED;
1256         else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
1257                 r = -EIO;
1258         else
1259                 r = 0;
1260
1261         free(d.result);
1262
1263 finish:
1264         /* This is slightly dirty, since we don't undo the filter registration. */
1265
1266         return r;
1267 }
1268
1269 static int start_unit_one(
1270                 DBusConnection *bus,
1271                 const char *method,
1272                 const char *name,
1273                 const char *mode,
1274                 DBusError *error,
1275                 Set *s) {
1276
1277         DBusMessage *m = NULL, *reply = NULL;
1278         const char *path;
1279         int r;
1280
1281         assert(bus);
1282         assert(method);
1283         assert(name);
1284         assert(mode);
1285         assert(error);
1286         assert(arg_no_block || s);
1287
1288         if (!(m = dbus_message_new_method_call(
1289                               "org.freedesktop.systemd1",
1290                               "/org/freedesktop/systemd1",
1291                               "org.freedesktop.systemd1.Manager",
1292                               method))) {
1293                 log_error("Could not allocate message.");
1294                 r = -ENOMEM;
1295                 goto finish;
1296         }
1297
1298         if (!dbus_message_append_args(m,
1299                                       DBUS_TYPE_STRING, &name,
1300                                       DBUS_TYPE_STRING, &mode,
1301                                       DBUS_TYPE_INVALID)) {
1302                 log_error("Could not append arguments to message.");
1303                 r = -ENOMEM;
1304                 goto finish;
1305         }
1306
1307         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
1308
1309                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
1310                         /* There's always a fallback possible for
1311                          * legacy actions. */
1312                         r = -EADDRNOTAVAIL;
1313                         goto finish;
1314                 }
1315
1316                 log_error("Failed to issue method call: %s", bus_error_message(error));
1317                 r = -EIO;
1318                 goto finish;
1319         }
1320
1321         if (!dbus_message_get_args(reply, error,
1322                                    DBUS_TYPE_OBJECT_PATH, &path,
1323                                    DBUS_TYPE_INVALID)) {
1324                 log_error("Failed to parse reply: %s", bus_error_message(error));
1325                 r = -EIO;
1326                 goto finish;
1327         }
1328
1329         if (need_daemon_reload(bus, name))
1330                 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1331                             arg_user ? "--user" : "--system");
1332
1333         if (!arg_no_block) {
1334                 char *p;
1335
1336                 if (!(p = strdup(path))) {
1337                         log_error("Failed to duplicate path.");
1338                         r = -ENOMEM;
1339                         goto finish;
1340                 }
1341
1342                 if ((r = set_put(s, p)) < 0) {
1343                         free(p);
1344                         log_error("Failed to add path to set.");
1345                         goto finish;
1346                 }
1347         }
1348
1349         r = 0;
1350
1351 finish:
1352         if (m)
1353                 dbus_message_unref(m);
1354
1355         if (reply)
1356                 dbus_message_unref(reply);
1357
1358         return r;
1359 }
1360
1361 static enum action verb_to_action(const char *verb) {
1362         if (streq(verb, "halt"))
1363                 return ACTION_HALT;
1364         else if (streq(verb, "poweroff"))
1365                 return ACTION_POWEROFF;
1366         else if (streq(verb, "reboot"))
1367                 return ACTION_REBOOT;
1368         else if (streq(verb, "kexec"))
1369                 return ACTION_KEXEC;
1370         else if (streq(verb, "rescue"))
1371                 return ACTION_RESCUE;
1372         else if (streq(verb, "emergency"))
1373                 return ACTION_EMERGENCY;
1374         else if (streq(verb, "default"))
1375                 return ACTION_DEFAULT;
1376         else if (streq(verb, "exit"))
1377                 return ACTION_EXIT;
1378         else
1379                 return ACTION_INVALID;
1380 }
1381
1382 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1383
1384         static const char * const table[_ACTION_MAX] = {
1385                 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1386                 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1387                 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1388                 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
1389                 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1390                 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1391                 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1392                 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1393                 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1394                 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1395                 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1396                 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
1397         };
1398
1399         int r, ret = 0;
1400         unsigned i;
1401         const char *method, *mode, *one_name;
1402         Set *s = NULL;
1403         DBusError error;
1404
1405         dbus_error_init(&error);
1406
1407         assert(bus);
1408
1409         spawn_ask_password_agent();
1410
1411         if (arg_action == ACTION_SYSTEMCTL) {
1412                 method =
1413                         streq(args[0], "stop") ||
1414                         streq(args[0], "condstop")              ? "StopUnit" :
1415                         streq(args[0], "reload")                ? "ReloadUnit" :
1416                         streq(args[0], "restart")               ? "RestartUnit" :
1417
1418                         streq(args[0], "try-restart")           ||
1419                         streq(args[0], "condrestart")           ? "TryRestartUnit" :
1420
1421                         streq(args[0], "reload-or-restart")     ? "ReloadOrRestartUnit" :
1422
1423                         streq(args[0], "reload-or-try-restart") ||
1424                         streq(args[0], "condreload") ||
1425
1426                         streq(args[0], "force-reload")          ? "ReloadOrTryRestartUnit" :
1427                                                                   "StartUnit";
1428
1429                 mode =
1430                         (streq(args[0], "isolate") ||
1431                          streq(args[0], "rescue")  ||
1432                          streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1433
1434                 one_name = table[verb_to_action(args[0])];
1435
1436         } else {
1437                 assert(arg_action < ELEMENTSOF(table));
1438                 assert(table[arg_action]);
1439
1440                 method = "StartUnit";
1441
1442                 mode = (arg_action == ACTION_EMERGENCY ||
1443                         arg_action == ACTION_RESCUE ||
1444                         arg_action == ACTION_RUNLEVEL2 ||
1445                         arg_action == ACTION_RUNLEVEL3 ||
1446                         arg_action == ACTION_RUNLEVEL4 ||
1447                         arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1448
1449                 one_name = table[arg_action];
1450         }
1451
1452         if (!arg_no_block) {
1453                 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1454                         log_error("Could not watch jobs: %s", strerror(-ret));
1455                         goto finish;
1456                 }
1457
1458                 if (!(s = set_new(string_hash_func, string_compare_func))) {
1459                         log_error("Failed to allocate set.");
1460                         ret = -ENOMEM;
1461                         goto finish;
1462                 }
1463         }
1464
1465         if (one_name) {
1466                 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1467                         goto finish;
1468         } else {
1469                 for (i = 1; i < n; i++)
1470                         if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1471                                 ret = translate_bus_error_to_exit_status(r, &error);
1472                                 dbus_error_free(&error);
1473                         }
1474         }
1475
1476         if (!arg_no_block)
1477                 if ((r = wait_for_jobs(bus, s)) < 0) {
1478                         ret = r;
1479                         goto finish;
1480                 }
1481
1482 finish:
1483         if (s)
1484                 set_free_free(s);
1485
1486         dbus_error_free(&error);
1487
1488         return ret;
1489 }
1490
1491 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1492         int r;
1493
1494         assert(bus);
1495         assert(args);
1496
1497         if (arg_force &&
1498             (streq(args[0], "halt") ||
1499              streq(args[0], "poweroff") ||
1500              streq(args[0], "reboot") ||
1501              streq(args[0], "kexec") ||
1502              streq(args[0], "exit")))
1503                 return daemon_reload(bus, args, n);
1504
1505         r = start_unit(bus, args, n);
1506
1507         if (r >= 0)
1508                 warn_wall(verb_to_action(args[0]));
1509
1510         return r;
1511 }
1512
1513 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1514         DBusMessage *m = NULL, *reply = NULL;
1515         const char
1516                 *interface = "org.freedesktop.systemd1.Unit",
1517                 *property = "ActiveState";
1518         int r = 3; /* According to LSB: "program is not running" */
1519         DBusError error;
1520         unsigned i;
1521
1522         assert(bus);
1523         assert(args);
1524
1525         dbus_error_init(&error);
1526
1527         for (i = 1; i < n; i++) {
1528                 const char *path = NULL;
1529                 const char *state;
1530                 DBusMessageIter iter, sub;
1531
1532                 if (!(m = dbus_message_new_method_call(
1533                                       "org.freedesktop.systemd1",
1534                                       "/org/freedesktop/systemd1",
1535                                       "org.freedesktop.systemd1.Manager",
1536                                       "GetUnit"))) {
1537                         log_error("Could not allocate message.");
1538                         r = -ENOMEM;
1539                         goto finish;
1540                 }
1541
1542                 if (!dbus_message_append_args(m,
1543                                               DBUS_TYPE_STRING, &args[i],
1544                                               DBUS_TYPE_INVALID)) {
1545                         log_error("Could not append arguments to message.");
1546                         r = -ENOMEM;
1547                         goto finish;
1548                 }
1549
1550                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1551
1552                         /* Hmm, cannot figure out anything about this unit... */
1553                         if (!arg_quiet)
1554                                 puts("unknown");
1555
1556                         dbus_error_free(&error);
1557                         dbus_message_unref(m);
1558                         m = NULL;
1559                         continue;
1560                 }
1561
1562                 if (!dbus_message_get_args(reply, &error,
1563                                            DBUS_TYPE_OBJECT_PATH, &path,
1564                                            DBUS_TYPE_INVALID)) {
1565                         log_error("Failed to parse reply: %s", bus_error_message(&error));
1566                         r = -EIO;
1567                         goto finish;
1568                 }
1569
1570                 dbus_message_unref(m);
1571                 if (!(m = dbus_message_new_method_call(
1572                                       "org.freedesktop.systemd1",
1573                                       path,
1574                                       "org.freedesktop.DBus.Properties",
1575                                       "Get"))) {
1576                         log_error("Could not allocate message.");
1577                         r = -ENOMEM;
1578                         goto finish;
1579                 }
1580
1581                 if (!dbus_message_append_args(m,
1582                                               DBUS_TYPE_STRING, &interface,
1583                                               DBUS_TYPE_STRING, &property,
1584                                               DBUS_TYPE_INVALID)) {
1585                         log_error("Could not append arguments to message.");
1586                         r = -ENOMEM;
1587                         goto finish;
1588                 }
1589
1590                 dbus_message_unref(reply);
1591                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1592                         log_error("Failed to issue method call: %s", bus_error_message(&error));
1593                         r = -EIO;
1594                         goto finish;
1595                 }
1596
1597                 if (!dbus_message_iter_init(reply, &iter) ||
1598                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1599                         log_error("Failed to parse reply.");
1600                         r = -EIO;
1601                         goto finish;
1602                 }
1603
1604                 dbus_message_iter_recurse(&iter, &sub);
1605
1606                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1607                         log_error("Failed to parse reply.");
1608                         r = -EIO;
1609                         goto finish;
1610                 }
1611
1612                 dbus_message_iter_get_basic(&sub, &state);
1613
1614                 if (!arg_quiet)
1615                         puts(state);
1616
1617                 if (streq(state, "active") || streq(state, "reloading"))
1618                         r = 0;
1619
1620                 dbus_message_unref(m);
1621                 dbus_message_unref(reply);
1622                 m = reply = NULL;
1623         }
1624
1625 finish:
1626         if (m)
1627                 dbus_message_unref(m);
1628
1629         if (reply)
1630                 dbus_message_unref(reply);
1631
1632         dbus_error_free(&error);
1633
1634         return r;
1635 }
1636
1637 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1638         DBusMessage *m = NULL, *reply = NULL;
1639         int r = 0;
1640         DBusError error;
1641         unsigned i;
1642
1643         assert(bus);
1644         assert(args);
1645
1646         dbus_error_init(&error);
1647
1648         if (!arg_kill_who)
1649                 arg_kill_who = "all";
1650
1651         if (!arg_kill_mode)
1652                 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1653
1654         for (i = 1; i < n; i++) {
1655
1656                 if (!(m = dbus_message_new_method_call(
1657                                       "org.freedesktop.systemd1",
1658                                       "/org/freedesktop/systemd1",
1659                                       "org.freedesktop.systemd1.Manager",
1660                                       "KillUnit"))) {
1661                         log_error("Could not allocate message.");
1662                         r = -ENOMEM;
1663                         goto finish;
1664                 }
1665
1666                 if (!dbus_message_append_args(m,
1667                                               DBUS_TYPE_STRING, &args[i],
1668                                               DBUS_TYPE_STRING, &arg_kill_who,
1669                                               DBUS_TYPE_STRING, &arg_kill_mode,
1670                                               DBUS_TYPE_INT32, &arg_signal,
1671                                               DBUS_TYPE_INVALID)) {
1672                         log_error("Could not append arguments to message.");
1673                         r = -ENOMEM;
1674                         goto finish;
1675                 }
1676
1677                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1678                         log_error("Failed to issue method call: %s", bus_error_message(&error));
1679                         dbus_error_free(&error);
1680                         r = -EIO;
1681                 }
1682
1683                 dbus_message_unref(m);
1684
1685                 if (reply)
1686                         dbus_message_unref(reply);
1687                 m = reply = NULL;
1688         }
1689
1690 finish:
1691         if (m)
1692                 dbus_message_unref(m);
1693
1694         if (reply)
1695                 dbus_message_unref(reply);
1696
1697         dbus_error_free(&error);
1698
1699         return r;
1700 }
1701
1702 typedef struct ExecStatusInfo {
1703         char *name;
1704
1705         char *path;
1706         char **argv;
1707
1708         bool ignore;
1709
1710         usec_t start_timestamp;
1711         usec_t exit_timestamp;
1712         pid_t pid;
1713         int code;
1714         int status;
1715
1716         LIST_FIELDS(struct ExecStatusInfo, exec);
1717 } ExecStatusInfo;
1718
1719 static void exec_status_info_free(ExecStatusInfo *i) {
1720         assert(i);
1721
1722         free(i->name);
1723         free(i->path);
1724         strv_free(i->argv);
1725         free(i);
1726 }
1727
1728 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1729         uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
1730         DBusMessageIter sub2, sub3;
1731         const char*path;
1732         unsigned n;
1733         uint32_t pid;
1734         int32_t code, status;
1735         dbus_bool_t ignore;
1736
1737         assert(i);
1738         assert(i);
1739
1740         if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1741                 return -EIO;
1742
1743         dbus_message_iter_recurse(sub, &sub2);
1744
1745         if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1746                 return -EIO;
1747
1748         if (!(i->path = strdup(path)))
1749                 return -ENOMEM;
1750
1751         if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1752             dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1753                 return -EIO;
1754
1755         n = 0;
1756         dbus_message_iter_recurse(&sub2, &sub3);
1757         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1758                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1759                 dbus_message_iter_next(&sub3);
1760                 n++;
1761         }
1762
1763
1764         if (!(i->argv = new0(char*, n+1)))
1765                 return -ENOMEM;
1766
1767         n = 0;
1768         dbus_message_iter_recurse(&sub2, &sub3);
1769         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1770                 const char *s;
1771
1772                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1773                 dbus_message_iter_get_basic(&sub3, &s);
1774                 dbus_message_iter_next(&sub3);
1775
1776                 if (!(i->argv[n++] = strdup(s)))
1777                         return -ENOMEM;
1778         }
1779
1780         if (!dbus_message_iter_next(&sub2) ||
1781             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1782             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1783             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
1784             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1785             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
1786             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1787             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1788             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1789                 return -EIO;
1790
1791         i->ignore = ignore;
1792         i->start_timestamp = (usec_t) start_timestamp;
1793         i->exit_timestamp = (usec_t) exit_timestamp;
1794         i->pid = (pid_t) pid;
1795         i->code = code;
1796         i->status = status;
1797
1798         return 0;
1799 }
1800
1801 typedef struct UnitStatusInfo {
1802         const char *id;
1803         const char *load_state;
1804         const char *active_state;
1805         const char *sub_state;
1806
1807         const char *description;
1808         const char *following;
1809
1810         const char *path;
1811         const char *default_control_group;
1812
1813         usec_t inactive_exit_timestamp;
1814         usec_t active_enter_timestamp;
1815         usec_t active_exit_timestamp;
1816         usec_t inactive_enter_timestamp;
1817
1818         bool need_daemon_reload;
1819
1820         /* Service */
1821         pid_t main_pid;
1822         pid_t control_pid;
1823         const char *status_text;
1824         bool running:1;
1825 #ifdef HAVE_SYSV_COMPAT
1826         bool is_sysv:1;
1827 #endif
1828
1829         usec_t start_timestamp;
1830         usec_t exit_timestamp;
1831
1832         int exit_code, exit_status;
1833
1834         usec_t condition_timestamp;
1835         bool condition_result;
1836
1837         /* Socket */
1838         unsigned n_accepted;
1839         unsigned n_connections;
1840         bool accept;
1841
1842         /* Device */
1843         const char *sysfs_path;
1844
1845         /* Mount, Automount */
1846         const char *where;
1847
1848         /* Swap */
1849         const char *what;
1850
1851         LIST_HEAD(ExecStatusInfo, exec);
1852 } UnitStatusInfo;
1853
1854 static void print_status_info(UnitStatusInfo *i) {
1855         ExecStatusInfo *p;
1856         const char *on, *off, *ss;
1857         usec_t timestamp;
1858         char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1859         char since2[FORMAT_TIMESTAMP_MAX], *s2;
1860
1861         assert(i);
1862
1863         /* This shows pretty information about a unit. See
1864          * print_property() for a low-level property printer */
1865
1866         printf("%s", strna(i->id));
1867
1868         if (i->description && !streq_ptr(i->id, i->description))
1869                 printf(" - %s", i->description);
1870
1871         printf("\n");
1872
1873         if (i->following)
1874                 printf("\t  Follow: unit currently follows state of %s\n", i->following);
1875
1876         if (streq_ptr(i->load_state, "failed") ||
1877             streq_ptr(i->load_state, "banned")) {
1878                 on = ansi_highlight(true);
1879                 off = ansi_highlight(false);
1880         } else
1881                 on = off = "";
1882
1883         if (i->path)
1884                 printf("\t  Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1885         else
1886                 printf("\t  Loaded: %s%s%s\n", on, strna(i->load_state), off);
1887
1888         ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1889
1890         if (streq_ptr(i->active_state, "failed")) {
1891                 on = ansi_highlight(true);
1892                 off = ansi_highlight(false);
1893         } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1894                 on = ansi_highlight_green(true);
1895                 off = ansi_highlight_green(false);
1896         } else
1897                 on = off = "";
1898
1899         if (ss)
1900                 printf("\t  Active: %s%s (%s)%s",
1901                        on,
1902                        strna(i->active_state),
1903                        ss,
1904                        off);
1905         else
1906                 printf("\t  Active: %s%s%s",
1907                        on,
1908                        strna(i->active_state),
1909                        off);
1910
1911         timestamp = (streq_ptr(i->active_state, "active")      ||
1912                      streq_ptr(i->active_state, "reloading"))   ? i->active_enter_timestamp :
1913                     (streq_ptr(i->active_state, "inactive")    ||
1914                      streq_ptr(i->active_state, "failed"))      ? i->inactive_enter_timestamp :
1915                     streq_ptr(i->active_state, "activating")    ? i->inactive_exit_timestamp :
1916                                                                   i->active_exit_timestamp;
1917
1918         s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1919         s2 = format_timestamp(since2, sizeof(since2), timestamp);
1920
1921         if (s1)
1922                 printf(" since %s; %s\n", s2, s1);
1923         else if (s2)
1924                 printf(" since %s\n", s2);
1925         else
1926                 printf("\n");
1927
1928         if (!i->condition_result && i->condition_timestamp > 0) {
1929                 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
1930                 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
1931
1932                 if (s1)
1933                         printf("\t          start condition failed at %s; %s\n", s2, s1);
1934                 else if (s2)
1935                         printf("\t          start condition failed at %s\n", s2);
1936         }
1937
1938         if (i->sysfs_path)
1939                 printf("\t  Device: %s\n", i->sysfs_path);
1940         if (i->where)
1941                 printf("\t   Where: %s\n", i->where);
1942         if (i->what)
1943                 printf("\t    What: %s\n", i->what);
1944
1945         if (i->accept)
1946                 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1947
1948         LIST_FOREACH(exec, p, i->exec) {
1949                 char *t;
1950                 bool good;
1951
1952                 /* Only show exited processes here */
1953                 if (p->code == 0)
1954                         continue;
1955
1956                 t = strv_join(p->argv, " ");
1957                 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1958                 free(t);
1959
1960 #ifdef HAVE_SYSV_COMPAT
1961                 if (i->is_sysv)
1962                         good = is_clean_exit_lsb(p->code, p->status);
1963                 else
1964 #endif
1965                         good = is_clean_exit(p->code, p->status);
1966
1967                 if (!good) {
1968                         on = ansi_highlight(true);
1969                         off = ansi_highlight(false);
1970                 } else
1971                         on = off = "";
1972
1973                 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1974
1975                 if (p->code == CLD_EXITED) {
1976                         const char *c;
1977
1978                         printf("status=%i", p->status);
1979
1980 #ifdef HAVE_SYSV_COMPAT
1981                         if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1982 #else
1983                         if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1984 #endif
1985                                 printf("/%s", c);
1986
1987                 } else
1988                         printf("signal=%s", signal_to_string(p->status));
1989
1990                 printf(")%s\n", off);
1991
1992                 on = off = NULL;
1993
1994                 if (i->main_pid == p->pid &&
1995                     i->start_timestamp == p->start_timestamp &&
1996                     i->exit_timestamp == p->start_timestamp)
1997                         /* Let's not show this twice */
1998                         i->main_pid = 0;
1999
2000                 if (p->pid == i->control_pid)
2001                         i->control_pid = 0;
2002         }
2003
2004         if (i->main_pid > 0 || i->control_pid > 0) {
2005                 printf("\t");
2006
2007                 if (i->main_pid > 0) {
2008                         printf("Main PID: %u", (unsigned) i->main_pid);
2009
2010                         if (i->running) {
2011                                 char *t = NULL;
2012                                 get_process_name(i->main_pid, &t);
2013                                 if (t) {
2014                                         printf(" (%s)", t);
2015                                         free(t);
2016                                 }
2017                         } else if (i->exit_code > 0) {
2018                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2019
2020                                 if (i->exit_code == CLD_EXITED) {
2021                                         const char *c;
2022
2023                                         printf("status=%i", i->exit_status);
2024
2025 #ifdef HAVE_SYSV_COMPAT
2026                                         if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2027 #else
2028                                         if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2029 #endif
2030                                                 printf("/%s", c);
2031
2032                                 } else
2033                                         printf("signal=%s", signal_to_string(i->exit_status));
2034                                 printf(")");
2035                         }
2036                 }
2037
2038                 if (i->main_pid > 0 && i->control_pid > 0)
2039                         printf(";");
2040
2041                 if (i->control_pid > 0) {
2042                         char *t = NULL;
2043
2044                         printf(" Control: %u", (unsigned) i->control_pid);
2045
2046                         get_process_name(i->control_pid, &t);
2047                         if (t) {
2048                                 printf(" (%s)", t);
2049                                 free(t);
2050                         }
2051                 }
2052
2053                 printf("\n");
2054         }
2055
2056         if (i->status_text)
2057                 printf("\t  Status: \"%s\"\n", i->status_text);
2058
2059         if (i->default_control_group) {
2060                 unsigned c;
2061
2062                 printf("\t  CGroup: %s\n", i->default_control_group);
2063
2064                 if (arg_transport != TRANSPORT_SSH) {
2065                         if ((c = columns()) > 18)
2066                                 c -= 18;
2067                         else
2068                                 c = 0;
2069
2070                         show_cgroup_by_path(i->default_control_group, "\t\t  ", c);
2071                 }
2072         }
2073
2074         if (i->need_daemon_reload)
2075                 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2076                        ansi_highlight(true),
2077                        ansi_highlight(false),
2078                        arg_user ? "--user" : "--system");
2079 }
2080
2081 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2082
2083         switch (dbus_message_iter_get_arg_type(iter)) {
2084
2085         case DBUS_TYPE_STRING: {
2086                 const char *s;
2087
2088                 dbus_message_iter_get_basic(iter, &s);
2089
2090                 if (s[0]) {
2091                         if (streq(name, "Id"))
2092                                 i->id = s;
2093                         else if (streq(name, "LoadState"))
2094                                 i->load_state = s;
2095                         else if (streq(name, "ActiveState"))
2096                                 i->active_state = s;
2097                         else if (streq(name, "SubState"))
2098                                 i->sub_state = s;
2099                         else if (streq(name, "Description"))
2100                                 i->description = s;
2101                         else if (streq(name, "FragmentPath"))
2102                                 i->path = s;
2103 #ifdef HAVE_SYSV_COMPAT
2104                         else if (streq(name, "SysVPath")) {
2105                                 i->is_sysv = true;
2106                                 i->path = s;
2107                         }
2108 #endif
2109                         else if (streq(name, "DefaultControlGroup"))
2110                                 i->default_control_group = s;
2111                         else if (streq(name, "StatusText"))
2112                                 i->status_text = s;
2113                         else if (streq(name, "SysFSPath"))
2114                                 i->sysfs_path = s;
2115                         else if (streq(name, "Where"))
2116                                 i->where = s;
2117                         else if (streq(name, "What"))
2118                                 i->what = s;
2119                         else if (streq(name, "Following"))
2120                                 i->following = s;
2121                 }
2122
2123                 break;
2124         }
2125
2126         case DBUS_TYPE_BOOLEAN: {
2127                 dbus_bool_t b;
2128
2129                 dbus_message_iter_get_basic(iter, &b);
2130
2131                 if (streq(name, "Accept"))
2132                         i->accept = b;
2133                 else if (streq(name, "NeedDaemonReload"))
2134                         i->need_daemon_reload = b;
2135                 else if (streq(name, "ConditionResult"))
2136                         i->condition_result = b;
2137
2138                 break;
2139         }
2140
2141         case DBUS_TYPE_UINT32: {
2142                 uint32_t u;
2143
2144                 dbus_message_iter_get_basic(iter, &u);
2145
2146                 if (streq(name, "MainPID")) {
2147                         if (u > 0) {
2148                                 i->main_pid = (pid_t) u;
2149                                 i->running = true;
2150                         }
2151                 } else if (streq(name, "ControlPID"))
2152                         i->control_pid = (pid_t) u;
2153                 else if (streq(name, "ExecMainPID")) {
2154                         if (u > 0)
2155                                 i->main_pid = (pid_t) u;
2156                 } else if (streq(name, "NAccepted"))
2157                         i->n_accepted = u;
2158                 else if (streq(name, "NConnections"))
2159                         i->n_connections = u;
2160
2161                 break;
2162         }
2163
2164         case DBUS_TYPE_INT32: {
2165                 int32_t j;
2166
2167                 dbus_message_iter_get_basic(iter, &j);
2168
2169                 if (streq(name, "ExecMainCode"))
2170                         i->exit_code = (int) j;
2171                 else if (streq(name, "ExecMainStatus"))
2172                         i->exit_status = (int) j;
2173
2174                 break;
2175         }
2176
2177         case DBUS_TYPE_UINT64: {
2178                 uint64_t u;
2179
2180                 dbus_message_iter_get_basic(iter, &u);
2181
2182                 if (streq(name, "ExecMainStartTimestamp"))
2183                         i->start_timestamp = (usec_t) u;
2184                 else if (streq(name, "ExecMainExitTimestamp"))
2185                         i->exit_timestamp = (usec_t) u;
2186                 else if (streq(name, "ActiveEnterTimestamp"))
2187                         i->active_enter_timestamp = (usec_t) u;
2188                 else if (streq(name, "InactiveEnterTimestamp"))
2189                         i->inactive_enter_timestamp = (usec_t) u;
2190                 else if (streq(name, "InactiveExitTimestamp"))
2191                         i->inactive_exit_timestamp = (usec_t) u;
2192                 else if (streq(name, "ActiveExitTimestamp"))
2193                         i->active_exit_timestamp = (usec_t) u;
2194                 else if (streq(name, "ConditionTimestamp"))
2195                         i->condition_timestamp = (usec_t) u;
2196
2197                 break;
2198         }
2199
2200         case DBUS_TYPE_ARRAY: {
2201
2202                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2203                     startswith(name, "Exec")) {
2204                         DBusMessageIter sub;
2205
2206                         dbus_message_iter_recurse(iter, &sub);
2207                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2208                                 ExecStatusInfo *info;
2209                                 int r;
2210
2211                                 if (!(info = new0(ExecStatusInfo, 1)))
2212                                         return -ENOMEM;
2213
2214                                 if (!(info->name = strdup(name))) {
2215                                         free(info);
2216                                         return -ENOMEM;
2217                                 }
2218
2219                                 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2220                                         free(info);
2221                                         return r;
2222                                 }
2223
2224                                 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2225
2226                                 dbus_message_iter_next(&sub);
2227                         }
2228                 }
2229
2230                 break;
2231         }
2232         }
2233
2234         return 0;
2235 }
2236
2237 static int print_property(const char *name, DBusMessageIter *iter) {
2238         assert(name);
2239         assert(iter);
2240
2241         /* This is a low-level property printer, see
2242          * print_status_info() for the nicer output */
2243
2244         if (arg_property && !strv_find(arg_property, name))
2245                 return 0;
2246
2247         switch (dbus_message_iter_get_arg_type(iter)) {
2248
2249         case DBUS_TYPE_STRING: {
2250                 const char *s;
2251                 dbus_message_iter_get_basic(iter, &s);
2252
2253                 if (arg_all || s[0])
2254                         printf("%s=%s\n", name, s);
2255
2256                 return 0;
2257         }
2258
2259         case DBUS_TYPE_BOOLEAN: {
2260                 dbus_bool_t b;
2261                 dbus_message_iter_get_basic(iter, &b);
2262                 printf("%s=%s\n", name, yes_no(b));
2263
2264                 return 0;
2265         }
2266
2267         case DBUS_TYPE_UINT64: {
2268                 uint64_t u;
2269                 dbus_message_iter_get_basic(iter, &u);
2270
2271                 /* Yes, heuristics! But we can change this check
2272                  * should it turn out to not be sufficient */
2273
2274                 if (endswith(name, "Timestamp")) {
2275                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2276
2277                         if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2278                                 printf("%s=%s\n", name, strempty(t));
2279                 } else if (strstr(name, "USec")) {
2280                         char timespan[FORMAT_TIMESPAN_MAX];
2281
2282                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2283                 } else
2284                         printf("%s=%llu\n", name, (unsigned long long) u);
2285
2286                 return 0;
2287         }
2288
2289         case DBUS_TYPE_UINT32: {
2290                 uint32_t u;
2291                 dbus_message_iter_get_basic(iter, &u);
2292
2293                 if (strstr(name, "UMask") || strstr(name, "Mode"))
2294                         printf("%s=%04o\n", name, u);
2295                 else
2296                         printf("%s=%u\n", name, (unsigned) u);
2297
2298                 return 0;
2299         }
2300
2301         case DBUS_TYPE_INT32: {
2302                 int32_t i;
2303                 dbus_message_iter_get_basic(iter, &i);
2304
2305                 printf("%s=%i\n", name, (int) i);
2306                 return 0;
2307         }
2308
2309         case DBUS_TYPE_DOUBLE: {
2310                 double d;
2311                 dbus_message_iter_get_basic(iter, &d);
2312
2313                 printf("%s=%g\n", name, d);
2314                 return 0;
2315         }
2316
2317         case DBUS_TYPE_STRUCT: {
2318                 DBusMessageIter sub;
2319                 dbus_message_iter_recurse(iter, &sub);
2320
2321                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2322                         uint32_t u;
2323
2324                         dbus_message_iter_get_basic(&sub, &u);
2325
2326                         if (u)
2327                                 printf("%s=%u\n", name, (unsigned) u);
2328                         else if (arg_all)
2329                                 printf("%s=\n", name);
2330
2331                         return 0;
2332                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2333                         const char *s;
2334
2335                         dbus_message_iter_get_basic(&sub, &s);
2336
2337                         if (arg_all || s[0])
2338                                 printf("%s=%s\n", name, s);
2339
2340                         return 0;
2341                 }
2342
2343                 break;
2344         }
2345
2346         case DBUS_TYPE_ARRAY:
2347
2348                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2349                         DBusMessageIter sub;
2350                         bool space = false;
2351
2352                         dbus_message_iter_recurse(iter, &sub);
2353                         if (arg_all ||
2354                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2355                                 printf("%s=", name);
2356
2357                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2358                                         const char *s;
2359
2360                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2361                                         dbus_message_iter_get_basic(&sub, &s);
2362                                         printf("%s%s", space ? " " : "", s);
2363
2364                                         space = true;
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_BYTE) {
2374                         DBusMessageIter sub;
2375
2376                         dbus_message_iter_recurse(iter, &sub);
2377                         if (arg_all ||
2378                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2379                                 printf("%s=", name);
2380
2381                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2382                                         uint8_t u;
2383
2384                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2385                                         dbus_message_iter_get_basic(&sub, &u);
2386                                         printf("%02x", u);
2387
2388                                         dbus_message_iter_next(&sub);
2389                                 }
2390
2391                                 puts("");
2392                         }
2393
2394                         return 0;
2395
2396                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2397                         DBusMessageIter sub, sub2;
2398
2399                         dbus_message_iter_recurse(iter, &sub);
2400                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2401                                 const char *path;
2402                                 dbus_bool_t ignore;
2403
2404                                 dbus_message_iter_recurse(&sub, &sub2);
2405
2406                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2407                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2408                                         printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2409
2410                                 dbus_message_iter_next(&sub);
2411                         }
2412
2413                         return 0;
2414
2415                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2416                         DBusMessageIter sub, sub2;
2417
2418                         dbus_message_iter_recurse(iter, &sub);
2419                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2420                                 const char *type, *path;
2421
2422                                 dbus_message_iter_recurse(&sub, &sub2);
2423
2424                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2425                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2426                                         printf("%s=%s\n", type, path);
2427
2428                                 dbus_message_iter_next(&sub);
2429                         }
2430
2431                         return 0;
2432
2433                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2434                         DBusMessageIter sub, sub2;
2435
2436                         dbus_message_iter_recurse(iter, &sub);
2437                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2438                                 const char *base;
2439                                 uint64_t value, next_elapse;
2440
2441                                 dbus_message_iter_recurse(&sub, &sub2);
2442
2443                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2444                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2445                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2446                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2447
2448                                         printf("%s={ value=%s ; next_elapse=%s }\n",
2449                                                base,
2450                                                format_timespan(timespan1, sizeof(timespan1), value),
2451                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
2452                                 }
2453
2454                                 dbus_message_iter_next(&sub);
2455                         }
2456
2457                         return 0;
2458
2459                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2460                         DBusMessageIter sub;
2461
2462                         dbus_message_iter_recurse(iter, &sub);
2463                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2464                                 ExecStatusInfo info;
2465
2466                                 zero(info);
2467                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2468                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2469                                         char *t;
2470
2471                                         t = strv_join(info.argv, " ");
2472
2473                                         printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2474                                                name,
2475                                                strna(info.path),
2476                                                strna(t),
2477                                                yes_no(info.ignore),
2478                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2479                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2480                                                (unsigned) info. pid,
2481                                                sigchld_code_to_string(info.code),
2482                                                info.status,
2483                                                info.code == CLD_EXITED ? "" : "/",
2484                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2485
2486                                         free(t);
2487                                 }
2488
2489                                 free(info.path);
2490                                 strv_free(info.argv);
2491
2492                                 dbus_message_iter_next(&sub);
2493                         }
2494
2495                         return 0;
2496                 }
2497
2498                 break;
2499         }
2500
2501         if (arg_all)
2502                 printf("%s=[unprintable]\n", name);
2503
2504         return 0;
2505 }
2506
2507 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2508         DBusMessage *m = NULL, *reply = NULL;
2509         const char *interface = "";
2510         int r;
2511         DBusError error;
2512         DBusMessageIter iter, sub, sub2, sub3;
2513         UnitStatusInfo info;
2514         ExecStatusInfo *p;
2515
2516         assert(bus);
2517         assert(path);
2518         assert(new_line);
2519
2520         zero(info);
2521         dbus_error_init(&error);
2522
2523         if (!(m = dbus_message_new_method_call(
2524                               "org.freedesktop.systemd1",
2525                               path,
2526                               "org.freedesktop.DBus.Properties",
2527                               "GetAll"))) {
2528                 log_error("Could not allocate message.");
2529                 r = -ENOMEM;
2530                 goto finish;
2531         }
2532
2533         if (!dbus_message_append_args(m,
2534                                       DBUS_TYPE_STRING, &interface,
2535                                       DBUS_TYPE_INVALID)) {
2536                 log_error("Could not append arguments to message.");
2537                 r = -ENOMEM;
2538                 goto finish;
2539         }
2540
2541         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2542                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2543                 r = -EIO;
2544                 goto finish;
2545         }
2546
2547         if (!dbus_message_iter_init(reply, &iter) ||
2548             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2549             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
2550                 log_error("Failed to parse reply.");
2551                 r = -EIO;
2552                 goto finish;
2553         }
2554
2555         dbus_message_iter_recurse(&iter, &sub);
2556
2557         if (*new_line)
2558                 printf("\n");
2559
2560         *new_line = true;
2561
2562         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2563                 const char *name;
2564
2565                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2566                         log_error("Failed to parse reply.");
2567                         r = -EIO;
2568                         goto finish;
2569                 }
2570
2571                 dbus_message_iter_recurse(&sub, &sub2);
2572
2573                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2574                         log_error("Failed to parse reply.");
2575                         r = -EIO;
2576                         goto finish;
2577                 }
2578
2579                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
2580                         log_error("Failed to parse reply.");
2581                         r = -EIO;
2582                         goto finish;
2583                 }
2584
2585                 dbus_message_iter_recurse(&sub2, &sub3);
2586
2587                 if (show_properties)
2588                         r = print_property(name, &sub3);
2589                 else
2590                         r = status_property(name, &sub3, &info);
2591
2592                 if (r < 0) {
2593                         log_error("Failed to parse reply.");
2594                         r = -EIO;
2595                         goto finish;
2596                 }
2597
2598                 dbus_message_iter_next(&sub);
2599         }
2600
2601         r = 0;
2602
2603         if (!show_properties)
2604                 print_status_info(&info);
2605
2606         if (!streq_ptr(info.active_state, "active") &&
2607             !streq_ptr(info.active_state, "reloading") &&
2608             streq(verb, "status"))
2609                 /* According to LSB: "program not running" */
2610                 r = 3;
2611
2612         while ((p = info.exec)) {
2613                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2614                 exec_status_info_free(p);
2615         }
2616
2617 finish:
2618         if (m)
2619                 dbus_message_unref(m);
2620
2621         if (reply)
2622                 dbus_message_unref(reply);
2623
2624         dbus_error_free(&error);
2625
2626         return r;
2627 }
2628
2629 static int show(DBusConnection *bus, char **args, unsigned n) {
2630         DBusMessage *m = NULL, *reply = NULL;
2631         int r, ret = 0;
2632         DBusError error;
2633         unsigned i;
2634         bool show_properties, new_line = false;
2635
2636         assert(bus);
2637         assert(args);
2638
2639         dbus_error_init(&error);
2640
2641         show_properties = !streq(args[0], "status");
2642
2643         if (show_properties)
2644                 pager_open_if_enabled();
2645
2646         if (show_properties && n <= 1) {
2647                 /* If not argument is specified inspect the manager
2648                  * itself */
2649
2650                 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2651                 goto finish;
2652         }
2653
2654         for (i = 1; i < n; i++) {
2655                 const char *path = NULL;
2656                 uint32_t id;
2657
2658                 if (safe_atou32(args[i], &id) < 0) {
2659
2660                         /* Interpret as unit name */
2661
2662                         if (!(m = dbus_message_new_method_call(
2663                                               "org.freedesktop.systemd1",
2664                                               "/org/freedesktop/systemd1",
2665                                               "org.freedesktop.systemd1.Manager",
2666                                               "LoadUnit"))) {
2667                                 log_error("Could not allocate message.");
2668                                 ret = -ENOMEM;
2669                                 goto finish;
2670                         }
2671
2672                         if (!dbus_message_append_args(m,
2673                                                       DBUS_TYPE_STRING, &args[i],
2674                                                       DBUS_TYPE_INVALID)) {
2675                                 log_error("Could not append arguments to message.");
2676                                 ret = -ENOMEM;
2677                                 goto finish;
2678                         }
2679
2680                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2681
2682                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2683                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2684                                         ret = -EIO;
2685                                         goto finish;
2686                                 }
2687
2688                                 dbus_error_free(&error);
2689
2690                                 dbus_message_unref(m);
2691                                 if (!(m = dbus_message_new_method_call(
2692                                                       "org.freedesktop.systemd1",
2693                                                       "/org/freedesktop/systemd1",
2694                                                       "org.freedesktop.systemd1.Manager",
2695                                                       "GetUnit"))) {
2696                                         log_error("Could not allocate message.");
2697                                         ret = -ENOMEM;
2698                                         goto finish;
2699                                 }
2700
2701                                 if (!dbus_message_append_args(m,
2702                                                               DBUS_TYPE_STRING, &args[i],
2703                                                               DBUS_TYPE_INVALID)) {
2704                                         log_error("Could not append arguments to message.");
2705                                         ret = -ENOMEM;
2706                                         goto finish;
2707                                 }
2708
2709                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2710                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2711
2712                                         if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2713                                                 ret = 4; /* According to LSB: "program or service status is unknown" */
2714                                         else
2715                                                 ret = -EIO;
2716                                         goto finish;
2717                                 }
2718                         }
2719
2720                 } else if (show_properties) {
2721
2722                         /* Interpret as job id */
2723
2724                         if (!(m = dbus_message_new_method_call(
2725                                               "org.freedesktop.systemd1",
2726                                               "/org/freedesktop/systemd1",
2727                                               "org.freedesktop.systemd1.Manager",
2728                                               "GetJob"))) {
2729                                 log_error("Could not allocate message.");
2730                                 ret = -ENOMEM;
2731                                 goto finish;
2732                         }
2733
2734                         if (!dbus_message_append_args(m,
2735                                                       DBUS_TYPE_UINT32, &id,
2736                                                       DBUS_TYPE_INVALID)) {
2737                                 log_error("Could not append arguments to message.");
2738                                 ret = -ENOMEM;
2739                                 goto finish;
2740                         }
2741
2742                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2743                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2744                                 ret = -EIO;
2745                                 goto finish;
2746                         }
2747                 } else {
2748
2749                         /* Interpret as PID */
2750
2751                         if (!(m = dbus_message_new_method_call(
2752                                               "org.freedesktop.systemd1",
2753                                               "/org/freedesktop/systemd1",
2754                                               "org.freedesktop.systemd1.Manager",
2755                                               "GetUnitByPID"))) {
2756                                 log_error("Could not allocate message.");
2757                                 ret = -ENOMEM;
2758                                 goto finish;
2759                         }
2760
2761                         if (!dbus_message_append_args(m,
2762                                                       DBUS_TYPE_UINT32, &id,
2763                                                       DBUS_TYPE_INVALID)) {
2764                                 log_error("Could not append arguments to message.");
2765                                 ret = -ENOMEM;
2766                                 goto finish;
2767                         }
2768
2769                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2770                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2771                                 ret = -EIO;
2772                                 goto finish;
2773                         }
2774                 }
2775
2776                 if (!dbus_message_get_args(reply, &error,
2777                                            DBUS_TYPE_OBJECT_PATH, &path,
2778                                            DBUS_TYPE_INVALID)) {
2779                         log_error("Failed to parse reply: %s", bus_error_message(&error));
2780                         ret = -EIO;
2781                         goto finish;
2782                 }
2783
2784                 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2785                         ret = r;
2786
2787                 dbus_message_unref(m);
2788                 dbus_message_unref(reply);
2789                 m = reply = NULL;
2790         }
2791
2792 finish:
2793         if (m)
2794                 dbus_message_unref(m);
2795
2796         if (reply)
2797                 dbus_message_unref(reply);
2798
2799         dbus_error_free(&error);
2800
2801         return ret;
2802 }
2803
2804 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2805         DBusError error;
2806         DBusMessage *m = NULL, *reply = NULL;
2807
2808         assert(connection);
2809         assert(message);
2810
2811         dbus_error_init(&error);
2812
2813         log_debug("Got D-Bus request: %s.%s() on %s",
2814                   dbus_message_get_interface(message),
2815                   dbus_message_get_member(message),
2816                   dbus_message_get_path(message));
2817
2818         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2819                 log_error("Warning! D-Bus connection terminated.");
2820                 dbus_connection_close(connection);
2821
2822         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2823                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2824                 const char *id, *path;
2825
2826                 if (!dbus_message_get_args(message, &error,
2827                                            DBUS_TYPE_STRING, &id,
2828                                            DBUS_TYPE_OBJECT_PATH, &path,
2829                                            DBUS_TYPE_INVALID))
2830                         log_error("Failed to parse message: %s", bus_error_message(&error));
2831                 else if (streq(dbus_message_get_member(message), "UnitNew"))
2832                         printf("Unit %s added.\n", id);
2833                 else
2834                         printf("Unit %s removed.\n", id);
2835
2836         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew")) {
2837                 uint32_t id;
2838                 const char *path;
2839
2840                 if (!dbus_message_get_args(message, &error,
2841                                            DBUS_TYPE_UINT32, &id,
2842                                            DBUS_TYPE_OBJECT_PATH, &path,
2843                                            DBUS_TYPE_INVALID))
2844                         log_error("Failed to parse message: %s", bus_error_message(&error));
2845                 else
2846                         printf("Job %u added.\n", id);
2847
2848
2849         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2850                 uint32_t id;
2851                 const char *path, *result;
2852
2853                 if (!dbus_message_get_args(message, &error,
2854                                            DBUS_TYPE_UINT32, &id,
2855                                            DBUS_TYPE_OBJECT_PATH, &path,
2856                                            DBUS_TYPE_STRING, &result,
2857                                            DBUS_TYPE_INVALID))
2858                         log_error("Failed to parse message: %s", bus_error_message(&error));
2859                 else
2860                         printf("Job %u removed (result=%s).\n", id, result);
2861
2862
2863         } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2864
2865                 const char *path, *interface, *property = "Id";
2866                 DBusMessageIter iter, sub;
2867
2868                 path = dbus_message_get_path(message);
2869
2870                 if (!dbus_message_get_args(message, &error,
2871                                           DBUS_TYPE_STRING, &interface,
2872                                           DBUS_TYPE_INVALID)) {
2873                         log_error("Failed to parse message: %s", bus_error_message(&error));
2874                         goto finish;
2875                 }
2876
2877                 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2878                     !streq(interface, "org.freedesktop.systemd1.Unit"))
2879                         goto finish;
2880
2881                 if (!(m = dbus_message_new_method_call(
2882                               "org.freedesktop.systemd1",
2883                               path,
2884                               "org.freedesktop.DBus.Properties",
2885                               "Get"))) {
2886                         log_error("Could not allocate message.");
2887                         goto oom;
2888                 }
2889
2890                 if (!dbus_message_append_args(m,
2891                                               DBUS_TYPE_STRING, &interface,
2892                                               DBUS_TYPE_STRING, &property,
2893                                               DBUS_TYPE_INVALID)) {
2894                         log_error("Could not append arguments to message.");
2895                         goto finish;
2896                 }
2897
2898                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2899                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2900                         goto finish;
2901                 }
2902
2903                 if (!dbus_message_iter_init(reply, &iter) ||
2904                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2905                         log_error("Failed to parse reply.");
2906                         goto finish;
2907                 }
2908
2909                 dbus_message_iter_recurse(&iter, &sub);
2910
2911                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2912                         const char *id;
2913
2914                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2915                                 log_error("Failed to parse reply.");
2916                                 goto finish;
2917                         }
2918
2919                         dbus_message_iter_get_basic(&sub, &id);
2920                         printf("Unit %s changed.\n", id);
2921                 } else {
2922                         uint32_t id;
2923
2924                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2925                                 log_error("Failed to parse reply.");
2926                                 goto finish;
2927                         }
2928
2929                         dbus_message_iter_get_basic(&sub, &id);
2930                         printf("Job %u changed.\n", id);
2931                 }
2932         }
2933
2934 finish:
2935         if (m)
2936                 dbus_message_unref(m);
2937
2938         if (reply)
2939                 dbus_message_unref(reply);
2940
2941         dbus_error_free(&error);
2942         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2943
2944 oom:
2945         if (m)
2946                 dbus_message_unref(m);
2947
2948         if (reply)
2949                 dbus_message_unref(reply);
2950
2951         dbus_error_free(&error);
2952         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2953 }
2954
2955 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2956         DBusMessage *m = NULL, *reply = NULL;
2957         DBusError error;
2958         int r;
2959
2960         dbus_error_init(&error);
2961
2962         if (!private_bus) {
2963                 dbus_bus_add_match(bus,
2964                                    "type='signal',"
2965                                    "sender='org.freedesktop.systemd1',"
2966                                    "interface='org.freedesktop.systemd1.Manager',"
2967                                    "path='/org/freedesktop/systemd1'",
2968                                    &error);
2969
2970                 if (dbus_error_is_set(&error)) {
2971                         log_error("Failed to add match: %s", bus_error_message(&error));
2972                         r = -EIO;
2973                         goto finish;
2974                 }
2975
2976                 dbus_bus_add_match(bus,
2977                                    "type='signal',"
2978                                    "sender='org.freedesktop.systemd1',"
2979                                    "interface='org.freedesktop.DBus.Properties',"
2980                                    "member='PropertiesChanged'",
2981                                    &error);
2982
2983                 if (dbus_error_is_set(&error)) {
2984                         log_error("Failed to add match: %s", bus_error_message(&error));
2985                         r = -EIO;
2986                         goto finish;
2987                 }
2988         }
2989
2990         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2991                 log_error("Failed to add filter.");
2992                 r = -ENOMEM;
2993                 goto finish;
2994         }
2995
2996         if (!(m = dbus_message_new_method_call(
2997                               "org.freedesktop.systemd1",
2998                               "/org/freedesktop/systemd1",
2999                               "org.freedesktop.systemd1.Manager",
3000                               "Subscribe"))) {
3001                 log_error("Could not allocate message.");
3002                 r = -ENOMEM;
3003                 goto finish;
3004         }
3005
3006         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3007                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3008                 r = -EIO;
3009                 goto finish;
3010         }
3011
3012         while (dbus_connection_read_write_dispatch(bus, -1))
3013                 ;
3014
3015         r = 0;
3016
3017 finish:
3018
3019         /* This is slightly dirty, since we don't undo the filter or the matches. */
3020
3021         if (m)
3022                 dbus_message_unref(m);
3023
3024         if (reply)
3025                 dbus_message_unref(reply);
3026
3027         dbus_error_free(&error);
3028
3029         return r;
3030 }
3031
3032 static int dump(DBusConnection *bus, char **args, unsigned n) {
3033         DBusMessage *m = NULL, *reply = NULL;
3034         DBusError error;
3035         int r;
3036         const char *text;
3037
3038         dbus_error_init(&error);
3039
3040         pager_open_if_enabled();
3041
3042         if (!(m = dbus_message_new_method_call(
3043                               "org.freedesktop.systemd1",
3044                               "/org/freedesktop/systemd1",
3045                               "org.freedesktop.systemd1.Manager",
3046                               "Dump"))) {
3047                 log_error("Could not allocate message.");
3048                 return -ENOMEM;
3049         }
3050
3051         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3052                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3053                 r = -EIO;
3054                 goto finish;
3055         }
3056
3057         if (!dbus_message_get_args(reply, &error,
3058                                    DBUS_TYPE_STRING, &text,
3059                                    DBUS_TYPE_INVALID)) {
3060                 log_error("Failed to parse reply: %s", bus_error_message(&error));
3061                 r = -EIO;
3062                 goto finish;
3063         }
3064
3065         fputs(text, stdout);
3066
3067         r = 0;
3068
3069 finish:
3070         if (m)
3071                 dbus_message_unref(m);
3072
3073         if (reply)
3074                 dbus_message_unref(reply);
3075
3076         dbus_error_free(&error);
3077
3078         return r;
3079 }
3080
3081 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3082         DBusMessage *m = NULL, *reply = NULL;
3083         DBusError error;
3084         int r;
3085         const char *name = "", *path, *id;
3086         dbus_bool_t cleanup = FALSE;
3087         DBusMessageIter iter, sub;
3088         const char
3089                 *interface = "org.freedesktop.systemd1.Unit",
3090                 *property = "Id";
3091
3092         dbus_error_init(&error);
3093
3094         if (!(m = dbus_message_new_method_call(
3095                               "org.freedesktop.systemd1",
3096                               "/org/freedesktop/systemd1",
3097                               "org.freedesktop.systemd1.Manager",
3098                               "CreateSnapshot"))) {
3099                 log_error("Could not allocate message.");
3100                 return -ENOMEM;
3101         }
3102
3103         if (n > 1)
3104                 name = args[1];
3105
3106         if (!dbus_message_append_args(m,
3107                                       DBUS_TYPE_STRING, &name,
3108                                       DBUS_TYPE_BOOLEAN, &cleanup,
3109                                       DBUS_TYPE_INVALID)) {
3110                 log_error("Could not append arguments to message.");
3111                 r = -ENOMEM;
3112                 goto finish;
3113         }
3114
3115         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3116                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3117                 r = -EIO;
3118                 goto finish;
3119         }
3120
3121         if (!dbus_message_get_args(reply, &error,
3122                                    DBUS_TYPE_OBJECT_PATH, &path,
3123                                    DBUS_TYPE_INVALID)) {
3124                 log_error("Failed to parse reply: %s", bus_error_message(&error));
3125                 r = -EIO;
3126                 goto finish;
3127         }
3128
3129         dbus_message_unref(m);
3130         if (!(m = dbus_message_new_method_call(
3131                               "org.freedesktop.systemd1",
3132                               path,
3133                               "org.freedesktop.DBus.Properties",
3134                               "Get"))) {
3135                 log_error("Could not allocate message.");
3136                 return -ENOMEM;
3137         }
3138
3139         if (!dbus_message_append_args(m,
3140                                       DBUS_TYPE_STRING, &interface,
3141                                       DBUS_TYPE_STRING, &property,
3142                                       DBUS_TYPE_INVALID)) {
3143                 log_error("Could not append arguments to message.");
3144                 r = -ENOMEM;
3145                 goto finish;
3146         }
3147
3148         dbus_message_unref(reply);
3149         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3150                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3151                 r = -EIO;
3152                 goto finish;
3153         }
3154
3155         if (!dbus_message_iter_init(reply, &iter) ||
3156             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3157                 log_error("Failed to parse reply.");
3158                 r = -EIO;
3159                 goto finish;
3160         }
3161
3162         dbus_message_iter_recurse(&iter, &sub);
3163
3164         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
3165                 log_error("Failed to parse reply.");
3166                 r = -EIO;
3167                 goto finish;
3168         }
3169
3170         dbus_message_iter_get_basic(&sub, &id);
3171
3172         if (!arg_quiet)
3173                 puts(id);
3174         r = 0;
3175
3176 finish:
3177         if (m)
3178                 dbus_message_unref(m);
3179
3180         if (reply)
3181                 dbus_message_unref(reply);
3182
3183         dbus_error_free(&error);
3184
3185         return r;
3186 }
3187
3188 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3189         DBusMessage *m = NULL, *reply = NULL;
3190         int r;
3191         DBusError error;
3192         unsigned i;
3193
3194         assert(bus);
3195         assert(args);
3196
3197         dbus_error_init(&error);
3198
3199         for (i = 1; i < n; i++) {
3200                 const char *path = NULL;
3201
3202                 if (!(m = dbus_message_new_method_call(
3203                                       "org.freedesktop.systemd1",
3204                                       "/org/freedesktop/systemd1",
3205                                       "org.freedesktop.systemd1.Manager",
3206                                       "GetUnit"))) {
3207                         log_error("Could not allocate message.");
3208                         r = -ENOMEM;
3209                         goto finish;
3210                 }
3211
3212                 if (!dbus_message_append_args(m,
3213                                               DBUS_TYPE_STRING, &args[i],
3214                                               DBUS_TYPE_INVALID)) {
3215                         log_error("Could not append arguments to message.");
3216                         r = -ENOMEM;
3217                         goto finish;
3218                 }
3219
3220                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3221                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3222                         r = -EIO;
3223                         goto finish;
3224                 }
3225
3226                 if (!dbus_message_get_args(reply, &error,
3227                                            DBUS_TYPE_OBJECT_PATH, &path,
3228                                            DBUS_TYPE_INVALID)) {
3229                         log_error("Failed to parse reply: %s", bus_error_message(&error));
3230                         r = -EIO;
3231                         goto finish;
3232                 }
3233
3234                 dbus_message_unref(m);
3235                 if (!(m = dbus_message_new_method_call(
3236                                       "org.freedesktop.systemd1",
3237                                       path,
3238                                       "org.freedesktop.systemd1.Snapshot",
3239                                       "Remove"))) {
3240                         log_error("Could not allocate message.");
3241                         r = -ENOMEM;
3242                         goto finish;
3243                 }
3244
3245                 dbus_message_unref(reply);
3246                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3247                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3248                         r = -EIO;
3249                         goto finish;
3250                 }
3251
3252                 dbus_message_unref(m);
3253                 dbus_message_unref(reply);
3254                 m = reply = NULL;
3255         }
3256
3257         r = 0;
3258
3259 finish:
3260         if (m)
3261                 dbus_message_unref(m);
3262
3263         if (reply)
3264                 dbus_message_unref(reply);
3265
3266         dbus_error_free(&error);
3267
3268         return r;
3269 }
3270
3271 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3272         DBusMessage *m = NULL, *reply = NULL;
3273         DBusError error;
3274         int r;
3275         const char *method;
3276
3277         dbus_error_init(&error);
3278
3279         if (arg_action == ACTION_RELOAD)
3280                 method = "Reload";
3281         else if (arg_action == ACTION_REEXEC)
3282                 method = "Reexecute";
3283         else {
3284                 assert(arg_action == ACTION_SYSTEMCTL);
3285
3286                 method =
3287                         streq(args[0], "clear-jobs")    ||
3288                         streq(args[0], "cancel")        ? "ClearJobs" :
3289                         streq(args[0], "daemon-reexec") ? "Reexecute" :
3290                         streq(args[0], "reset-failed")  ? "ResetFailed" :
3291                         streq(args[0], "halt")          ? "Halt" :
3292                         streq(args[0], "poweroff")      ? "PowerOff" :
3293                         streq(args[0], "reboot")        ? "Reboot" :
3294                         streq(args[0], "kexec")         ? "KExec" :
3295                         streq(args[0], "exit")          ? "Exit" :
3296                                     /* "daemon-reload" */ "Reload";
3297         }
3298
3299         if (!(m = dbus_message_new_method_call(
3300                               "org.freedesktop.systemd1",
3301                               "/org/freedesktop/systemd1",
3302                               "org.freedesktop.systemd1.Manager",
3303                               method))) {
3304                 log_error("Could not allocate message.");
3305                 return -ENOMEM;
3306         }
3307
3308         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3309
3310                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3311                         /* There's always a fallback possible for
3312                          * legacy actions. */
3313                         r = -EADDRNOTAVAIL;
3314                         goto finish;
3315                 }
3316
3317                 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3318                         /* On reexecution, we expect a disconnect, not
3319                          * a reply */
3320                         r = 0;
3321                         goto finish;
3322                 }
3323
3324                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3325                 r = -EIO;
3326                 goto finish;
3327         }
3328
3329         r = 0;
3330
3331 finish:
3332         if (m)
3333                 dbus_message_unref(m);
3334
3335         if (reply)
3336                 dbus_message_unref(reply);
3337
3338         dbus_error_free(&error);
3339
3340         return r;
3341 }
3342
3343 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3344         DBusMessage *m = NULL, *reply = NULL;
3345         unsigned i;
3346         int r;
3347         DBusError error;
3348
3349         assert(bus);
3350         dbus_error_init(&error);
3351
3352         if (n <= 1)
3353                 return daemon_reload(bus, args, n);
3354
3355         for (i = 1; i < n; i++) {
3356
3357                 if (!(m = dbus_message_new_method_call(
3358                                       "org.freedesktop.systemd1",
3359                                       "/org/freedesktop/systemd1",
3360                                       "org.freedesktop.systemd1.Manager",
3361                                       "ResetFailedUnit"))) {
3362                         log_error("Could not allocate message.");
3363                         r = -ENOMEM;
3364                         goto finish;
3365                 }
3366
3367                 if (!dbus_message_append_args(m,
3368                                               DBUS_TYPE_STRING, args + i,
3369                                               DBUS_TYPE_INVALID)) {
3370                         log_error("Could not append arguments to message.");
3371                         r = -ENOMEM;
3372                         goto finish;
3373                 }
3374
3375                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3376                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3377                         r = -EIO;
3378                         goto finish;
3379                 }
3380
3381                 dbus_message_unref(m);
3382                 dbus_message_unref(reply);
3383                 m = reply = NULL;
3384         }
3385
3386         r = 0;
3387
3388 finish:
3389         if (m)
3390                 dbus_message_unref(m);
3391
3392         if (reply)
3393                 dbus_message_unref(reply);
3394
3395         dbus_error_free(&error);
3396
3397         return r;
3398 }
3399
3400 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3401         DBusMessage *m = NULL, *reply = NULL;
3402         DBusError error;
3403         DBusMessageIter iter, sub, sub2;
3404         int r;
3405         const char
3406                 *interface = "org.freedesktop.systemd1.Manager",
3407                 *property = "Environment";
3408
3409         dbus_error_init(&error);
3410
3411         pager_open_if_enabled();
3412
3413         if (!(m = dbus_message_new_method_call(
3414                               "org.freedesktop.systemd1",
3415                               "/org/freedesktop/systemd1",
3416                               "org.freedesktop.DBus.Properties",
3417                               "Get"))) {
3418                 log_error("Could not allocate message.");
3419                 return -ENOMEM;
3420         }
3421
3422         if (!dbus_message_append_args(m,
3423                                       DBUS_TYPE_STRING, &interface,
3424                                       DBUS_TYPE_STRING, &property,
3425                                       DBUS_TYPE_INVALID)) {
3426                 log_error("Could not append arguments to message.");
3427                 r = -ENOMEM;
3428                 goto finish;
3429         }
3430
3431         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3432                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3433                 r = -EIO;
3434                 goto finish;
3435         }
3436
3437         if (!dbus_message_iter_init(reply, &iter) ||
3438             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3439                 log_error("Failed to parse reply.");
3440                 r = -EIO;
3441                 goto finish;
3442         }
3443
3444         dbus_message_iter_recurse(&iter, &sub);
3445
3446         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3447             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
3448                 log_error("Failed to parse reply.");
3449                 r = -EIO;
3450                 goto finish;
3451         }
3452
3453         dbus_message_iter_recurse(&sub, &sub2);
3454
3455         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3456                 const char *text;
3457
3458                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3459                         log_error("Failed to parse reply.");
3460                         r = -EIO;
3461                         goto finish;
3462                 }
3463
3464                 dbus_message_iter_get_basic(&sub2, &text);
3465                 printf("%s\n", text);
3466
3467                 dbus_message_iter_next(&sub2);
3468         }
3469
3470         r = 0;
3471
3472 finish:
3473         if (m)
3474                 dbus_message_unref(m);
3475
3476         if (reply)
3477                 dbus_message_unref(reply);
3478
3479         dbus_error_free(&error);
3480
3481         return r;
3482 }
3483
3484 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3485         DBusMessage *m = NULL, *reply = NULL;
3486         DBusError error;
3487         int r;
3488         const char *method;
3489         DBusMessageIter iter, sub;
3490         unsigned i;
3491
3492         dbus_error_init(&error);
3493
3494         method = streq(args[0], "set-environment")
3495                 ? "SetEnvironment"
3496                 : "UnsetEnvironment";
3497
3498         if (!(m = dbus_message_new_method_call(
3499                               "org.freedesktop.systemd1",
3500                               "/org/freedesktop/systemd1",
3501                               "org.freedesktop.systemd1.Manager",
3502                               method))) {
3503
3504                 log_error("Could not allocate message.");
3505                 return -ENOMEM;
3506         }
3507
3508         dbus_message_iter_init_append(m, &iter);
3509
3510         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3511                 log_error("Could not append arguments to message.");
3512                 r = -ENOMEM;
3513                 goto finish;
3514         }
3515
3516         for (i = 1; i < n; i++)
3517                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3518                         log_error("Could not append arguments to message.");
3519                         r = -ENOMEM;
3520                         goto finish;
3521                 }
3522
3523         if (!dbus_message_iter_close_container(&iter, &sub)) {
3524                 log_error("Could not append arguments to message.");
3525                 r = -ENOMEM;
3526                 goto finish;
3527         }
3528
3529         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3530                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3531                 r = -EIO;
3532                 goto finish;
3533         }
3534
3535         r = 0;
3536
3537 finish:
3538         if (m)
3539                 dbus_message_unref(m);
3540
3541         if (reply)
3542                 dbus_message_unref(reply);
3543
3544         dbus_error_free(&error);
3545
3546         return r;
3547 }
3548
3549 typedef struct {
3550         char *name;
3551         char *path;
3552
3553         char **aliases;
3554         char **wanted_by;
3555 } InstallInfo;
3556
3557 static Hashmap *will_install = NULL, *have_installed = NULL;
3558 static Set *remove_symlinks_to = NULL;
3559 static unsigned n_symlinks = 0;
3560
3561 static void install_info_free(InstallInfo *i) {
3562         assert(i);
3563
3564         free(i->name);
3565         free(i->path);
3566         strv_free(i->aliases);
3567         strv_free(i->wanted_by);
3568         free(i);
3569 }
3570
3571 static void install_info_hashmap_free(Hashmap *m) {
3572         InstallInfo *i;
3573
3574         while ((i = hashmap_steal_first(m)))
3575                 install_info_free(i);
3576
3577         hashmap_free(m);
3578 }
3579
3580 static int install_info_add(const char *name) {
3581         InstallInfo *i;
3582         int r;
3583
3584         assert(will_install);
3585
3586         if (!unit_name_is_valid_no_type(name, true)) {
3587                 log_warning("Unit name %s is not a valid unit name.", name);
3588                 return -EINVAL;
3589         }
3590
3591         if (hashmap_get(have_installed, name) ||
3592             hashmap_get(will_install, name))
3593                 return 0;
3594
3595         if (!(i = new0(InstallInfo, 1))) {
3596                 r = -ENOMEM;
3597                 goto fail;
3598         }
3599
3600         if (!(i->name = strdup(name))) {
3601                 r = -ENOMEM;
3602                 goto fail;
3603         }
3604
3605         if ((r = hashmap_put(will_install, i->name, i)) < 0)
3606                 goto fail;
3607
3608         return 0;
3609
3610 fail:
3611         if (i)
3612                 install_info_free(i);
3613
3614         return r;
3615 }
3616
3617 static int config_parse_also(
3618                 const char *filename,
3619                 unsigned line,
3620                 const char *section,
3621                 const char *lvalue,
3622                 int ltype,
3623                 const char *rvalue,
3624                 void *data,
3625                 void *userdata) {
3626
3627         char *w;
3628         size_t l;
3629         char *state;
3630
3631         assert(filename);
3632         assert(lvalue);
3633         assert(rvalue);
3634
3635         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3636                 char *n;
3637                 int r;
3638
3639                 if (!(n = strndup(w, l)))
3640                         return -ENOMEM;
3641
3642                 if ((r = install_info_add(n)) < 0) {
3643                         log_warning("Cannot install unit %s: %s", n, strerror(-r));
3644                         free(n);
3645                         return r;
3646                 }
3647
3648                 free(n);
3649         }
3650
3651         return 0;
3652 }
3653
3654 static int mark_symlink_for_removal(const char *p) {
3655         char *n;
3656         int r;
3657
3658         assert(p);
3659         assert(path_is_absolute(p));
3660
3661         if (!remove_symlinks_to)
3662                 return 0;
3663
3664         if (!(n = strdup(p)))
3665                 return -ENOMEM;
3666
3667         path_kill_slashes(n);
3668
3669         if ((r = set_put(remove_symlinks_to, n)) < 0) {
3670                 free(n);
3671                 return r == -EEXIST ? 0 : r;
3672         }
3673
3674         return 0;
3675 }
3676
3677 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3678         int r = 0;
3679         DIR *d;
3680         struct dirent *de;
3681
3682         assert(fd >= 0);
3683         assert(root);
3684         assert(deleted);
3685
3686         if (!(d = fdopendir(fd))) {
3687                 close_nointr_nofail(fd);
3688                 return -errno;
3689         }
3690
3691         rewinddir(d);
3692
3693         while ((de = readdir(d))) {
3694                 bool is_dir = false, is_link = false;
3695
3696                 if (ignore_file(de->d_name))
3697                         continue;
3698
3699                 if (de->d_type == DT_LNK)
3700                         is_link = true;
3701                 else if (de->d_type == DT_DIR)
3702                         is_dir = true;
3703                 else if (de->d_type == DT_UNKNOWN) {
3704                         struct stat st;
3705
3706                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3707                                 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3708
3709                                 if (r == 0)
3710                                         r = -errno;
3711                                 continue;
3712                         }
3713
3714                         is_link = S_ISLNK(st.st_mode);
3715                         is_dir = S_ISDIR(st.st_mode);
3716                 } else
3717                         continue;
3718
3719                 if (is_dir) {
3720                         int nfd, q;
3721                         char *p;
3722
3723                         if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3724                                 log_error("Failed to open %s/%s: %m", root, de->d_name);
3725
3726                                 if (r == 0)
3727                                         r = -errno;
3728                                 continue;
3729                         }
3730
3731                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3732                                 log_error("Failed to allocate directory string.");
3733                                 close_nointr_nofail(nfd);
3734                                 r = -ENOMEM;
3735                                 break;
3736                         }
3737
3738                         /* This will close nfd, regardless whether it succeeds or not */
3739                         q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3740                         free(p);
3741
3742                         if (r == 0)
3743                                 r = q;
3744
3745                 } else if (is_link) {
3746                         char *p, *dest, *c;
3747                         int q;
3748
3749                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3750                                 log_error("Failed to allocate symlink string.");
3751                                 r = -ENOMEM;
3752                                 break;
3753                         }
3754
3755                         if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3756                                 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3757                                 free(p);
3758
3759                                 if (r == 0)
3760                                         r = q;
3761                                 continue;
3762                         }
3763
3764                         if ((c = canonicalize_file_name(dest))) {
3765                                 /* This might fail if the destination
3766                                  * is already removed */
3767
3768                                 free(dest);
3769                                 dest = c;
3770                         }
3771
3772                         path_kill_slashes(dest);
3773                         if (set_get(remove_symlinks_to, dest)) {
3774
3775                                 if (!arg_quiet)
3776                                         log_info("rm '%s'", p);
3777
3778                                 if (unlink(p) < 0) {
3779                                         log_error("Cannot unlink symlink %s: %m", p);
3780
3781                                         if (r == 0)
3782                                                 r = -errno;
3783                                 } else {
3784                                         rmdir_parents(p, config_path);
3785                                         path_kill_slashes(p);
3786
3787                                         if (!set_get(remove_symlinks_to, p)) {
3788
3789                                                 if ((r = mark_symlink_for_removal(p)) < 0) {
3790                                                         if (r == 0)
3791                                                                 r = q;
3792                                                 } else
3793                                                         *deleted = true;
3794                                         }
3795                                 }
3796                         }
3797
3798                         free(p);
3799                         free(dest);
3800                 }
3801         }
3802
3803         closedir(d);
3804
3805         return r;
3806 }
3807
3808 static int remove_marked_symlinks(const char *config_path) {
3809         int fd, r = 0;
3810         bool deleted;
3811
3812         assert(config_path);
3813
3814         if (set_size(remove_symlinks_to) <= 0)
3815                 return 0;
3816
3817         if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3818                 return -errno;
3819
3820         do {
3821                 int q, cfd;
3822                 deleted = false;
3823
3824                 if ((cfd = dup(fd)) < 0) {
3825                         r = -errno;
3826                         break;
3827                 }
3828
3829                 /* This takes possession of cfd and closes it */
3830                 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3831                         if (r == 0)
3832                                 r = q;
3833                 }
3834         } while (deleted);
3835
3836         close_nointr_nofail(fd);
3837
3838         return r;
3839 }
3840
3841 static int create_symlink(const char *verb, const char *orig_old_path, const char *new_path) {
3842         int r;
3843         const char *old_path;
3844
3845         if (arg_root)
3846                 old_path = orig_old_path+strlen(arg_root);
3847         else
3848                 old_path = orig_old_path;
3849
3850         assert(old_path);
3851         assert(new_path);
3852         assert(verb);
3853
3854         if (streq(verb, "enable")) {
3855                 char *dest;
3856
3857                 mkdir_parents(new_path, 0755);
3858
3859                 if (symlink(old_path, new_path) >= 0) {
3860
3861                         if (!arg_quiet)
3862                                 log_info("ln -s '%s' '%s'", old_path, new_path);
3863
3864                         return 0;
3865                 }
3866
3867                 if (errno != EEXIST) {
3868                         log_error("Cannot link %s to %s: %m", old_path, new_path);
3869                         return -errno;
3870                 }
3871
3872                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3873
3874                         if (errno == EINVAL) {
3875                                 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3876                                 return -EEXIST;
3877                         }
3878
3879                         log_error("readlink() failed: %s", strerror(-r));
3880                         return r;
3881                 }
3882
3883                 if (streq(dest, old_path)) {
3884                         free(dest);
3885                         return 0;
3886                 }
3887
3888                 if (!arg_force) {
3889                         log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3890                         free(dest);
3891                         return -EEXIST;
3892                 }
3893
3894                 free(dest);
3895                 unlink(new_path);
3896
3897                 if (!arg_quiet)
3898                         log_info("ln -s '%s' '%s'", old_path, new_path);
3899
3900                 if (symlink(old_path, new_path) >= 0)
3901                         return 0;
3902
3903                 log_error("Cannot link %s to %s: %m", old_path, new_path);
3904                 return -errno;
3905
3906         } else if (streq(verb, "disable")) {
3907                 char *dest;
3908
3909                 if ((r = mark_symlink_for_removal(old_path)) < 0)
3910                         return r;
3911
3912                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3913                         if (errno == ENOENT)
3914                                 return 0;
3915
3916                         if (errno == EINVAL) {
3917                                 log_warning("File %s not a symlink, ignoring.", old_path);
3918                                 return 0;
3919                         }
3920
3921                         log_error("readlink() failed: %s", strerror(-r));
3922                         return r;
3923                 }
3924
3925                 if (!streq(dest, old_path)) {
3926                         log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3927                         free(dest);
3928                         return 0;
3929                 }
3930
3931                 free(dest);
3932
3933                 if ((r = mark_symlink_for_removal(new_path)) < 0)
3934                         return r;
3935
3936                 if (!arg_quiet)
3937                         log_info("rm '%s'", new_path);
3938
3939                 if (unlink(new_path) >= 0)
3940                         return 0;
3941
3942                 log_error("Cannot unlink %s: %m", new_path);
3943                 return -errno;
3944
3945         } else if (streq(verb, "is-enabled")) {
3946                 char *dest;
3947
3948                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3949
3950                         if (errno == ENOENT || errno == EINVAL)
3951                                 return 0;
3952
3953                         log_error("readlink() failed: %s", strerror(-r));
3954                         return r;
3955                 }
3956
3957                 if (streq(dest, old_path)) {
3958                         free(dest);
3959                         return 1;
3960                 }
3961
3962                 free(dest);
3963                 return 0;
3964         }
3965
3966         assert_not_reached("Unknown action.");
3967 }
3968
3969 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3970         char **s;
3971         char *alias_path = NULL;
3972         int r;
3973
3974         assert(verb);
3975         assert(i);
3976         assert(config_path);
3977
3978         STRV_FOREACH(s, i->aliases) {
3979
3980                 free(alias_path);
3981                 if (!(alias_path = path_make_absolute(*s, config_path))) {
3982                         log_error("Out of memory");
3983                         r = -ENOMEM;
3984                         goto finish;
3985                 }
3986
3987                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3988                         goto finish;
3989
3990                 if (streq(verb, "disable"))
3991                         rmdir_parents(alias_path, config_path);
3992         }
3993         r = 0;
3994
3995 finish:
3996         free(alias_path);
3997
3998         return r;
3999 }
4000
4001 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
4002         char **s;
4003         char *alias_path = NULL;
4004         int r;
4005
4006         assert(verb);
4007         assert(i);
4008         assert(config_path);
4009
4010         STRV_FOREACH(s, i->wanted_by) {
4011                 if (!unit_name_is_valid_no_type(*s, true)) {
4012                         log_error("Invalid name %s.", *s);
4013                         r = -EINVAL;
4014                         goto finish;
4015                 }
4016
4017                 free(alias_path);
4018                 alias_path = NULL;
4019
4020                 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
4021                         log_error("Out of memory");
4022                         r = -ENOMEM;
4023                         goto finish;
4024                 }
4025
4026                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4027                         goto finish;
4028
4029                 if (streq(verb, "disable"))
4030                         rmdir_parents(alias_path, config_path);
4031         }
4032
4033         r = 0;
4034
4035 finish:
4036         free(alias_path);
4037
4038         return r;
4039 }
4040
4041 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
4042
4043         const ConfigItem items[] = {
4044                 { "Alias",    config_parse_strv, 0, &i->aliases,   "Install" },
4045                 { "WantedBy", config_parse_strv, 0, &i->wanted_by, "Install" },
4046                 { "Also",     config_parse_also, 0, NULL,          "Install" },
4047
4048                 { NULL, NULL, 0, NULL, NULL }
4049         };
4050
4051         char **p;
4052         char *filename = NULL;
4053         FILE *f = NULL;
4054         int r;
4055
4056         assert(paths);
4057         assert(i);
4058
4059         STRV_FOREACH(p, paths->unit_path) {
4060                 int fd;
4061                 char *path, *should_free;
4062
4063                 if (arg_root)
4064                         should_free = path = strappend(arg_root, *p);
4065                 else {
4066                         should_free = NULL;
4067                         path = *p;
4068                 }
4069
4070                 if (!(filename = path_make_absolute(i->name, path))) {
4071                         log_error("Out of memory");
4072                         return -ENOMEM;
4073                 }
4074
4075                 if (should_free)
4076                         free(should_free);
4077
4078                 /* Ensure that we don't follow symlinks */
4079                 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4080                         if ((f = fdopen(fd, "re")))
4081                                 break;
4082
4083                 if (errno == ELOOP) {
4084                         log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4085                         free(filename);
4086                         return -errno;
4087                 }
4088
4089                 if (errno != ENOENT) {
4090                         log_error("Failed to open %s: %m", filename);
4091                         free(filename);
4092                         return -errno;
4093                 }
4094
4095                 free(filename);
4096                 filename = NULL;
4097         }
4098
4099         if (!f) {
4100 #if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX)) && defined (HAVE_SYSV_COMPAT)
4101
4102                 if (endswith(i->name, ".service")) {
4103                         char *sysv;
4104                         bool exists;
4105
4106                         if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4107                                 log_error("Out of memory");
4108                                 return -ENOMEM;
4109                         }
4110
4111                         sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4112                         if (arg_root) {
4113                                 char *tmp_path;
4114
4115                                 tmp_path = strappend (arg_root, sysv);
4116                                 exists = access (tmp_path, F_OK) >= 0;
4117                                 free (tmp_path);
4118                         } else
4119                                 exists = access(sysv, F_OK) >= 0;
4120
4121                         if (exists) {
4122                                 pid_t pid;
4123                                 siginfo_t status;
4124
4125                                 const char *argv[] = {
4126                                         "/sbin/chkconfig",
4127                                         NULL,
4128                                         NULL,
4129                                         NULL,
4130                                         NULL
4131                                 };
4132
4133                                 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4134
4135                                 argv[1] = file_name_from_path(sysv);
4136                                 argv[2] =
4137                                         streq(verb, "enable") ? "on" :
4138                                         streq(verb, "disable") ? "off" : "--level=5";
4139                                 if (arg_root)
4140                                         argv[3] = strappend("--root=", arg_root);
4141
4142                                 log_info("Executing %s %s %s %s", argv[0], argv[1], strempty(argv[2]), strempty(argv[3]));
4143
4144                                 if ((pid = fork()) < 0) {
4145                                         log_error("Failed to fork: %m");
4146                                         free(sysv);
4147                                         return -errno;
4148                                 } else if (pid == 0) {
4149                                         execv(argv[0], (char**) argv);
4150                                         _exit(EXIT_FAILURE);
4151                                 }
4152
4153                                 free(sysv);
4154
4155                                 if ((r = wait_for_terminate(pid, &status)) < 0)
4156                                         return r;
4157
4158                                 if (status.si_code == CLD_EXITED) {
4159
4160                                         if (streq(verb, "is-enabled"))
4161                                                 return status.si_status == 0 ? 1 : 0;
4162
4163                                         if (status.si_status == 0)
4164                                                 n_symlinks ++;
4165
4166                                         return status.si_status == 0 ? 0 : -EINVAL;
4167
4168                                 } else
4169                                         return -EPROTO;
4170                         }
4171
4172                         free(sysv);
4173                 }
4174
4175 #endif
4176
4177                 log_error("Couldn't find %s.", i->name);
4178                 return -ENOENT;
4179         }
4180
4181         i->path = filename;
4182
4183         if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4184                 fclose(f);
4185                 return r;
4186         }
4187
4188         /* Consider unit files stored in /lib and /usr always enabled
4189          * if they have no [Install] data. */
4190         if (streq(verb, "is-enabled") &&
4191             strv_isempty(i->aliases) &&
4192             strv_isempty(i->wanted_by) &&
4193             !path_startswith(filename, "/etc")) {
4194                 fclose(f);
4195                 return 1;
4196         }
4197
4198         n_symlinks += strv_length(i->aliases);
4199         n_symlinks += strv_length(i->wanted_by);
4200
4201         fclose(f);
4202
4203         if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4204                 return r;
4205
4206         if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4207                 return r;
4208
4209         if ((r = mark_symlink_for_removal(filename)) < 0)
4210                 return r;
4211
4212         if ((r = remove_marked_symlinks(config_path)) < 0)
4213                 return r;
4214
4215         return 0;
4216 }
4217
4218 static char *get_config_path(void) {
4219         char *ret;
4220
4221         if (arg_user && arg_global)
4222                 ret = strdup(USER_CONFIG_UNIT_PATH);
4223
4224         if (arg_user) {
4225                 if (user_config_home(&ret) < 0)
4226                         return NULL;
4227         }
4228
4229         ret = strdup(SYSTEM_CONFIG_UNIT_PATH);
4230         if (arg_root) {
4231                 char *p;
4232                 p = strappend (arg_root, ret);
4233                 free (ret);
4234                 return p;
4235         } else
4236                 return ret;
4237 }
4238
4239 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4240         DBusError error;
4241         int r;
4242         LookupPaths paths;
4243         char *config_path = NULL;
4244         unsigned j;
4245         InstallInfo *i;
4246         const char *verb = args[0];
4247
4248         dbus_error_init(&error);
4249
4250         zero(paths);
4251         if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4252                 log_error("Failed to determine lookup paths: %s", strerror(-r));
4253                 goto finish;
4254         }
4255
4256         if (!(config_path = get_config_path())) {
4257                 log_error("Failed to determine config path");
4258                 r = -ENOMEM;
4259                 goto finish;
4260         }
4261
4262         will_install = hashmap_new(string_hash_func, string_compare_func);
4263         have_installed = hashmap_new(string_hash_func, string_compare_func);
4264
4265         if (!will_install || !have_installed) {
4266                 log_error("Failed to allocate unit sets.");
4267                 r = -ENOMEM;
4268                 goto finish;
4269         }
4270
4271         if (!arg_defaults && streq(verb, "disable"))
4272                 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4273                         log_error("Failed to allocate symlink sets.");
4274                         r = -ENOMEM;
4275                         goto finish;
4276                 }
4277
4278         for (j = 1; j < n; j++)
4279                 if ((r = install_info_add(args[j])) < 0) {
4280                         log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4281                         goto finish;
4282                 }
4283
4284         r = 0;
4285
4286         while ((i = hashmap_first(will_install))) {
4287                 int q;
4288
4289                 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4290
4291                 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4292
4293                         if (q < 0) {
4294                                 if (r == 0)
4295                                         r = q;
4296                                 goto finish;
4297                         }
4298
4299                         /* In test mode and found something */
4300                         r = 1;
4301                         break;
4302                 }
4303         }
4304
4305         if (streq(verb, "is-enabled"))
4306                 r = r > 0 ? 0 : -ENOENT;
4307         else {
4308                 if (n_symlinks <= 0)
4309                         log_warning("Unit files contain no applicable installation information. Ignoring.");
4310
4311                 if (bus &&
4312                     /* Don't try to reload anything if the user asked us to not do this */
4313                     !arg_no_reload &&
4314                     /* Don't try to reload anything when updating a unit globally */
4315                     !arg_global &&
4316                     /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4317                     (arg_user || sd_booted() > 0) &&
4318                     /* Don't try to reload anything if we are running in a chroot environment */
4319                     (arg_user || running_in_chroot() <= 0 || arg_root) ) {
4320                         int q;
4321
4322                         if ((q = daemon_reload(bus, args, n)) < 0)
4323                                 r = q;
4324                 }
4325         }
4326
4327 finish:
4328         install_info_hashmap_free(will_install);
4329         install_info_hashmap_free(have_installed);
4330
4331         set_free_free(remove_symlinks_to);
4332
4333         lookup_paths_free(&paths);
4334
4335         free(config_path);
4336
4337         return r;
4338 }
4339
4340 static int systemctl_help(void) {
4341
4342         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4343                "Send control commands to or query the systemd manager.\n\n"
4344                "  -h --help           Show this help\n"
4345                "     --version        Show package version\n"
4346                "  -t --type=TYPE      List only units of a particular type\n"
4347                "  -p --property=NAME  Show only properties by this name\n"
4348                "  -a --all            Show all units/properties, including dead/empty ones\n"
4349                "     --failed         Show only failed units\n"
4350                "     --full           Don't ellipsize unit names on output\n"
4351                "     --fail           When queueing a new job, fail if conflicting jobs are\n"
4352                "                      pending\n"
4353                "     --ignore-dependencies\n"
4354                "                      When queueing a new job, ignore all its dependencies\n"
4355                "     --kill-mode=MODE How to send signal\n"
4356                "     --kill-who=WHO   Who to send signal to\n"
4357                "  -s --signal=SIGNAL  Which signal to send\n"
4358                "  -H --host=[user@]host\n"
4359                "                      Show information for remote host\n"
4360                "  -P --privileged     Acquire privileges before execution\n"
4361                "  -q --quiet          Suppress output\n"
4362                "     --no-block       Do not wait until operation finished\n"
4363                "     --no-wall        Don't send wall message before halt/power-off/reboot\n"
4364                "     --no-reload      When enabling/disabling unit files, don't reload daemon\n"
4365                "                      configuration\n"
4366                "     --no-pager       Do not pipe output into a pager.\n"
4367                "     --no-ask-password\n"
4368                "                      Do not ask for system passwords\n"
4369                "     --order          When generating graph for dot, show only order\n"
4370                "     --require        When generating graph for dot, show only requirement\n"
4371                "     --root=path      Use <root> as the root file system\n"
4372                "     --system         Connect to system manager\n"
4373                "     --user           Connect to user service manager\n"
4374                "     --global         Enable/disable unit files globally\n"
4375                "  -f --force          When enabling unit files, override existing symlinks\n"
4376                "                      When shutting down, execute action immediately\n"
4377                "     --defaults       When disabling unit files, remove default symlinks only\n\n"
4378                "Commands:\n"
4379                "  list-units                      List units\n"
4380                "  start [NAME...]                 Start (activate) one or more units\n"
4381                "  stop [NAME...]                  Stop (deactivate) one or more units\n"
4382                "  reload [NAME...]                Reload one or more units\n"
4383                "  restart [NAME...]               Start or restart one or more units\n"
4384                "  try-restart [NAME...]           Restart one or more units if active\n"
4385                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
4386                "                                  otherwise start or restart\n"
4387                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4388                "                                  otherwise restart if active\n"
4389                "  isolate [NAME]                  Start one unit and stop all others\n"
4390                "  kill [NAME...]                  Send signal to processes of a unit\n"
4391                "  is-active [NAME...]             Check whether units are active\n"
4392                "  status [NAME...|PID...]         Show runtime status of one or more units\n"
4393                "  show [NAME...|JOB...]           Show properties of one or more\n"
4394                "                                  units/jobs or the manager\n"
4395                "  reset-failed [NAME...]          Reset failed state for all, one, or more\n"
4396                "                                  units\n"
4397                "  enable [NAME...]                Enable one or more unit files\n"
4398                "  disable [NAME...]               Disable one or more unit files\n"
4399                "  is-enabled [NAME...]            Check whether unit files are enabled\n"
4400                "  load [NAME...]                  Load one or more units\n"
4401                "  list-jobs                       List jobs\n"
4402                "  cancel [JOB...]                 Cancel all, one, or more jobs\n"
4403                "  monitor                         Monitor unit/job changes\n"
4404                "  dump                            Dump server status\n"
4405                "  dot                             Dump dependency graph for dot(1)\n"
4406                "  snapshot [NAME]                 Create a snapshot\n"
4407                "  delete [NAME...]                Remove one or more snapshots\n"
4408                "  daemon-reload                   Reload systemd manager configuration\n"
4409                "  daemon-reexec                   Reexecute systemd manager\n"
4410                "  show-environment                Dump environment\n"
4411                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
4412                "  unset-environment [NAME...]     Unset one or more environment variables\n"
4413                "  default                         Enter system default mode\n"
4414                "  rescue                          Enter system rescue mode\n"
4415                "  emergency                       Enter system emergency mode\n"
4416                "  halt                            Shut down and halt the system\n"
4417                "  poweroff                        Shut down and power-off the system\n"
4418                "  reboot                          Shut down and reboot the system\n"
4419                "  kexec                           Shut down and reboot the system with kexec\n"
4420                "  exit                            Ask for user instance termination\n",
4421                program_invocation_short_name);
4422
4423         return 0;
4424 }
4425
4426 static int halt_help(void) {
4427
4428         printf("%s [OPTIONS...]\n\n"
4429                "%s the system.\n\n"
4430                "     --help      Show this help\n"
4431                "     --halt      Halt the machine\n"
4432                "  -p --poweroff  Switch off the machine\n"
4433                "     --reboot    Reboot the machine\n"
4434                "  -f --force     Force immediate halt/power-off/reboot\n"
4435                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4436                "  -d --no-wtmp   Don't write wtmp record\n"
4437                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
4438                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
4439                program_invocation_short_name,
4440                arg_action == ACTION_REBOOT   ? "Reboot" :
4441                arg_action == ACTION_POWEROFF ? "Power off" :
4442                                                "Halt");
4443
4444         return 0;
4445 }
4446
4447 static int shutdown_help(void) {
4448
4449         printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4450                "Shut down the system.\n\n"
4451                "     --help      Show this help\n"
4452                "  -H --halt      Halt the machine\n"
4453                "  -P --poweroff  Power-off the machine\n"
4454                "  -r --reboot    Reboot the machine\n"
4455                "  -h             Equivalent to --poweroff, overriden by --halt\n"
4456                "  -k             Don't halt/power-off/reboot, just send warnings\n"
4457                "     --no-wall   Don't send wall message before halt/power-off/reboot\n"
4458                "  -c             Cancel a pending shutdown\n",
4459                program_invocation_short_name);
4460
4461         return 0;
4462 }
4463
4464 static int telinit_help(void) {
4465
4466         printf("%s [OPTIONS...] {COMMAND}\n\n"
4467                "Send control commands to the init daemon.\n\n"
4468                "     --help      Show this help\n"
4469                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
4470                "Commands:\n"
4471                "  0              Power-off the machine\n"
4472                "  6              Reboot the machine\n"
4473                "  2, 3, 4, 5     Start runlevelX.target unit\n"
4474                "  1, s, S        Enter rescue mode\n"
4475                "  q, Q           Reload init daemon configuration\n"
4476                "  u, U           Reexecute init daemon\n",
4477                program_invocation_short_name);
4478
4479         return 0;
4480 }
4481
4482 static int runlevel_help(void) {
4483
4484         printf("%s [OPTIONS...]\n\n"
4485                "Prints the previous and current runlevel of the init system.\n\n"
4486                "     --help      Show this help\n",
4487                program_invocation_short_name);
4488
4489         return 0;
4490 }
4491
4492 static int systemctl_parse_argv(int argc, char *argv[]) {
4493
4494         enum {
4495                 ARG_FAIL = 0x100,
4496                 ARG_IGNORE_DEPENDENCIES,
4497                 ARG_VERSION,
4498                 ARG_USER,
4499                 ARG_SYSTEM,
4500                 ARG_GLOBAL,
4501                 ARG_NO_BLOCK,
4502                 ARG_NO_PAGER,
4503                 ARG_NO_WALL,
4504                 ARG_ORDER,
4505                 ARG_REQUIRE,
4506                 ARG_ROOT,
4507                 ARG_FULL,
4508                 ARG_NO_RELOAD,
4509                 ARG_DEFAULTS,
4510                 ARG_KILL_MODE,
4511                 ARG_KILL_WHO,
4512                 ARG_NO_ASK_PASSWORD,
4513                 ARG_FAILED
4514         };
4515
4516         static const struct option options[] = {
4517                 { "help",      no_argument,       NULL, 'h'           },
4518                 { "version",   no_argument,       NULL, ARG_VERSION   },
4519                 { "type",      required_argument, NULL, 't'           },
4520                 { "property",  required_argument, NULL, 'p'           },
4521                 { "all",       no_argument,       NULL, 'a'           },
4522                 { "failed",    no_argument,       NULL, ARG_FAILED    },
4523                 { "full",      no_argument,       NULL, ARG_FULL      },
4524                 { "fail",      no_argument,       NULL, ARG_FAIL      },
4525                 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4526                 { "user",      no_argument,       NULL, ARG_USER      },
4527                 { "system",    no_argument,       NULL, ARG_SYSTEM    },
4528                 { "global",    no_argument,       NULL, ARG_GLOBAL    },
4529                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
4530                 { "no-pager",  no_argument,       NULL, ARG_NO_PAGER  },
4531                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL   },
4532                 { "quiet",     no_argument,       NULL, 'q'           },
4533                 { "order",     no_argument,       NULL, ARG_ORDER     },
4534                 { "require",   no_argument,       NULL, ARG_REQUIRE   },
4535                 { "root",      required_argument, NULL, ARG_ROOT      },
4536                 { "force",     no_argument,       NULL, 'f'           },
4537                 { "no-reload", no_argument,       NULL, ARG_NO_RELOAD },
4538                 { "defaults",  no_argument,       NULL, ARG_DEFAULTS  },
4539                 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4540                 { "kill-who",  required_argument, NULL, ARG_KILL_WHO  },
4541                 { "signal",    required_argument, NULL, 's'           },
4542                 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4543                 { "host",      required_argument, NULL, 'H'           },
4544                 { "privileged",no_argument,       NULL, 'P'           },
4545                 { NULL,        0,                 NULL, 0             }
4546         };
4547
4548         int c;
4549
4550         assert(argc >= 0);
4551         assert(argv);
4552
4553         /* Only when running as systemctl we ask for passwords */
4554         arg_ask_password = true;
4555
4556         while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
4557
4558                 switch (c) {
4559
4560                 case 'h':
4561                         systemctl_help();
4562                         return 0;
4563
4564                 case ARG_VERSION:
4565                         puts(PACKAGE_STRING);
4566                         puts(DISTRIBUTION);
4567                         puts(SYSTEMD_FEATURES);
4568                         return 0;
4569
4570                 case 't':
4571                         arg_type = optarg;
4572                         break;
4573
4574                 case 'p': {
4575                         char **l;
4576
4577                         if (!(l = strv_append(arg_property, optarg)))
4578                                 return -ENOMEM;
4579
4580                         strv_free(arg_property);
4581                         arg_property = l;
4582
4583                         /* If the user asked for a particular
4584                          * property, show it to him, even if it is
4585                          * empty. */
4586                         arg_all = true;
4587                         break;
4588                 }
4589
4590                 case 'a':
4591                         arg_all = true;
4592                         break;
4593
4594                 case ARG_FAIL:
4595                         arg_job_mode = "fail";
4596                         break;
4597
4598                 case ARG_IGNORE_DEPENDENCIES:
4599                         arg_job_mode = "ignore-dependencies";
4600                         break;
4601
4602                 case ARG_USER:
4603                         arg_user = true;
4604                         break;
4605
4606                 case ARG_SYSTEM:
4607                         arg_user = false;
4608                         break;
4609
4610                 case ARG_NO_BLOCK:
4611                         arg_no_block = true;
4612                         break;
4613
4614                 case ARG_NO_PAGER:
4615                         arg_no_pager = true;
4616                         break;
4617
4618                 case ARG_NO_WALL:
4619                         arg_no_wall = true;
4620                         break;
4621
4622                 case ARG_ORDER:
4623                         arg_dot = DOT_ORDER;
4624                         break;
4625
4626                 case ARG_REQUIRE:
4627                         arg_dot = DOT_REQUIRE;
4628                         break;
4629
4630                 case ARG_ROOT:
4631                         arg_root = optarg;
4632                         break;
4633
4634                 case ARG_FULL:
4635                         arg_full = true;
4636                         break;
4637
4638                 case ARG_FAILED:
4639                         arg_failed = true;
4640                         break;
4641
4642                 case 'q':
4643                         arg_quiet = true;
4644                         break;
4645
4646                 case 'f':
4647                         arg_force = true;
4648                         break;
4649
4650                 case ARG_NO_RELOAD:
4651                         arg_no_reload = true;
4652                         break;
4653
4654                 case ARG_GLOBAL:
4655                         arg_global = true;
4656                         arg_user = true;
4657                         break;
4658
4659                 case ARG_DEFAULTS:
4660                         arg_defaults = true;
4661                         break;
4662
4663                 case ARG_KILL_WHO:
4664                         arg_kill_who = optarg;
4665                         break;
4666
4667                 case ARG_KILL_MODE:
4668                         arg_kill_mode = optarg;
4669                         break;
4670
4671                 case 's':
4672                         if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4673                                 log_error("Failed to parse signal string %s.", optarg);
4674                                 return -EINVAL;
4675                         }
4676                         break;
4677
4678                 case ARG_NO_ASK_PASSWORD:
4679                         arg_ask_password = false;
4680                         break;
4681
4682                 case 'P':
4683                         arg_transport = TRANSPORT_POLKIT;
4684                         break;
4685
4686                 case 'H':
4687                         arg_transport = TRANSPORT_SSH;
4688                         arg_host = optarg;
4689                         break;
4690
4691                 case '?':
4692                         return -EINVAL;
4693
4694                 default:
4695                         log_error("Unknown option code %c", c);
4696                         return -EINVAL;
4697                 }
4698         }
4699
4700         if (arg_transport != TRANSPORT_NORMAL && arg_user) {
4701                 log_error("Cannot access user instance remotely.");
4702                 return -EINVAL;
4703         }
4704
4705         return 1;
4706 }
4707
4708 static int halt_parse_argv(int argc, char *argv[]) {
4709
4710         enum {
4711                 ARG_HELP = 0x100,
4712                 ARG_HALT,
4713                 ARG_REBOOT,
4714                 ARG_NO_WALL
4715         };
4716
4717         static const struct option options[] = {
4718                 { "help",      no_argument,       NULL, ARG_HELP    },
4719                 { "halt",      no_argument,       NULL, ARG_HALT    },
4720                 { "poweroff",  no_argument,       NULL, 'p'         },
4721                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
4722                 { "force",     no_argument,       NULL, 'f'         },
4723                 { "wtmp-only", no_argument,       NULL, 'w'         },
4724                 { "no-wtmp",   no_argument,       NULL, 'd'         },
4725                 { "no-sync",   no_argument,       NULL, 'n'         },
4726                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4727                 { NULL,        0,                 NULL, 0           }
4728         };
4729
4730         int c, runlevel;
4731
4732         assert(argc >= 0);
4733         assert(argv);
4734
4735         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4736                 if (runlevel == '0' || runlevel == '6')
4737                         arg_immediate = true;
4738
4739         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4740                 switch (c) {
4741
4742                 case ARG_HELP:
4743                         halt_help();
4744                         return 0;
4745
4746                 case ARG_HALT:
4747                         arg_action = ACTION_HALT;
4748                         break;
4749
4750                 case 'p':
4751                         if (arg_action != ACTION_REBOOT)
4752                                 arg_action = ACTION_POWEROFF;
4753                         break;
4754
4755                 case ARG_REBOOT:
4756                         arg_action = ACTION_REBOOT;
4757                         break;
4758
4759                 case 'f':
4760                         arg_immediate = true;
4761                         break;
4762
4763                 case 'w':
4764                         arg_dry = true;
4765                         break;
4766
4767                 case 'd':
4768                         arg_no_wtmp = true;
4769                         break;
4770
4771                 case 'n':
4772                         arg_no_sync = true;
4773                         break;
4774
4775                 case ARG_NO_WALL:
4776                         arg_no_wall = true;
4777                         break;
4778
4779                 case 'i':
4780                 case 'h':
4781                         /* Compatibility nops */
4782                         break;
4783
4784                 case '?':
4785                         return -EINVAL;
4786
4787                 default:
4788                         log_error("Unknown option code %c", c);
4789                         return -EINVAL;
4790                 }
4791         }
4792
4793         if (optind < argc) {
4794                 log_error("Too many arguments.");
4795                 return -EINVAL;
4796         }
4797
4798         return 1;
4799 }
4800
4801 static int parse_time_spec(const char *t, usec_t *_u) {
4802         assert(t);
4803         assert(_u);
4804
4805         if (streq(t, "now"))
4806                 *_u = 0;
4807         else if (!strchr(t, ':')) {
4808                 uint64_t u;
4809
4810                 if (safe_atou64(t, &u) < 0)
4811                         return -EINVAL;
4812
4813                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4814         } else {
4815                 char *e = NULL;
4816                 long hour, minute;
4817                 struct tm tm;
4818                 time_t s;
4819                 usec_t n;
4820
4821                 errno = 0;
4822                 hour = strtol(t, &e, 10);
4823                 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4824                         return -EINVAL;
4825
4826                 minute = strtol(e+1, &e, 10);
4827                 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4828                         return -EINVAL;
4829
4830                 n = now(CLOCK_REALTIME);
4831                 s = (time_t) (n / USEC_PER_SEC);
4832
4833                 zero(tm);
4834                 assert_se(localtime_r(&s, &tm));
4835
4836                 tm.tm_hour = (int) hour;
4837                 tm.tm_min = (int) minute;
4838                 tm.tm_sec = 0;
4839
4840                 assert_se(s = mktime(&tm));
4841
4842                 *_u = (usec_t) s * USEC_PER_SEC;
4843
4844                 while (*_u <= n)
4845                         *_u += USEC_PER_DAY;
4846         }
4847
4848         return 0;
4849 }
4850
4851 static bool kexec_loaded(void) {
4852        bool loaded = false;
4853        char *s;
4854
4855        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4856                if (s[0] == '1')
4857                        loaded = true;
4858                free(s);
4859        }
4860        return loaded;
4861 }
4862
4863 static int shutdown_parse_argv(int argc, char *argv[]) {
4864
4865         enum {
4866                 ARG_HELP = 0x100,
4867                 ARG_NO_WALL
4868         };
4869
4870         static const struct option options[] = {
4871                 { "help",      no_argument,       NULL, ARG_HELP    },
4872                 { "halt",      no_argument,       NULL, 'H'         },
4873                 { "poweroff",  no_argument,       NULL, 'P'         },
4874                 { "reboot",    no_argument,       NULL, 'r'         },
4875                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4876                 { NULL,        0,                 NULL, 0           }
4877         };
4878
4879         int c, r;
4880
4881         assert(argc >= 0);
4882         assert(argv);
4883
4884         while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4885                 switch (c) {
4886
4887                 case ARG_HELP:
4888                         shutdown_help();
4889                         return 0;
4890
4891                 case 'H':
4892                         arg_action = ACTION_HALT;
4893                         break;
4894
4895                 case 'P':
4896                         arg_action = ACTION_POWEROFF;
4897                         break;
4898
4899                 case 'r':
4900                         if (kexec_loaded())
4901                                 arg_action = ACTION_KEXEC;
4902                         else
4903                                 arg_action = ACTION_REBOOT;
4904                         break;
4905
4906                 case 'h':
4907                         if (arg_action != ACTION_HALT)
4908                                 arg_action = ACTION_POWEROFF;
4909                         break;
4910
4911                 case 'k':
4912                         arg_dry = true;
4913                         break;
4914
4915                 case ARG_NO_WALL:
4916                         arg_no_wall = true;
4917                         break;
4918
4919                 case 't':
4920                 case 'a':
4921                         /* Compatibility nops */
4922                         break;
4923
4924                 case 'c':
4925                         arg_action = ACTION_CANCEL_SHUTDOWN;
4926                         break;
4927
4928                 case '?':
4929                         return -EINVAL;
4930
4931                 default:
4932                         log_error("Unknown option code %c", c);
4933                         return -EINVAL;
4934                 }
4935         }
4936
4937         if (argc > optind) {
4938                 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4939                         log_error("Failed to parse time specification: %s", argv[optind]);
4940                         return r;
4941                 }
4942         } else
4943                 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4944
4945         /* We skip the time argument */
4946         if (argc > optind + 1)
4947                 arg_wall = argv + optind + 1;
4948
4949         optind = argc;
4950
4951         return 1;
4952 }
4953
4954 static int telinit_parse_argv(int argc, char *argv[]) {
4955
4956         enum {
4957                 ARG_HELP = 0x100,
4958                 ARG_NO_WALL
4959         };
4960
4961         static const struct option options[] = {
4962                 { "help",      no_argument,       NULL, ARG_HELP    },
4963                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4964                 { NULL,        0,                 NULL, 0           }
4965         };
4966
4967         static const struct {
4968                 char from;
4969                 enum action to;
4970         } table[] = {
4971                 { '0', ACTION_POWEROFF },
4972                 { '6', ACTION_REBOOT },
4973                 { '1', ACTION_RESCUE },
4974                 { '2', ACTION_RUNLEVEL2 },
4975                 { '3', ACTION_RUNLEVEL3 },
4976                 { '4', ACTION_RUNLEVEL4 },
4977                 { '5', ACTION_RUNLEVEL5 },
4978                 { 's', ACTION_RESCUE },
4979                 { 'S', ACTION_RESCUE },
4980                 { 'q', ACTION_RELOAD },
4981                 { 'Q', ACTION_RELOAD },
4982                 { 'u', ACTION_REEXEC },
4983                 { 'U', ACTION_REEXEC }
4984         };
4985
4986         unsigned i;
4987         int c;
4988
4989         assert(argc >= 0);
4990         assert(argv);
4991
4992         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4993                 switch (c) {
4994
4995                 case ARG_HELP:
4996                         telinit_help();
4997                         return 0;
4998
4999                 case ARG_NO_WALL:
5000                         arg_no_wall = true;
5001                         break;
5002
5003                 case '?':
5004                         return -EINVAL;
5005
5006                 default:
5007                         log_error("Unknown option code %c", c);
5008                         return -EINVAL;
5009                 }
5010         }
5011
5012         if (optind >= argc) {
5013                 telinit_help();
5014                 return -EINVAL;
5015         }
5016
5017         if (optind + 1 < argc) {
5018                 log_error("Too many arguments.");
5019                 return -EINVAL;
5020         }
5021
5022         if (strlen(argv[optind]) != 1) {
5023                 log_error("Expected single character argument.");
5024                 return -EINVAL;
5025         }
5026
5027         for (i = 0; i < ELEMENTSOF(table); i++)
5028                 if (table[i].from == argv[optind][0])
5029                         break;
5030
5031         if (i >= ELEMENTSOF(table)) {
5032                 log_error("Unknown command %s.", argv[optind]);
5033                 return -EINVAL;
5034         }
5035
5036         arg_action = table[i].to;
5037
5038         optind ++;
5039
5040         return 1;
5041 }
5042
5043 static int runlevel_parse_argv(int argc, char *argv[]) {
5044
5045         enum {
5046                 ARG_HELP = 0x100,
5047         };
5048
5049         static const struct option options[] = {
5050                 { "help",      no_argument,       NULL, ARG_HELP    },
5051                 { NULL,        0,                 NULL, 0           }
5052         };
5053
5054         int c;
5055
5056         assert(argc >= 0);
5057         assert(argv);
5058
5059         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5060                 switch (c) {
5061
5062                 case ARG_HELP:
5063                         runlevel_help();
5064                         return 0;
5065
5066                 case '?':
5067                         return -EINVAL;
5068
5069                 default:
5070                         log_error("Unknown option code %c", c);
5071                         return -EINVAL;
5072                 }
5073         }
5074
5075         if (optind < argc) {
5076                 log_error("Too many arguments.");
5077                 return -EINVAL;
5078         }
5079
5080         return 1;
5081 }
5082
5083 static int parse_argv(int argc, char *argv[]) {
5084         assert(argc >= 0);
5085         assert(argv);
5086
5087         if (program_invocation_short_name) {
5088
5089                 if (strstr(program_invocation_short_name, "halt")) {
5090                         arg_action = ACTION_HALT;
5091                         return halt_parse_argv(argc, argv);
5092                 } else if (strstr(program_invocation_short_name, "poweroff")) {
5093                         arg_action = ACTION_POWEROFF;
5094                         return halt_parse_argv(argc, argv);
5095                 } else if (strstr(program_invocation_short_name, "reboot")) {
5096                         if (kexec_loaded())
5097                                 arg_action = ACTION_KEXEC;
5098                         else
5099                                 arg_action = ACTION_REBOOT;
5100                         return halt_parse_argv(argc, argv);
5101                 } else if (strstr(program_invocation_short_name, "shutdown")) {
5102                         arg_action = ACTION_POWEROFF;
5103                         return shutdown_parse_argv(argc, argv);
5104                 } else if (strstr(program_invocation_short_name, "init")) {
5105
5106                         if (sd_booted() > 0) {
5107                                 arg_action = ACTION_INVALID;
5108                                 return telinit_parse_argv(argc, argv);
5109                         } else {
5110                                 /* Hmm, so some other init system is
5111                                  * running, we need to forward this
5112                                  * request to it. For now we simply
5113                                  * guess that it is Upstart. */
5114
5115                                 execv("/lib/upstart/telinit", argv);
5116
5117                                 log_error("Couldn't find an alternative telinit implementation to spawn.");
5118                                 return -EIO;
5119                         }
5120
5121                 } else if (strstr(program_invocation_short_name, "runlevel")) {
5122                         arg_action = ACTION_RUNLEVEL;
5123                         return runlevel_parse_argv(argc, argv);
5124                 }
5125         }
5126
5127         arg_action = ACTION_SYSTEMCTL;
5128         return systemctl_parse_argv(argc, argv);
5129 }
5130
5131 static int action_to_runlevel(void) {
5132
5133         static const char table[_ACTION_MAX] = {
5134                 [ACTION_HALT] =      '0',
5135                 [ACTION_POWEROFF] =  '0',
5136                 [ACTION_REBOOT] =    '6',
5137                 [ACTION_RUNLEVEL2] = '2',
5138                 [ACTION_RUNLEVEL3] = '3',
5139                 [ACTION_RUNLEVEL4] = '4',
5140                 [ACTION_RUNLEVEL5] = '5',
5141                 [ACTION_RESCUE] =    '1'
5142         };
5143
5144         assert(arg_action < _ACTION_MAX);
5145
5146         return table[arg_action];
5147 }
5148
5149 static int talk_upstart(void) {
5150         DBusMessage *m = NULL, *reply = NULL;
5151         DBusError error;
5152         int previous, rl, r;
5153         char
5154                 env1_buf[] = "RUNLEVEL=X",
5155                 env2_buf[] = "PREVLEVEL=X";
5156         char *env1 = env1_buf, *env2 = env2_buf;
5157         const char *emit = "runlevel";
5158         dbus_bool_t b_false = FALSE;
5159         DBusMessageIter iter, sub;
5160         DBusConnection *bus;
5161
5162         dbus_error_init(&error);
5163
5164         if (!(rl = action_to_runlevel()))
5165                 return 0;
5166
5167         if (utmp_get_runlevel(&previous, NULL) < 0)
5168                 previous = 'N';
5169
5170         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5171                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5172                         r = 0;
5173                         goto finish;
5174                 }
5175
5176                 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5177                 r = -EIO;
5178                 goto finish;
5179         }
5180
5181         if ((r = bus_check_peercred(bus)) < 0) {
5182                 log_error("Failed to verify owner of bus.");
5183                 goto finish;
5184         }
5185
5186         if (!(m = dbus_message_new_method_call(
5187                               "com.ubuntu.Upstart",
5188                               "/com/ubuntu/Upstart",
5189                               "com.ubuntu.Upstart0_6",
5190                               "EmitEvent"))) {
5191
5192                 log_error("Could not allocate message.");
5193                 r = -ENOMEM;
5194                 goto finish;
5195         }
5196
5197         dbus_message_iter_init_append(m, &iter);
5198
5199         env1_buf[sizeof(env1_buf)-2] = rl;
5200         env2_buf[sizeof(env2_buf)-2] = previous;
5201
5202         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5203             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5204             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5205             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5206             !dbus_message_iter_close_container(&iter, &sub) ||
5207             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5208                 log_error("Could not append arguments to message.");
5209                 r = -ENOMEM;
5210                 goto finish;
5211         }
5212
5213         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5214
5215                 if (error_is_no_service(&error)) {
5216                         r = -EADDRNOTAVAIL;
5217                         goto finish;
5218                 }
5219
5220                 log_error("Failed to issue method call: %s", bus_error_message(&error));
5221                 r = -EIO;
5222                 goto finish;
5223         }
5224
5225         r = 0;
5226
5227 finish:
5228         if (m)
5229                 dbus_message_unref(m);
5230
5231         if (reply)
5232                 dbus_message_unref(reply);
5233
5234         if (bus) {
5235                 dbus_connection_flush(bus);
5236                 dbus_connection_close(bus);
5237                 dbus_connection_unref(bus);
5238         }
5239
5240         dbus_error_free(&error);
5241
5242         return r;
5243 }
5244
5245 static int talk_initctl(void) {
5246         struct init_request request;
5247         int r, fd;
5248         char rl;
5249
5250         if (!(rl = action_to_runlevel()))
5251                 return 0;
5252
5253         zero(request);
5254         request.magic = INIT_MAGIC;
5255         request.sleeptime = 0;
5256         request.cmd = INIT_CMD_RUNLVL;
5257         request.runlevel = rl;
5258
5259         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5260
5261                 if (errno == ENOENT)
5262                         return 0;
5263
5264                 log_error("Failed to open "INIT_FIFO": %m");
5265                 return -errno;
5266         }
5267
5268         errno = 0;
5269         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5270         close_nointr_nofail(fd);
5271
5272         if (r < 0) {
5273                 log_error("Failed to write to "INIT_FIFO": %m");
5274                 return errno ? -errno : -EIO;
5275         }
5276
5277         return 1;
5278 }
5279
5280 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5281
5282         static const struct {
5283                 const char* verb;
5284                 const enum {
5285                         MORE,
5286                         LESS,
5287                         EQUAL
5288                 } argc_cmp;
5289                 const int argc;
5290                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5291         } verbs[] = {
5292                 { "list-units",            LESS,  1, list_units        },
5293                 { "list-jobs",             EQUAL, 1, list_jobs         },
5294                 { "clear-jobs",            EQUAL, 1, daemon_reload     },
5295                 { "load",                  MORE,  2, load_unit         },
5296                 { "cancel",                MORE,  2, cancel_job        },
5297                 { "start",                 MORE,  2, start_unit        },
5298                 { "stop",                  MORE,  2, start_unit        },
5299                 { "condstop",              MORE,  2, start_unit        }, /* For compatibility with ALTLinux */
5300                 { "reload",                MORE,  2, start_unit        },
5301                 { "restart",               MORE,  2, start_unit        },
5302                 { "try-restart",           MORE,  2, start_unit        },
5303                 { "reload-or-restart",     MORE,  2, start_unit        },
5304                 { "reload-or-try-restart", MORE,  2, start_unit        },
5305                 { "force-reload",          MORE,  2, start_unit        }, /* For compatibility with SysV */
5306                 { "condreload",            MORE,  2, start_unit        }, /* For compatibility with ALTLinux */
5307                 { "condrestart",           MORE,  2, start_unit        }, /* For compatibility with RH */
5308                 { "isolate",               EQUAL, 2, start_unit        },
5309                 { "kill",                  MORE,  2, kill_unit         },
5310                 { "is-active",             MORE,  2, check_unit        },
5311                 { "check",                 MORE,  2, check_unit        },
5312                 { "show",                  MORE,  1, show              },
5313                 { "status",                MORE,  2, show              },
5314                 { "monitor",               EQUAL, 1, monitor           },
5315                 { "dump",                  EQUAL, 1, dump              },
5316                 { "dot",                   EQUAL, 1, dot               },
5317                 { "snapshot",              LESS,  2, snapshot          },
5318                 { "delete",                MORE,  2, delete_snapshot   },
5319                 { "daemon-reload",         EQUAL, 1, daemon_reload     },
5320                 { "daemon-reexec",         EQUAL, 1, daemon_reload     },
5321                 { "show-environment",      EQUAL, 1, show_enviroment   },
5322                 { "set-environment",       MORE,  2, set_environment   },
5323                 { "unset-environment",     MORE,  2, set_environment   },
5324                 { "halt",                  EQUAL, 1, start_special     },
5325                 { "poweroff",              EQUAL, 1, start_special     },
5326                 { "reboot",                EQUAL, 1, start_special     },
5327                 { "kexec",                 EQUAL, 1, start_special     },
5328                 { "default",               EQUAL, 1, start_special     },
5329                 { "rescue",                EQUAL, 1, start_special     },
5330                 { "emergency",             EQUAL, 1, start_special     },
5331                 { "exit",                  EQUAL, 1, start_special     },
5332                 { "reset-failed",          MORE,  1, reset_failed      },
5333                 { "enable",                MORE,  2, enable_unit       },
5334                 { "disable",               MORE,  2, enable_unit       },
5335                 { "is-enabled",            MORE,  2, enable_unit       }
5336         };
5337
5338         int left;
5339         unsigned i;
5340
5341         assert(argc >= 0);
5342         assert(argv);
5343         assert(error);
5344
5345         left = argc - optind;
5346
5347         if (left <= 0)
5348                 /* Special rule: no arguments means "list-units" */
5349                 i = 0;
5350         else {
5351                 if (streq(argv[optind], "help")) {
5352                         systemctl_help();
5353                         return 0;
5354                 }
5355
5356                 for (i = 0; i < ELEMENTSOF(verbs); i++)
5357                         if (streq(argv[optind], verbs[i].verb))
5358                                 break;
5359
5360                 if (i >= ELEMENTSOF(verbs)) {
5361                         log_error("Unknown operation %s", argv[optind]);
5362                         return -EINVAL;
5363                 }
5364         }
5365
5366         switch (verbs[i].argc_cmp) {
5367
5368         case EQUAL:
5369                 if (left != verbs[i].argc) {
5370                         log_error("Invalid number of arguments.");
5371                         return -EINVAL;
5372                 }
5373
5374                 break;
5375
5376         case MORE:
5377                 if (left < verbs[i].argc) {
5378                         log_error("Too few arguments.");
5379                         return -EINVAL;
5380                 }
5381
5382                 break;
5383
5384         case LESS:
5385                 if (left > verbs[i].argc) {
5386                         log_error("Too many arguments.");
5387                         return -EINVAL;
5388                 }
5389
5390                 break;
5391
5392         default:
5393                 assert_not_reached("Unknown comparison operator.");
5394         }
5395
5396         /* Require a bus connection for all operations but
5397          * enable/disable */
5398         if (!streq(verbs[i].verb, "enable") && !streq(verbs[i].verb, "disable")) {
5399
5400                 if (running_in_chroot() > 0) {
5401                         log_info("Running in chroot, ignoring request.");
5402                         return 0;
5403                 }
5404
5405                 if (!bus) {
5406                         log_error("Failed to get D-Bus connection: %s", error->message);
5407                         return -EIO;
5408                 }
5409         }
5410
5411         return verbs[i].dispatch(bus, argv + optind, left);
5412 }
5413
5414 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
5415         int fd = -1;
5416         struct msghdr msghdr;
5417         struct iovec iovec;
5418         union sockaddr_union sockaddr;
5419         struct shutdownd_command c;
5420
5421         zero(c);
5422         c.elapse = t;
5423         c.mode = mode;
5424         c.dry_run = dry_run;
5425         c.warn_wall = warn;
5426
5427         if (message)
5428                 strncpy(c.wall_message, message, sizeof(c.wall_message));
5429
5430         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5431                 return -errno;
5432
5433         zero(sockaddr);
5434         sockaddr.sa.sa_family = AF_UNIX;
5435         sockaddr.un.sun_path[0] = 0;
5436         strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5437
5438         zero(iovec);
5439         iovec.iov_base = (char*) &c;
5440         iovec.iov_len = sizeof(c);
5441
5442         zero(msghdr);
5443         msghdr.msg_name = &sockaddr;
5444         msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5445
5446         msghdr.msg_iov = &iovec;
5447         msghdr.msg_iovlen = 1;
5448
5449         if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5450                 close_nointr_nofail(fd);
5451                 return -errno;
5452         }
5453
5454         close_nointr_nofail(fd);
5455         return 0;
5456 }
5457
5458 static int reload_with_fallback(DBusConnection *bus) {
5459
5460         if (bus) {
5461                 /* First, try systemd via D-Bus. */
5462                 if (daemon_reload(bus, NULL, 0) > 0)
5463                         return 0;
5464         }
5465
5466         /* Nothing else worked, so let's try signals */
5467         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5468
5469         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5470                 log_error("kill() failed: %m");
5471                 return -errno;
5472         }
5473
5474         return 0;
5475 }
5476
5477 static int start_with_fallback(DBusConnection *bus) {
5478
5479         if (bus) {
5480                 /* First, try systemd via D-Bus. */
5481                 if (start_unit(bus, NULL, 0) >= 0)
5482                         goto done;
5483         }
5484
5485         /* Hmm, talking to systemd via D-Bus didn't work. Then
5486          * let's try to talk to Upstart via D-Bus. */
5487         if (talk_upstart() > 0)
5488                 goto done;
5489
5490         /* Nothing else worked, so let's try
5491          * /dev/initctl */
5492         if (talk_initctl() > 0)
5493                 goto done;
5494
5495         log_error("Failed to talk to init daemon.");
5496         return -EIO;
5497
5498 done:
5499         warn_wall(arg_action);
5500         return 0;
5501 }
5502
5503 static int halt_main(DBusConnection *bus) {
5504         int r;
5505
5506         if (geteuid() != 0) {
5507                 log_error("Must be root.");
5508                 return -EPERM;
5509         }
5510
5511         if (arg_when > 0) {
5512                 char *m;
5513                 char date[FORMAT_TIMESTAMP_MAX];
5514
5515                 m = strv_join(arg_wall, " ");
5516                 r = send_shutdownd(arg_when,
5517                                    arg_action == ACTION_HALT     ? 'H' :
5518                                    arg_action == ACTION_POWEROFF ? 'P' :
5519                                                                    'r',
5520                                    arg_dry,
5521                                    !arg_no_wall,
5522                                    m);
5523                 free(m);
5524
5525                 if (r < 0)
5526                         log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5527                 else {
5528                         log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5529                                  format_timestamp(date, sizeof(date), arg_when));
5530                         return 0;
5531                 }
5532         }
5533
5534         if (!arg_dry && !arg_immediate)
5535                 return start_with_fallback(bus);
5536
5537         if (!arg_no_wtmp) {
5538                 if (sd_booted() > 0)
5539                         log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5540                 else if ((r = utmp_put_shutdown(0)) < 0)
5541                         log_warning("Failed to write utmp record: %s", strerror(-r));
5542         }
5543
5544         if (!arg_no_sync)
5545                 sync();
5546
5547         if (arg_dry)
5548                 return 0;
5549
5550         /* Make sure C-A-D is handled by the kernel from this
5551          * point on... */
5552         reboot(RB_ENABLE_CAD);
5553
5554         switch (arg_action) {
5555
5556         case ACTION_HALT:
5557                 log_info("Halting.");
5558                 reboot(RB_HALT_SYSTEM);
5559                 break;
5560
5561         case ACTION_POWEROFF:
5562                 log_info("Powering off.");
5563                 reboot(RB_POWER_OFF);
5564                 break;
5565
5566         case ACTION_REBOOT:
5567                 log_info("Rebooting.");
5568                 reboot(RB_AUTOBOOT);
5569                 break;
5570
5571         default:
5572                 assert_not_reached("Unknown halt action.");
5573         }
5574
5575         /* We should never reach this. */
5576         return -ENOSYS;
5577 }
5578
5579 static int runlevel_main(void) {
5580         int r, runlevel, previous;
5581
5582         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5583                 printf("unknown\n");
5584                 return r;
5585         }
5586
5587         printf("%c %c\n",
5588                previous <= 0 ? 'N' : previous,
5589                runlevel <= 0 ? 'N' : runlevel);
5590
5591         return 0;
5592 }
5593
5594 static void agent_close(void) {
5595         siginfo_t dummy;
5596
5597         if (agent_pid <= 0)
5598                 return;
5599
5600         /* Inform agent that we are done */
5601         kill(agent_pid, SIGTERM);
5602         kill(agent_pid, SIGCONT);
5603         wait_for_terminate(agent_pid, &dummy);
5604         agent_pid = 0;
5605 }
5606
5607 int main(int argc, char*argv[]) {
5608         int r, retval = EXIT_FAILURE;
5609         DBusConnection *bus = NULL;
5610         DBusError error;
5611
5612         dbus_error_init(&error);
5613
5614         log_parse_environment();
5615         log_open();
5616
5617         if ((r = parse_argv(argc, argv)) < 0)
5618                 goto finish;
5619         else if (r == 0) {
5620                 retval = EXIT_SUCCESS;
5621                 goto finish;
5622         }
5623
5624         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5625          * let's shortcut this */
5626         if (arg_action == ACTION_RUNLEVEL) {
5627                 r = runlevel_main();
5628                 retval = r < 0 ? EXIT_FAILURE : r;
5629                 goto finish;
5630         }
5631
5632         if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5633                 log_info("Running in chroot, ignoring request.");
5634                 retval = 0;
5635                 goto finish;
5636         }
5637
5638         if (arg_transport == TRANSPORT_NORMAL)
5639                 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5640         else if (arg_transport == TRANSPORT_POLKIT) {
5641                 bus_connect_system_polkit(&bus, &error);
5642                 private_bus = false;
5643         } else if (arg_transport == TRANSPORT_SSH) {
5644                 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5645                 private_bus = false;
5646         } else
5647                 assert_not_reached("Uh, invalid transport...");
5648
5649         switch (arg_action) {
5650
5651         case ACTION_SYSTEMCTL:
5652                 r = systemctl_main(bus, argc, argv, &error);
5653                 break;
5654
5655         case ACTION_HALT:
5656         case ACTION_POWEROFF:
5657         case ACTION_REBOOT:
5658         case ACTION_KEXEC:
5659                 r = halt_main(bus);
5660                 break;
5661
5662         case ACTION_RUNLEVEL2:
5663         case ACTION_RUNLEVEL3:
5664         case ACTION_RUNLEVEL4:
5665         case ACTION_RUNLEVEL5:
5666         case ACTION_RESCUE:
5667         case ACTION_EMERGENCY:
5668         case ACTION_DEFAULT:
5669                 r = start_with_fallback(bus);
5670                 break;
5671
5672         case ACTION_RELOAD:
5673         case ACTION_REEXEC:
5674                 r = reload_with_fallback(bus);
5675                 break;
5676
5677         case ACTION_CANCEL_SHUTDOWN:
5678                 r = send_shutdownd(0, 0, false, false, NULL);
5679                 break;
5680
5681         case ACTION_INVALID:
5682         case ACTION_RUNLEVEL:
5683         default:
5684                 assert_not_reached("Unknown action");
5685         }
5686
5687         retval = r < 0 ? EXIT_FAILURE : r;
5688
5689 finish:
5690
5691         if (bus) {
5692                 dbus_connection_flush(bus);
5693                 dbus_connection_close(bus);
5694                 dbus_connection_unref(bus);
5695         }
5696
5697         dbus_error_free(&error);
5698
5699         dbus_shutdown();
5700
5701         strv_free(arg_property);
5702
5703         pager_close();
5704         agent_close();
5705
5706         return retval;
5707 }