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