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