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