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