chiark / gitweb /
Spelling Corrections
[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], "force-reload")          ? "ReloadOrTryRestartUnit" :
1425                                                                   "StartUnit";
1426
1427                 mode =
1428                         (streq(args[0], "isolate") ||
1429                          streq(args[0], "rescue")  ||
1430                          streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
1431
1432                 one_name = table[verb_to_action(args[0])];
1433
1434         } else {
1435                 assert(arg_action < ELEMENTSOF(table));
1436                 assert(table[arg_action]);
1437
1438                 method = "StartUnit";
1439
1440                 mode = (arg_action == ACTION_EMERGENCY ||
1441                         arg_action == ACTION_RESCUE ||
1442                         arg_action == ACTION_RUNLEVEL2 ||
1443                         arg_action == ACTION_RUNLEVEL3 ||
1444                         arg_action == ACTION_RUNLEVEL4 ||
1445                         arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
1446
1447                 one_name = table[arg_action];
1448         }
1449
1450         if (!arg_no_block) {
1451                 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1452                         log_error("Could not watch jobs: %s", strerror(-ret));
1453                         goto finish;
1454                 }
1455
1456                 if (!(s = set_new(string_hash_func, string_compare_func))) {
1457                         log_error("Failed to allocate set.");
1458                         ret = -ENOMEM;
1459                         goto finish;
1460                 }
1461         }
1462
1463         if (one_name) {
1464                 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
1465                         goto finish;
1466         } else {
1467                 for (i = 1; i < n; i++)
1468                         if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
1469                                 ret = translate_bus_error_to_exit_status(r, &error);
1470                                 dbus_error_free(&error);
1471                         }
1472         }
1473
1474         if (!arg_no_block)
1475                 if ((r = wait_for_jobs(bus, s)) < 0) {
1476                         ret = r;
1477                         goto finish;
1478                 }
1479
1480 finish:
1481         if (s)
1482                 set_free_free(s);
1483
1484         dbus_error_free(&error);
1485
1486         return ret;
1487 }
1488
1489 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1490         int r;
1491
1492         assert(bus);
1493         assert(args);
1494
1495         if (arg_force &&
1496             (streq(args[0], "halt") ||
1497              streq(args[0], "poweroff") ||
1498              streq(args[0], "reboot") ||
1499              streq(args[0], "kexec") ||
1500              streq(args[0], "exit")))
1501                 return daemon_reload(bus, args, n);
1502
1503         r = start_unit(bus, args, n);
1504
1505         if (r >= 0)
1506                 warn_wall(verb_to_action(args[0]));
1507
1508         return r;
1509 }
1510
1511 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1512         DBusMessage *m = NULL, *reply = NULL;
1513         const char
1514                 *interface = "org.freedesktop.systemd1.Unit",
1515                 *property = "ActiveState";
1516         int r = 3; /* According to LSB: "program is not running" */
1517         DBusError error;
1518         unsigned i;
1519
1520         assert(bus);
1521         assert(args);
1522
1523         dbus_error_init(&error);
1524
1525         for (i = 1; i < n; i++) {
1526                 const char *path = NULL;
1527                 const char *state;
1528                 DBusMessageIter iter, sub;
1529
1530                 if (!(m = dbus_message_new_method_call(
1531                                       "org.freedesktop.systemd1",
1532                                       "/org/freedesktop/systemd1",
1533                                       "org.freedesktop.systemd1.Manager",
1534                                       "GetUnit"))) {
1535                         log_error("Could not allocate message.");
1536                         r = -ENOMEM;
1537                         goto finish;
1538                 }
1539
1540                 if (!dbus_message_append_args(m,
1541                                               DBUS_TYPE_STRING, &args[i],
1542                                               DBUS_TYPE_INVALID)) {
1543                         log_error("Could not append arguments to message.");
1544                         r = -ENOMEM;
1545                         goto finish;
1546                 }
1547
1548                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1549
1550                         /* Hmm, cannot figure out anything about this unit... */
1551                         if (!arg_quiet)
1552                                 puts("unknown");
1553
1554                         dbus_error_free(&error);
1555                         dbus_message_unref(m);
1556                         continue;
1557                 }
1558
1559                 if (!dbus_message_get_args(reply, &error,
1560                                            DBUS_TYPE_OBJECT_PATH, &path,
1561                                            DBUS_TYPE_INVALID)) {
1562                         log_error("Failed to parse reply: %s", bus_error_message(&error));
1563                         r = -EIO;
1564                         goto finish;
1565                 }
1566
1567                 dbus_message_unref(m);
1568                 if (!(m = dbus_message_new_method_call(
1569                                       "org.freedesktop.systemd1",
1570                                       path,
1571                                       "org.freedesktop.DBus.Properties",
1572                                       "Get"))) {
1573                         log_error("Could not allocate message.");
1574                         r = -ENOMEM;
1575                         goto finish;
1576                 }
1577
1578                 if (!dbus_message_append_args(m,
1579                                               DBUS_TYPE_STRING, &interface,
1580                                               DBUS_TYPE_STRING, &property,
1581                                               DBUS_TYPE_INVALID)) {
1582                         log_error("Could not append arguments to message.");
1583                         r = -ENOMEM;
1584                         goto finish;
1585                 }
1586
1587                 dbus_message_unref(reply);
1588                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1589                         log_error("Failed to issue method call: %s", bus_error_message(&error));
1590                         r = -EIO;
1591                         goto finish;
1592                 }
1593
1594                 if (!dbus_message_iter_init(reply, &iter) ||
1595                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1596                         log_error("Failed to parse reply.");
1597                         r = -EIO;
1598                         goto finish;
1599                 }
1600
1601                 dbus_message_iter_recurse(&iter, &sub);
1602
1603                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1604                         log_error("Failed to parse reply.");
1605                         r = -EIO;
1606                         goto finish;
1607                 }
1608
1609                 dbus_message_iter_get_basic(&sub, &state);
1610
1611                 if (!arg_quiet)
1612                         puts(state);
1613
1614                 if (streq(state, "active") || streq(state, "reloading"))
1615                         r = 0;
1616
1617                 dbus_message_unref(m);
1618                 dbus_message_unref(reply);
1619                 m = reply = NULL;
1620         }
1621
1622 finish:
1623         if (m)
1624                 dbus_message_unref(m);
1625
1626         if (reply)
1627                 dbus_message_unref(reply);
1628
1629         dbus_error_free(&error);
1630
1631         return r;
1632 }
1633
1634 static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1635         DBusMessage *m = NULL, *reply = NULL;
1636         int r = 0;
1637         DBusError error;
1638         unsigned i;
1639
1640         assert(bus);
1641         assert(args);
1642
1643         dbus_error_init(&error);
1644
1645         if (!arg_kill_who)
1646                 arg_kill_who = "all";
1647
1648         if (!arg_kill_mode)
1649                 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1650
1651         for (i = 1; i < n; i++) {
1652
1653                 if (!(m = dbus_message_new_method_call(
1654                                       "org.freedesktop.systemd1",
1655                                       "/org/freedesktop/systemd1",
1656                                       "org.freedesktop.systemd1.Manager",
1657                                       "KillUnit"))) {
1658                         log_error("Could not allocate message.");
1659                         r = -ENOMEM;
1660                         goto finish;
1661                 }
1662
1663                 if (!dbus_message_append_args(m,
1664                                               DBUS_TYPE_STRING, &args[i],
1665                                               DBUS_TYPE_STRING, &arg_kill_who,
1666                                               DBUS_TYPE_STRING, &arg_kill_mode,
1667                                               DBUS_TYPE_INT32, &arg_signal,
1668                                               DBUS_TYPE_INVALID)) {
1669                         log_error("Could not append arguments to message.");
1670                         r = -ENOMEM;
1671                         goto finish;
1672                 }
1673
1674                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1675                         log_error("Failed to issue method call: %s", bus_error_message(&error));
1676                         dbus_error_free(&error);
1677                         r = -EIO;
1678                 }
1679
1680                 dbus_message_unref(m);
1681
1682                 if (reply)
1683                         dbus_message_unref(reply);
1684                 m = reply = NULL;
1685         }
1686
1687 finish:
1688         if (m)
1689                 dbus_message_unref(m);
1690
1691         if (reply)
1692                 dbus_message_unref(reply);
1693
1694         dbus_error_free(&error);
1695
1696         return r;
1697 }
1698
1699 typedef struct ExecStatusInfo {
1700         char *name;
1701
1702         char *path;
1703         char **argv;
1704
1705         bool ignore;
1706
1707         usec_t start_timestamp;
1708         usec_t exit_timestamp;
1709         pid_t pid;
1710         int code;
1711         int status;
1712
1713         LIST_FIELDS(struct ExecStatusInfo, exec);
1714 } ExecStatusInfo;
1715
1716 static void exec_status_info_free(ExecStatusInfo *i) {
1717         assert(i);
1718
1719         free(i->name);
1720         free(i->path);
1721         strv_free(i->argv);
1722         free(i);
1723 }
1724
1725 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1726         uint64_t start_timestamp, exit_timestamp;
1727         DBusMessageIter sub2, sub3;
1728         const char*path;
1729         unsigned n;
1730         uint32_t pid;
1731         int32_t code, status;
1732         dbus_bool_t ignore;
1733
1734         assert(i);
1735         assert(i);
1736
1737         if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1738                 return -EIO;
1739
1740         dbus_message_iter_recurse(sub, &sub2);
1741
1742         if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1743                 return -EIO;
1744
1745         if (!(i->path = strdup(path)))
1746                 return -ENOMEM;
1747
1748         if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1749             dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1750                 return -EIO;
1751
1752         n = 0;
1753         dbus_message_iter_recurse(&sub2, &sub3);
1754         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1755                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1756                 dbus_message_iter_next(&sub3);
1757                 n++;
1758         }
1759
1760
1761         if (!(i->argv = new0(char*, n+1)))
1762                 return -ENOMEM;
1763
1764         n = 0;
1765         dbus_message_iter_recurse(&sub2, &sub3);
1766         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1767                 const char *s;
1768
1769                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1770                 dbus_message_iter_get_basic(&sub3, &s);
1771                 dbus_message_iter_next(&sub3);
1772
1773                 if (!(i->argv[n++] = strdup(s)))
1774                         return -ENOMEM;
1775         }
1776
1777         if (!dbus_message_iter_next(&sub2) ||
1778             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1779             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1780             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1781             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1782             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1783             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1784                 return -EIO;
1785
1786         i->ignore = ignore;
1787         i->start_timestamp = (usec_t) start_timestamp;
1788         i->exit_timestamp = (usec_t) exit_timestamp;
1789         i->pid = (pid_t) pid;
1790         i->code = code;
1791         i->status = status;
1792
1793         return 0;
1794 }
1795
1796 typedef struct UnitStatusInfo {
1797         const char *id;
1798         const char *load_state;
1799         const char *active_state;
1800         const char *sub_state;
1801
1802         const char *description;
1803         const char *following;
1804
1805         const char *path;
1806         const char *default_control_group;
1807
1808         usec_t inactive_exit_timestamp;
1809         usec_t active_enter_timestamp;
1810         usec_t active_exit_timestamp;
1811         usec_t inactive_enter_timestamp;
1812
1813         bool need_daemon_reload;
1814
1815         /* Service */
1816         pid_t main_pid;
1817         pid_t control_pid;
1818         const char *status_text;
1819         bool running:1;
1820 #ifdef HAVE_SYSV_COMPAT
1821         bool is_sysv:1;
1822 #endif
1823
1824         usec_t start_timestamp;
1825         usec_t exit_timestamp;
1826
1827         int exit_code, exit_status;
1828
1829         /* Socket */
1830         unsigned n_accepted;
1831         unsigned n_connections;
1832         bool accept;
1833
1834         /* Device */
1835         const char *sysfs_path;
1836
1837         /* Mount, Automount */
1838         const char *where;
1839
1840         /* Swap */
1841         const char *what;
1842
1843         LIST_HEAD(ExecStatusInfo, exec);
1844 } UnitStatusInfo;
1845
1846 static void print_status_info(UnitStatusInfo *i) {
1847         ExecStatusInfo *p;
1848         const char *on, *off, *ss;
1849         usec_t timestamp;
1850         char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1851         char since2[FORMAT_TIMESTAMP_MAX], *s2;
1852
1853         assert(i);
1854
1855         /* This shows pretty information about a unit. See
1856          * print_property() for a low-level property printer */
1857
1858         printf("%s", strna(i->id));
1859
1860         if (i->description && !streq_ptr(i->id, i->description))
1861                 printf(" - %s", i->description);
1862
1863         printf("\n");
1864
1865         if (i->following)
1866                 printf("\t  Follow: unit currently follows state of %s\n", i->following);
1867
1868         if (streq_ptr(i->load_state, "failed") ||
1869             streq_ptr(i->load_state, "banned")) {
1870                 on = ansi_highlight(true);
1871                 off = ansi_highlight(false);
1872         } else
1873                 on = off = "";
1874
1875         if (i->path)
1876                 printf("\t  Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1877         else
1878                 printf("\t  Loaded: %s%s%s\n", on, strna(i->load_state), off);
1879
1880         ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1881
1882         if (streq_ptr(i->active_state, "failed")) {
1883                 on = ansi_highlight(true);
1884                 off = ansi_highlight(false);
1885         } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1886                 on = ansi_highlight_green(true);
1887                 off = ansi_highlight_green(false);
1888         } else
1889                 on = off = "";
1890
1891         if (ss)
1892                 printf("\t  Active: %s%s (%s)%s",
1893                        on,
1894                        strna(i->active_state),
1895                        ss,
1896                        off);
1897         else
1898                 printf("\t  Active: %s%s%s",
1899                        on,
1900                        strna(i->active_state),
1901                        off);
1902
1903         timestamp = (streq_ptr(i->active_state, "active")      ||
1904                      streq_ptr(i->active_state, "reloading"))   ? i->active_enter_timestamp :
1905                     (streq_ptr(i->active_state, "inactive")    ||
1906                      streq_ptr(i->active_state, "failed"))      ? i->inactive_enter_timestamp :
1907                     streq_ptr(i->active_state, "activating")    ? i->inactive_exit_timestamp :
1908                                                                   i->active_exit_timestamp;
1909
1910         s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1911         s2 = format_timestamp(since2, sizeof(since2), timestamp);
1912
1913         if (s1)
1914                 printf(" since %s; %s\n", s2, s1);
1915         else if (s2)
1916                 printf(" since %s\n", s2);
1917         else
1918                 printf("\n");
1919
1920         if (i->sysfs_path)
1921                 printf("\t  Device: %s\n", i->sysfs_path);
1922         if (i->where)
1923                 printf("\t   Where: %s\n", i->where);
1924         if (i->what)
1925                 printf("\t    What: %s\n", i->what);
1926
1927         if (i->accept)
1928                 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1929
1930         LIST_FOREACH(exec, p, i->exec) {
1931                 char *t;
1932                 bool good;
1933
1934                 /* Only show exited processes here */
1935                 if (p->code == 0)
1936                         continue;
1937
1938                 t = strv_join(p->argv, " ");
1939                 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
1940                 free(t);
1941
1942 #ifdef HAVE_SYSV_COMPAT
1943                 if (i->is_sysv)
1944                         good = is_clean_exit_lsb(p->code, p->status);
1945                 else
1946 #endif
1947                         good = is_clean_exit(p->code, p->status);
1948
1949                 if (!good) {
1950                         on = ansi_highlight(true);
1951                         off = ansi_highlight(false);
1952                 } else
1953                         on = off = "";
1954
1955                 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1956
1957                 if (p->code == CLD_EXITED) {
1958                         const char *c;
1959
1960                         printf("status=%i", p->status);
1961
1962 #ifdef HAVE_SYSV_COMPAT
1963                         if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
1964 #else
1965                         if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1966 #endif
1967                                 printf("/%s", c);
1968
1969                 } else
1970                         printf("signal=%s", signal_to_string(p->status));
1971
1972                 printf(")%s\n", off);
1973
1974                 on = off = NULL;
1975
1976                 if (i->main_pid == p->pid &&
1977                     i->start_timestamp == p->start_timestamp &&
1978                     i->exit_timestamp == p->start_timestamp)
1979                         /* Let's not show this twice */
1980                         i->main_pid = 0;
1981
1982                 if (p->pid == i->control_pid)
1983                         i->control_pid = 0;
1984         }
1985
1986         if (i->main_pid > 0 || i->control_pid > 0) {
1987                 printf("\t");
1988
1989                 if (i->main_pid > 0) {
1990                         printf("Main PID: %u", (unsigned) i->main_pid);
1991
1992                         if (i->running) {
1993                                 char *t = NULL;
1994                                 get_process_name(i->main_pid, &t);
1995                                 if (t) {
1996                                         printf(" (%s)", t);
1997                                         free(t);
1998                                 }
1999                         } else if (i->exit_code > 0) {
2000                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2001
2002                                 if (i->exit_code == CLD_EXITED) {
2003                                         const char *c;
2004
2005                                         printf("status=%i", i->exit_status);
2006
2007 #ifdef HAVE_SYSV_COMPAT
2008                                         if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
2009 #else
2010                                         if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2011 #endif
2012                                                 printf("/%s", c);
2013
2014                                 } else
2015                                         printf("signal=%s", signal_to_string(i->exit_status));
2016                                 printf(")");
2017                         }
2018                 }
2019
2020                 if (i->main_pid > 0 && i->control_pid > 0)
2021                         printf(";");
2022
2023                 if (i->control_pid > 0) {
2024                         char *t = NULL;
2025
2026                         printf(" Control: %u", (unsigned) i->control_pid);
2027
2028                         get_process_name(i->control_pid, &t);
2029                         if (t) {
2030                                 printf(" (%s)", t);
2031                                 free(t);
2032                         }
2033                 }
2034
2035                 printf("\n");
2036         }
2037
2038         if (i->status_text)
2039                 printf("\t  Status: \"%s\"\n", i->status_text);
2040
2041         if (i->default_control_group) {
2042                 unsigned c;
2043
2044                 printf("\t  CGroup: %s\n", i->default_control_group);
2045
2046                 if ((c = columns()) > 18)
2047                         c -= 18;
2048                 else
2049                         c = 0;
2050
2051                 show_cgroup_by_path(i->default_control_group, "\t\t  ", c);
2052         }
2053
2054         if (i->need_daemon_reload)
2055                 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2056                        ansi_highlight(true),
2057                        ansi_highlight(false),
2058                        arg_user ? "--user" : "--system");
2059 }
2060
2061 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2062
2063         switch (dbus_message_iter_get_arg_type(iter)) {
2064
2065         case DBUS_TYPE_STRING: {
2066                 const char *s;
2067
2068                 dbus_message_iter_get_basic(iter, &s);
2069
2070                 if (s[0]) {
2071                         if (streq(name, "Id"))
2072                                 i->id = s;
2073                         else if (streq(name, "LoadState"))
2074                                 i->load_state = s;
2075                         else if (streq(name, "ActiveState"))
2076                                 i->active_state = s;
2077                         else if (streq(name, "SubState"))
2078                                 i->sub_state = s;
2079                         else if (streq(name, "Description"))
2080                                 i->description = s;
2081                         else if (streq(name, "FragmentPath"))
2082                                 i->path = s;
2083 #ifdef HAVE_SYSV_COMPAT
2084                         else if (streq(name, "SysVPath")) {
2085                                 i->is_sysv = true;
2086                                 i->path = s;
2087                         }
2088 #endif
2089                         else if (streq(name, "DefaultControlGroup"))
2090                                 i->default_control_group = s;
2091                         else if (streq(name, "StatusText"))
2092                                 i->status_text = s;
2093                         else if (streq(name, "SysFSPath"))
2094                                 i->sysfs_path = s;
2095                         else if (streq(name, "Where"))
2096                                 i->where = s;
2097                         else if (streq(name, "What"))
2098                                 i->what = s;
2099                         else if (streq(name, "Following"))
2100                                 i->following = s;
2101                 }
2102
2103                 break;
2104         }
2105
2106         case DBUS_TYPE_BOOLEAN: {
2107                 dbus_bool_t b;
2108
2109                 dbus_message_iter_get_basic(iter, &b);
2110
2111                 if (streq(name, "Accept"))
2112                         i->accept = b;
2113                 else if (streq(name, "NeedDaemonReload"))
2114                         i->need_daemon_reload = b;
2115
2116                 break;
2117         }
2118
2119         case DBUS_TYPE_UINT32: {
2120                 uint32_t u;
2121
2122                 dbus_message_iter_get_basic(iter, &u);
2123
2124                 if (streq(name, "MainPID")) {
2125                         if (u > 0) {
2126                                 i->main_pid = (pid_t) u;
2127                                 i->running = true;
2128                         }
2129                 } else if (streq(name, "ControlPID"))
2130                         i->control_pid = (pid_t) u;
2131                 else if (streq(name, "ExecMainPID")) {
2132                         if (u > 0)
2133                                 i->main_pid = (pid_t) u;
2134                 } else if (streq(name, "NAccepted"))
2135                         i->n_accepted = u;
2136                 else if (streq(name, "NConnections"))
2137                         i->n_connections = u;
2138
2139                 break;
2140         }
2141
2142         case DBUS_TYPE_INT32: {
2143                 int32_t j;
2144
2145                 dbus_message_iter_get_basic(iter, &j);
2146
2147                 if (streq(name, "ExecMainCode"))
2148                         i->exit_code = (int) j;
2149                 else if (streq(name, "ExecMainStatus"))
2150                         i->exit_status = (int) j;
2151
2152                 break;
2153         }
2154
2155         case DBUS_TYPE_UINT64: {
2156                 uint64_t u;
2157
2158                 dbus_message_iter_get_basic(iter, &u);
2159
2160                 if (streq(name, "ExecMainStartTimestamp"))
2161                         i->start_timestamp = (usec_t) u;
2162                 else if (streq(name, "ExecMainExitTimestamp"))
2163                         i->exit_timestamp = (usec_t) u;
2164                 else if (streq(name, "ActiveEnterTimestamp"))
2165                         i->active_enter_timestamp = (usec_t) u;
2166                 else if (streq(name, "InactiveEnterTimestamp"))
2167                         i->inactive_enter_timestamp = (usec_t) u;
2168                 else if (streq(name, "InactiveExitTimestamp"))
2169                         i->inactive_exit_timestamp = (usec_t) u;
2170                 else if (streq(name, "ActiveExitTimestamp"))
2171                         i->active_exit_timestamp = (usec_t) u;
2172
2173                 break;
2174         }
2175
2176         case DBUS_TYPE_ARRAY: {
2177
2178                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2179                     startswith(name, "Exec")) {
2180                         DBusMessageIter sub;
2181
2182                         dbus_message_iter_recurse(iter, &sub);
2183                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2184                                 ExecStatusInfo *info;
2185                                 int r;
2186
2187                                 if (!(info = new0(ExecStatusInfo, 1)))
2188                                         return -ENOMEM;
2189
2190                                 if (!(info->name = strdup(name))) {
2191                                         free(info);
2192                                         return -ENOMEM;
2193                                 }
2194
2195                                 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2196                                         free(info);
2197                                         return r;
2198                                 }
2199
2200                                 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2201
2202                                 dbus_message_iter_next(&sub);
2203                         }
2204                 }
2205
2206                 break;
2207         }
2208         }
2209
2210         return 0;
2211 }
2212
2213 static int print_property(const char *name, DBusMessageIter *iter) {
2214         assert(name);
2215         assert(iter);
2216
2217         /* This is a low-level property printer, see
2218          * print_status_info() for the nicer output */
2219
2220         if (arg_property && !strv_find(arg_property, name))
2221                 return 0;
2222
2223         switch (dbus_message_iter_get_arg_type(iter)) {
2224
2225         case DBUS_TYPE_STRING: {
2226                 const char *s;
2227                 dbus_message_iter_get_basic(iter, &s);
2228
2229                 if (arg_all || s[0])
2230                         printf("%s=%s\n", name, s);
2231
2232                 return 0;
2233         }
2234
2235         case DBUS_TYPE_BOOLEAN: {
2236                 dbus_bool_t b;
2237                 dbus_message_iter_get_basic(iter, &b);
2238                 printf("%s=%s\n", name, yes_no(b));
2239
2240                 return 0;
2241         }
2242
2243         case DBUS_TYPE_UINT64: {
2244                 uint64_t u;
2245                 dbus_message_iter_get_basic(iter, &u);
2246
2247                 /* Yes, heuristics! But we can change this check
2248                  * should it turn out to not be sufficient */
2249
2250                 if (strstr(name, "Timestamp")) {
2251                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2252
2253                         if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2254                                 printf("%s=%s\n", name, strempty(t));
2255                 } else if (strstr(name, "USec")) {
2256                         char timespan[FORMAT_TIMESPAN_MAX];
2257
2258                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
2259                 } else
2260                         printf("%s=%llu\n", name, (unsigned long long) u);
2261
2262                 return 0;
2263         }
2264
2265         case DBUS_TYPE_UINT32: {
2266                 uint32_t u;
2267                 dbus_message_iter_get_basic(iter, &u);
2268
2269                 if (strstr(name, "UMask") || strstr(name, "Mode"))
2270                         printf("%s=%04o\n", name, u);
2271                 else
2272                         printf("%s=%u\n", name, (unsigned) u);
2273
2274                 return 0;
2275         }
2276
2277         case DBUS_TYPE_INT32: {
2278                 int32_t i;
2279                 dbus_message_iter_get_basic(iter, &i);
2280
2281                 printf("%s=%i\n", name, (int) i);
2282                 return 0;
2283         }
2284
2285         case DBUS_TYPE_DOUBLE: {
2286                 double d;
2287                 dbus_message_iter_get_basic(iter, &d);
2288
2289                 printf("%s=%g\n", name, d);
2290                 return 0;
2291         }
2292
2293         case DBUS_TYPE_STRUCT: {
2294                 DBusMessageIter sub;
2295                 dbus_message_iter_recurse(iter, &sub);
2296
2297                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
2298                         uint32_t u;
2299
2300                         dbus_message_iter_get_basic(&sub, &u);
2301
2302                         if (u)
2303                                 printf("%s=%u\n", name, (unsigned) u);
2304                         else if (arg_all)
2305                                 printf("%s=\n", name);
2306
2307                         return 0;
2308                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
2309                         const char *s;
2310
2311                         dbus_message_iter_get_basic(&sub, &s);
2312
2313                         if (arg_all || s[0])
2314                                 printf("%s=%s\n", name, s);
2315
2316                         return 0;
2317                 }
2318
2319                 break;
2320         }
2321
2322         case DBUS_TYPE_ARRAY:
2323
2324                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2325                         DBusMessageIter sub;
2326                         bool space = false;
2327
2328                         dbus_message_iter_recurse(iter, &sub);
2329                         if (arg_all ||
2330                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2331                                 printf("%s=", name);
2332
2333                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2334                                         const char *s;
2335
2336                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2337                                         dbus_message_iter_get_basic(&sub, &s);
2338                                         printf("%s%s", space ? " " : "", s);
2339
2340                                         space = true;
2341                                         dbus_message_iter_next(&sub);
2342                                 }
2343
2344                                 puts("");
2345                         }
2346
2347                         return 0;
2348
2349                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2350                         DBusMessageIter sub;
2351
2352                         dbus_message_iter_recurse(iter, &sub);
2353                         if (arg_all ||
2354                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2355                                 printf("%s=", name);
2356
2357                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2358                                         uint8_t u;
2359
2360                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2361                                         dbus_message_iter_get_basic(&sub, &u);
2362                                         printf("%02x", u);
2363
2364                                         dbus_message_iter_next(&sub);
2365                                 }
2366
2367                                 puts("");
2368                         }
2369
2370                         return 0;
2371
2372                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2373                         DBusMessageIter sub, sub2;
2374
2375                         dbus_message_iter_recurse(iter, &sub);
2376                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2377                                 const char *type, *path;
2378
2379                                 dbus_message_iter_recurse(&sub, &sub2);
2380
2381                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2382                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2383                                         printf("%s=%s\n", type, path);
2384
2385                                 dbus_message_iter_next(&sub);
2386                         }
2387
2388                         return 0;
2389
2390                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2391                         DBusMessageIter sub, sub2;
2392
2393                         dbus_message_iter_recurse(iter, &sub);
2394                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2395                                 const char *base;
2396                                 uint64_t value, next_elapse;
2397
2398                                 dbus_message_iter_recurse(&sub, &sub2);
2399
2400                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2401                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2402                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2403                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2404
2405                                         printf("%s={ value=%s ; next_elapse=%s }\n",
2406                                                base,
2407                                                format_timespan(timespan1, sizeof(timespan1), value),
2408                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
2409                                 }
2410
2411                                 dbus_message_iter_next(&sub);
2412                         }
2413
2414                         return 0;
2415
2416                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2417                         DBusMessageIter sub;
2418
2419                         dbus_message_iter_recurse(iter, &sub);
2420                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2421                                 ExecStatusInfo info;
2422
2423                                 zero(info);
2424                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2425                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2426                                         char *t;
2427
2428                                         t = strv_join(info.argv, " ");
2429
2430                                         printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2431                                                name,
2432                                                strna(info.path),
2433                                                strna(t),
2434                                                yes_no(info.ignore),
2435                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2436                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2437                                                (unsigned) info. pid,
2438                                                sigchld_code_to_string(info.code),
2439                                                info.status,
2440                                                info.code == CLD_EXITED ? "" : "/",
2441                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2442
2443                                         free(t);
2444                                 }
2445
2446                                 free(info.path);
2447                                 strv_free(info.argv);
2448
2449                                 dbus_message_iter_next(&sub);
2450                         }
2451
2452                         return 0;
2453                 }
2454
2455                 break;
2456         }
2457
2458         if (arg_all)
2459                 printf("%s=[unprintable]\n", name);
2460
2461         return 0;
2462 }
2463
2464 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2465         DBusMessage *m = NULL, *reply = NULL;
2466         const char *interface = "";
2467         int r;
2468         DBusError error;
2469         DBusMessageIter iter, sub, sub2, sub3;
2470         UnitStatusInfo info;
2471         ExecStatusInfo *p;
2472
2473         assert(bus);
2474         assert(path);
2475         assert(new_line);
2476
2477         zero(info);
2478         dbus_error_init(&error);
2479
2480         if (!(m = dbus_message_new_method_call(
2481                               "org.freedesktop.systemd1",
2482                               path,
2483                               "org.freedesktop.DBus.Properties",
2484                               "GetAll"))) {
2485                 log_error("Could not allocate message.");
2486                 r = -ENOMEM;
2487                 goto finish;
2488         }
2489
2490         if (!dbus_message_append_args(m,
2491                                       DBUS_TYPE_STRING, &interface,
2492                                       DBUS_TYPE_INVALID)) {
2493                 log_error("Could not append arguments to message.");
2494                 r = -ENOMEM;
2495                 goto finish;
2496         }
2497
2498         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2499                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2500                 r = -EIO;
2501                 goto finish;
2502         }
2503
2504         if (!dbus_message_iter_init(reply, &iter) ||
2505             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2506             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
2507                 log_error("Failed to parse reply.");
2508                 r = -EIO;
2509                 goto finish;
2510         }
2511
2512         dbus_message_iter_recurse(&iter, &sub);
2513
2514         if (*new_line)
2515                 printf("\n");
2516
2517         *new_line = true;
2518
2519         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2520                 const char *name;
2521
2522                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2523                         log_error("Failed to parse reply.");
2524                         r = -EIO;
2525                         goto finish;
2526                 }
2527
2528                 dbus_message_iter_recurse(&sub, &sub2);
2529
2530                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2531                         log_error("Failed to parse reply.");
2532                         r = -EIO;
2533                         goto finish;
2534                 }
2535
2536                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
2537                         log_error("Failed to parse reply.");
2538                         r = -EIO;
2539                         goto finish;
2540                 }
2541
2542                 dbus_message_iter_recurse(&sub2, &sub3);
2543
2544                 if (show_properties)
2545                         r = print_property(name, &sub3);
2546                 else
2547                         r = status_property(name, &sub3, &info);
2548
2549                 if (r < 0) {
2550                         log_error("Failed to parse reply.");
2551                         r = -EIO;
2552                         goto finish;
2553                 }
2554
2555                 dbus_message_iter_next(&sub);
2556         }
2557
2558         r = 0;
2559
2560         if (!show_properties)
2561                 print_status_info(&info);
2562
2563         if (!streq_ptr(info.active_state, "active") &&
2564             !streq_ptr(info.active_state, "reloading") &&
2565             streq(verb, "status"))
2566                 /* According to LSB: "program not running" */
2567                 r = 3;
2568
2569         while ((p = info.exec)) {
2570                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2571                 exec_status_info_free(p);
2572         }
2573
2574 finish:
2575         if (m)
2576                 dbus_message_unref(m);
2577
2578         if (reply)
2579                 dbus_message_unref(reply);
2580
2581         dbus_error_free(&error);
2582
2583         return r;
2584 }
2585
2586 static int show(DBusConnection *bus, char **args, unsigned n) {
2587         DBusMessage *m = NULL, *reply = NULL;
2588         int r, ret = 0;
2589         DBusError error;
2590         unsigned i;
2591         bool show_properties, new_line = false;
2592
2593         assert(bus);
2594         assert(args);
2595
2596         dbus_error_init(&error);
2597
2598         show_properties = !streq(args[0], "status");
2599
2600         if (show_properties)
2601                 pager_open();
2602
2603         if (show_properties && n <= 1) {
2604                 /* If not argument is specified inspect the manager
2605                  * itself */
2606
2607                 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2608                 goto finish;
2609         }
2610
2611         for (i = 1; i < n; i++) {
2612                 const char *path = NULL;
2613                 uint32_t id;
2614
2615                 if (safe_atou32(args[i], &id) < 0) {
2616
2617                         /* Interpret as unit name */
2618
2619                         if (!(m = dbus_message_new_method_call(
2620                                               "org.freedesktop.systemd1",
2621                                               "/org/freedesktop/systemd1",
2622                                               "org.freedesktop.systemd1.Manager",
2623                                               "LoadUnit"))) {
2624                                 log_error("Could not allocate message.");
2625                                 ret = -ENOMEM;
2626                                 goto finish;
2627                         }
2628
2629                         if (!dbus_message_append_args(m,
2630                                                       DBUS_TYPE_STRING, &args[i],
2631                                                       DBUS_TYPE_INVALID)) {
2632                                 log_error("Could not append arguments to message.");
2633                                 ret = -ENOMEM;
2634                                 goto finish;
2635                         }
2636
2637                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2638
2639                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2640                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2641                                         ret = -EIO;
2642                                         goto finish;
2643                                 }
2644
2645                                 dbus_error_free(&error);
2646
2647                                 dbus_message_unref(m);
2648                                 if (!(m = dbus_message_new_method_call(
2649                                                       "org.freedesktop.systemd1",
2650                                                       "/org/freedesktop/systemd1",
2651                                                       "org.freedesktop.systemd1.Manager",
2652                                                       "GetUnit"))) {
2653                                         log_error("Could not allocate message.");
2654                                         ret = -ENOMEM;
2655                                         goto finish;
2656                                 }
2657
2658                                 if (!dbus_message_append_args(m,
2659                                                               DBUS_TYPE_STRING, &args[i],
2660                                                               DBUS_TYPE_INVALID)) {
2661                                         log_error("Could not append arguments to message.");
2662                                         ret = -ENOMEM;
2663                                         goto finish;
2664                                 }
2665
2666                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2667                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2668
2669                                         if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2670                                                 ret = 4; /* According to LSB: "program or service status is unknown" */
2671                                         else
2672                                                 ret = -EIO;
2673                                         goto finish;
2674                                 }
2675                         }
2676
2677                 } else if (show_properties) {
2678
2679                         /* Interpret as job id */
2680
2681                         if (!(m = dbus_message_new_method_call(
2682                                               "org.freedesktop.systemd1",
2683                                               "/org/freedesktop/systemd1",
2684                                               "org.freedesktop.systemd1.Manager",
2685                                               "GetJob"))) {
2686                                 log_error("Could not allocate message.");
2687                                 ret = -ENOMEM;
2688                                 goto finish;
2689                         }
2690
2691                         if (!dbus_message_append_args(m,
2692                                                       DBUS_TYPE_UINT32, &id,
2693                                                       DBUS_TYPE_INVALID)) {
2694                                 log_error("Could not append arguments to message.");
2695                                 ret = -ENOMEM;
2696                                 goto finish;
2697                         }
2698
2699                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2700                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2701                                 ret = -EIO;
2702                                 goto finish;
2703                         }
2704                 } else {
2705
2706                         /* Interpret as PID */
2707
2708                         if (!(m = dbus_message_new_method_call(
2709                                               "org.freedesktop.systemd1",
2710                                               "/org/freedesktop/systemd1",
2711                                               "org.freedesktop.systemd1.Manager",
2712                                               "GetUnitByPID"))) {
2713                                 log_error("Could not allocate message.");
2714                                 ret = -ENOMEM;
2715                                 goto finish;
2716                         }
2717
2718                         if (!dbus_message_append_args(m,
2719                                                       DBUS_TYPE_UINT32, &id,
2720                                                       DBUS_TYPE_INVALID)) {
2721                                 log_error("Could not append arguments to message.");
2722                                 ret = -ENOMEM;
2723                                 goto finish;
2724                         }
2725
2726                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2727                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2728                                 ret = -EIO;
2729                                 goto finish;
2730                         }
2731                 }
2732
2733                 if (!dbus_message_get_args(reply, &error,
2734                                            DBUS_TYPE_OBJECT_PATH, &path,
2735                                            DBUS_TYPE_INVALID)) {
2736                         log_error("Failed to parse reply: %s", bus_error_message(&error));
2737                         ret = -EIO;
2738                         goto finish;
2739                 }
2740
2741                 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2742                         ret = r;
2743
2744                 dbus_message_unref(m);
2745                 dbus_message_unref(reply);
2746                 m = reply = NULL;
2747         }
2748
2749 finish:
2750         if (m)
2751                 dbus_message_unref(m);
2752
2753         if (reply)
2754                 dbus_message_unref(reply);
2755
2756         dbus_error_free(&error);
2757
2758         return ret;
2759 }
2760
2761 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2762         DBusError error;
2763         DBusMessage *m = NULL, *reply = NULL;
2764
2765         assert(connection);
2766         assert(message);
2767
2768         dbus_error_init(&error);
2769
2770         log_debug("Got D-Bus request: %s.%s() on %s",
2771                   dbus_message_get_interface(message),
2772                   dbus_message_get_member(message),
2773                   dbus_message_get_path(message));
2774
2775         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2776                 log_error("Warning! D-Bus connection terminated.");
2777                 dbus_connection_close(connection);
2778
2779         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2780                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2781                 const char *id, *path;
2782
2783                 if (!dbus_message_get_args(message, &error,
2784                                            DBUS_TYPE_STRING, &id,
2785                                            DBUS_TYPE_OBJECT_PATH, &path,
2786                                            DBUS_TYPE_INVALID))
2787                         log_error("Failed to parse message: %s", bus_error_message(&error));
2788                 else if (streq(dbus_message_get_member(message), "UnitNew"))
2789                         printf("Unit %s added.\n", id);
2790                 else
2791                         printf("Unit %s removed.\n", id);
2792
2793         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2794                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2795                 uint32_t id;
2796                 const char *path, *result;
2797
2798                 if (!dbus_message_get_args(message, &error,
2799                                            DBUS_TYPE_UINT32, &id,
2800                                            DBUS_TYPE_OBJECT_PATH, &path,
2801                                            DBUS_TYPE_STRING, &result,
2802                                            DBUS_TYPE_INVALID))
2803                         log_error("Failed to parse message: %s", bus_error_message(&error));
2804                 else if (streq(dbus_message_get_member(message), "JobNew"))
2805                         printf("Job %u added.\n", id);
2806                 else
2807                         printf("Job %u removed.\n", id);
2808
2809
2810         } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
2811
2812                 const char *path, *interface, *property = "Id";
2813                 DBusMessageIter iter, sub;
2814
2815                 path = dbus_message_get_path(message);
2816
2817                 if (!dbus_message_get_args(message, &error,
2818                                           DBUS_TYPE_STRING, &interface,
2819                                           DBUS_TYPE_INVALID)) {
2820                         log_error("Failed to parse message: %s", bus_error_message(&error));
2821                         goto finish;
2822                 }
2823
2824                 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2825                     !streq(interface, "org.freedesktop.systemd1.Unit"))
2826                         goto finish;
2827
2828                 if (!(m = dbus_message_new_method_call(
2829                               "org.freedesktop.systemd1",
2830                               path,
2831                               "org.freedesktop.DBus.Properties",
2832                               "Get"))) {
2833                         log_error("Could not allocate message.");
2834                         goto oom;
2835                 }
2836
2837                 if (!dbus_message_append_args(m,
2838                                               DBUS_TYPE_STRING, &interface,
2839                                               DBUS_TYPE_STRING, &property,
2840                                               DBUS_TYPE_INVALID)) {
2841                         log_error("Could not append arguments to message.");
2842                         goto finish;
2843                 }
2844
2845                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2846                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2847                         goto finish;
2848                 }
2849
2850                 if (!dbus_message_iter_init(reply, &iter) ||
2851                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2852                         log_error("Failed to parse reply.");
2853                         goto finish;
2854                 }
2855
2856                 dbus_message_iter_recurse(&iter, &sub);
2857
2858                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2859                         const char *id;
2860
2861                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2862                                 log_error("Failed to parse reply.");
2863                                 goto finish;
2864                         }
2865
2866                         dbus_message_iter_get_basic(&sub, &id);
2867                         printf("Unit %s changed.\n", id);
2868                 } else {
2869                         uint32_t id;
2870
2871                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2872                                 log_error("Failed to parse reply.");
2873                                 goto finish;
2874                         }
2875
2876                         dbus_message_iter_get_basic(&sub, &id);
2877                         printf("Job %u changed.\n", id);
2878                 }
2879         }
2880
2881 finish:
2882         if (m)
2883                 dbus_message_unref(m);
2884
2885         if (reply)
2886                 dbus_message_unref(reply);
2887
2888         dbus_error_free(&error);
2889         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2890
2891 oom:
2892         if (m)
2893                 dbus_message_unref(m);
2894
2895         if (reply)
2896                 dbus_message_unref(reply);
2897
2898         dbus_error_free(&error);
2899         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2900 }
2901
2902 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2903         DBusMessage *m = NULL, *reply = NULL;
2904         DBusError error;
2905         int r;
2906
2907         dbus_error_init(&error);
2908
2909         if (!private_bus) {
2910                 dbus_bus_add_match(bus,
2911                                    "type='signal',"
2912                                    "sender='org.freedesktop.systemd1',"
2913                                    "interface='org.freedesktop.systemd1.Manager',"
2914                                    "path='/org/freedesktop/systemd1'",
2915                                    &error);
2916
2917                 if (dbus_error_is_set(&error)) {
2918                         log_error("Failed to add match: %s", bus_error_message(&error));
2919                         r = -EIO;
2920                         goto finish;
2921                 }
2922
2923                 dbus_bus_add_match(bus,
2924                                    "type='signal',"
2925                                    "sender='org.freedesktop.systemd1',"
2926                                    "interface='org.freedesktop.DBus.Properties',"
2927                                    "member='PropertiesChanged'",
2928                                    &error);
2929
2930                 if (dbus_error_is_set(&error)) {
2931                         log_error("Failed to add match: %s", bus_error_message(&error));
2932                         r = -EIO;
2933                         goto finish;
2934                 }
2935         }
2936
2937         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2938                 log_error("Failed to add filter.");
2939                 r = -ENOMEM;
2940                 goto finish;
2941         }
2942
2943         if (!(m = dbus_message_new_method_call(
2944                               "org.freedesktop.systemd1",
2945                               "/org/freedesktop/systemd1",
2946                               "org.freedesktop.systemd1.Manager",
2947                               "Subscribe"))) {
2948                 log_error("Could not allocate message.");
2949                 r = -ENOMEM;
2950                 goto finish;
2951         }
2952
2953         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2954                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2955                 r = -EIO;
2956                 goto finish;
2957         }
2958
2959         while (dbus_connection_read_write_dispatch(bus, -1))
2960                 ;
2961
2962         r = 0;
2963
2964 finish:
2965
2966         /* This is slightly dirty, since we don't undo the filter or the matches. */
2967
2968         if (m)
2969                 dbus_message_unref(m);
2970
2971         if (reply)
2972                 dbus_message_unref(reply);
2973
2974         dbus_error_free(&error);
2975
2976         return r;
2977 }
2978
2979 static int dump(DBusConnection *bus, char **args, unsigned n) {
2980         DBusMessage *m = NULL, *reply = NULL;
2981         DBusError error;
2982         int r;
2983         const char *text;
2984
2985         dbus_error_init(&error);
2986
2987         pager_open();
2988
2989         if (!(m = dbus_message_new_method_call(
2990                               "org.freedesktop.systemd1",
2991                               "/org/freedesktop/systemd1",
2992                               "org.freedesktop.systemd1.Manager",
2993                               "Dump"))) {
2994                 log_error("Could not allocate message.");
2995                 return -ENOMEM;
2996         }
2997
2998         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2999                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3000                 r = -EIO;
3001                 goto finish;
3002         }
3003
3004         if (!dbus_message_get_args(reply, &error,
3005                                    DBUS_TYPE_STRING, &text,
3006                                    DBUS_TYPE_INVALID)) {
3007                 log_error("Failed to parse reply: %s", bus_error_message(&error));
3008                 r = -EIO;
3009                 goto finish;
3010         }
3011
3012         fputs(text, stdout);
3013
3014         r = 0;
3015
3016 finish:
3017         if (m)
3018                 dbus_message_unref(m);
3019
3020         if (reply)
3021                 dbus_message_unref(reply);
3022
3023         dbus_error_free(&error);
3024
3025         return r;
3026 }
3027
3028 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3029         DBusMessage *m = NULL, *reply = NULL;
3030         DBusError error;
3031         int r;
3032         const char *name = "", *path, *id;
3033         dbus_bool_t cleanup = FALSE;
3034         DBusMessageIter iter, sub;
3035         const char
3036                 *interface = "org.freedesktop.systemd1.Unit",
3037                 *property = "Id";
3038
3039         dbus_error_init(&error);
3040
3041         if (!(m = dbus_message_new_method_call(
3042                               "org.freedesktop.systemd1",
3043                               "/org/freedesktop/systemd1",
3044                               "org.freedesktop.systemd1.Manager",
3045                               "CreateSnapshot"))) {
3046                 log_error("Could not allocate message.");
3047                 return -ENOMEM;
3048         }
3049
3050         if (n > 1)
3051                 name = args[1];
3052
3053         if (!dbus_message_append_args(m,
3054                                       DBUS_TYPE_STRING, &name,
3055                                       DBUS_TYPE_BOOLEAN, &cleanup,
3056                                       DBUS_TYPE_INVALID)) {
3057                 log_error("Could not append arguments to message.");
3058                 r = -ENOMEM;
3059                 goto finish;
3060         }
3061
3062         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3063                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3064                 r = -EIO;
3065                 goto finish;
3066         }
3067
3068         if (!dbus_message_get_args(reply, &error,
3069                                    DBUS_TYPE_OBJECT_PATH, &path,
3070                                    DBUS_TYPE_INVALID)) {
3071                 log_error("Failed to parse reply: %s", bus_error_message(&error));
3072                 r = -EIO;
3073                 goto finish;
3074         }
3075
3076         dbus_message_unref(m);
3077         if (!(m = dbus_message_new_method_call(
3078                               "org.freedesktop.systemd1",
3079                               path,
3080                               "org.freedesktop.DBus.Properties",
3081                               "Get"))) {
3082                 log_error("Could not allocate message.");
3083                 return -ENOMEM;
3084         }
3085
3086         if (!dbus_message_append_args(m,
3087                                       DBUS_TYPE_STRING, &interface,
3088                                       DBUS_TYPE_STRING, &property,
3089                                       DBUS_TYPE_INVALID)) {
3090                 log_error("Could not append arguments to message.");
3091                 r = -ENOMEM;
3092                 goto finish;
3093         }
3094
3095         dbus_message_unref(reply);
3096         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3097                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3098                 r = -EIO;
3099                 goto finish;
3100         }
3101
3102         if (!dbus_message_iter_init(reply, &iter) ||
3103             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3104                 log_error("Failed to parse reply.");
3105                 r = -EIO;
3106                 goto finish;
3107         }
3108
3109         dbus_message_iter_recurse(&iter, &sub);
3110
3111         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
3112                 log_error("Failed to parse reply.");
3113                 r = -EIO;
3114                 goto finish;
3115         }
3116
3117         dbus_message_iter_get_basic(&sub, &id);
3118
3119         if (!arg_quiet)
3120                 puts(id);
3121         r = 0;
3122
3123 finish:
3124         if (m)
3125                 dbus_message_unref(m);
3126
3127         if (reply)
3128                 dbus_message_unref(reply);
3129
3130         dbus_error_free(&error);
3131
3132         return r;
3133 }
3134
3135 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3136         DBusMessage *m = NULL, *reply = NULL;
3137         int r;
3138         DBusError error;
3139         unsigned i;
3140
3141         assert(bus);
3142         assert(args);
3143
3144         dbus_error_init(&error);
3145
3146         for (i = 1; i < n; i++) {
3147                 const char *path = NULL;
3148
3149                 if (!(m = dbus_message_new_method_call(
3150                                       "org.freedesktop.systemd1",
3151                                       "/org/freedesktop/systemd1",
3152                                       "org.freedesktop.systemd1.Manager",
3153                                       "GetUnit"))) {
3154                         log_error("Could not allocate message.");
3155                         r = -ENOMEM;
3156                         goto finish;
3157                 }
3158
3159                 if (!dbus_message_append_args(m,
3160                                               DBUS_TYPE_STRING, &args[i],
3161                                               DBUS_TYPE_INVALID)) {
3162                         log_error("Could not append arguments to message.");
3163                         r = -ENOMEM;
3164                         goto finish;
3165                 }
3166
3167                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3168                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3169                         r = -EIO;
3170                         goto finish;
3171                 }
3172
3173                 if (!dbus_message_get_args(reply, &error,
3174                                            DBUS_TYPE_OBJECT_PATH, &path,
3175                                            DBUS_TYPE_INVALID)) {
3176                         log_error("Failed to parse reply: %s", bus_error_message(&error));
3177                         r = -EIO;
3178                         goto finish;
3179                 }
3180
3181                 dbus_message_unref(m);
3182                 if (!(m = dbus_message_new_method_call(
3183                                       "org.freedesktop.systemd1",
3184                                       path,
3185                                       "org.freedesktop.systemd1.Snapshot",
3186                                       "Remove"))) {
3187                         log_error("Could not allocate message.");
3188                         r = -ENOMEM;
3189                         goto finish;
3190                 }
3191
3192                 dbus_message_unref(reply);
3193                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3194                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3195                         r = -EIO;
3196                         goto finish;
3197                 }
3198
3199                 dbus_message_unref(m);
3200                 dbus_message_unref(reply);
3201                 m = reply = NULL;
3202         }
3203
3204         r = 0;
3205
3206 finish:
3207         if (m)
3208                 dbus_message_unref(m);
3209
3210         if (reply)
3211                 dbus_message_unref(reply);
3212
3213         dbus_error_free(&error);
3214
3215         return r;
3216 }
3217
3218 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
3219         DBusMessage *m = NULL, *reply = NULL;
3220         DBusError error;
3221         int r;
3222         const char *method;
3223
3224         dbus_error_init(&error);
3225
3226         if (arg_action == ACTION_RELOAD)
3227                 method = "Reload";
3228         else if (arg_action == ACTION_REEXEC)
3229                 method = "Reexecute";
3230         else {
3231                 assert(arg_action == ACTION_SYSTEMCTL);
3232
3233                 method =
3234                         streq(args[0], "clear-jobs")    ||
3235                         streq(args[0], "cancel")        ? "ClearJobs" :
3236                         streq(args[0], "daemon-reexec") ? "Reexecute" :
3237                         streq(args[0], "reset-failed")  ? "ResetFailed" :
3238                         streq(args[0], "halt")          ? "Halt" :
3239                         streq(args[0], "poweroff")      ? "PowerOff" :
3240                         streq(args[0], "reboot")        ? "Reboot" :
3241                         streq(args[0], "kexec")         ? "KExec" :
3242                         streq(args[0], "exit")          ? "Exit" :
3243                                     /* "daemon-reload" */ "Reload";
3244         }
3245
3246         if (!(m = dbus_message_new_method_call(
3247                               "org.freedesktop.systemd1",
3248                               "/org/freedesktop/systemd1",
3249                               "org.freedesktop.systemd1.Manager",
3250                               method))) {
3251                 log_error("Could not allocate message.");
3252                 return -ENOMEM;
3253         }
3254
3255         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3256
3257                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3258                         /* There's always a fallback possible for
3259                          * legacy actions. */
3260                         r = -EADDRNOTAVAIL;
3261                         goto finish;
3262                 }
3263
3264                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3265                 r = -EIO;
3266                 goto finish;
3267         }
3268
3269         r = 0;
3270
3271 finish:
3272         if (m)
3273                 dbus_message_unref(m);
3274
3275         if (reply)
3276                 dbus_message_unref(reply);
3277
3278         dbus_error_free(&error);
3279
3280         return r;
3281 }
3282
3283 static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
3284         DBusMessage *m = NULL, *reply = NULL;
3285         unsigned i;
3286         int r;
3287         DBusError error;
3288
3289         assert(bus);
3290         dbus_error_init(&error);
3291
3292         if (n <= 1)
3293                 return daemon_reload(bus, args, n);
3294
3295         for (i = 1; i < n; i++) {
3296
3297                 if (!(m = dbus_message_new_method_call(
3298                                       "org.freedesktop.systemd1",
3299                                       "/org/freedesktop/systemd1",
3300                                       "org.freedesktop.systemd1.Manager",
3301                                       "ResetFailedUnit"))) {
3302                         log_error("Could not allocate message.");
3303                         r = -ENOMEM;
3304                         goto finish;
3305                 }
3306
3307                 if (!dbus_message_append_args(m,
3308                                               DBUS_TYPE_STRING, args + i,
3309                                               DBUS_TYPE_INVALID)) {
3310                         log_error("Could not append arguments to message.");
3311                         r = -ENOMEM;
3312                         goto finish;
3313                 }
3314
3315                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3316                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3317                         r = -EIO;
3318                         goto finish;
3319                 }
3320
3321                 dbus_message_unref(m);
3322                 dbus_message_unref(reply);
3323                 m = reply = NULL;
3324         }
3325
3326         r = 0;
3327
3328 finish:
3329         if (m)
3330                 dbus_message_unref(m);
3331
3332         if (reply)
3333                 dbus_message_unref(reply);
3334
3335         dbus_error_free(&error);
3336
3337         return r;
3338 }
3339
3340 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3341         DBusMessage *m = NULL, *reply = NULL;
3342         DBusError error;
3343         DBusMessageIter iter, sub, sub2;
3344         int r;
3345         const char
3346                 *interface = "org.freedesktop.systemd1.Manager",
3347                 *property = "Environment";
3348
3349         dbus_error_init(&error);
3350
3351         pager_open();
3352
3353         if (!(m = dbus_message_new_method_call(
3354                               "org.freedesktop.systemd1",
3355                               "/org/freedesktop/systemd1",
3356                               "org.freedesktop.DBus.Properties",
3357                               "Get"))) {
3358                 log_error("Could not allocate message.");
3359                 return -ENOMEM;
3360         }
3361
3362         if (!dbus_message_append_args(m,
3363                                       DBUS_TYPE_STRING, &interface,
3364                                       DBUS_TYPE_STRING, &property,
3365                                       DBUS_TYPE_INVALID)) {
3366                 log_error("Could not append arguments to message.");
3367                 r = -ENOMEM;
3368                 goto finish;
3369         }
3370
3371         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3372                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3373                 r = -EIO;
3374                 goto finish;
3375         }
3376
3377         if (!dbus_message_iter_init(reply, &iter) ||
3378             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3379                 log_error("Failed to parse reply.");
3380                 r = -EIO;
3381                 goto finish;
3382         }
3383
3384         dbus_message_iter_recurse(&iter, &sub);
3385
3386         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3387             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
3388                 log_error("Failed to parse reply.");
3389                 r = -EIO;
3390                 goto finish;
3391         }
3392
3393         dbus_message_iter_recurse(&sub, &sub2);
3394
3395         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3396                 const char *text;
3397
3398                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3399                         log_error("Failed to parse reply.");
3400                         r = -EIO;
3401                         goto finish;
3402                 }
3403
3404                 dbus_message_iter_get_basic(&sub2, &text);
3405                 printf("%s\n", text);
3406
3407                 dbus_message_iter_next(&sub2);
3408         }
3409
3410         r = 0;
3411
3412 finish:
3413         if (m)
3414                 dbus_message_unref(m);
3415
3416         if (reply)
3417                 dbus_message_unref(reply);
3418
3419         dbus_error_free(&error);
3420
3421         return r;
3422 }
3423
3424 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3425         DBusMessage *m = NULL, *reply = NULL;
3426         DBusError error;
3427         int r;
3428         const char *method;
3429         DBusMessageIter iter, sub;
3430         unsigned i;
3431
3432         dbus_error_init(&error);
3433
3434         method = streq(args[0], "set-environment")
3435                 ? "SetEnvironment"
3436                 : "UnsetEnvironment";
3437
3438         if (!(m = dbus_message_new_method_call(
3439                               "org.freedesktop.systemd1",
3440                               "/org/freedesktop/systemd1",
3441                               "org.freedesktop.systemd1.Manager",
3442                               method))) {
3443
3444                 log_error("Could not allocate message.");
3445                 return -ENOMEM;
3446         }
3447
3448         dbus_message_iter_init_append(m, &iter);
3449
3450         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3451                 log_error("Could not append arguments to message.");
3452                 r = -ENOMEM;
3453                 goto finish;
3454         }
3455
3456         for (i = 1; i < n; i++)
3457                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3458                         log_error("Could not append arguments to message.");
3459                         r = -ENOMEM;
3460                         goto finish;
3461                 }
3462
3463         if (!dbus_message_iter_close_container(&iter, &sub)) {
3464                 log_error("Could not append arguments to message.");
3465                 r = -ENOMEM;
3466                 goto finish;
3467         }
3468
3469         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3470                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3471                 r = -EIO;
3472                 goto finish;
3473         }
3474
3475         r = 0;
3476
3477 finish:
3478         if (m)
3479                 dbus_message_unref(m);
3480
3481         if (reply)
3482                 dbus_message_unref(reply);
3483
3484         dbus_error_free(&error);
3485
3486         return r;
3487 }
3488
3489 typedef struct {
3490         char *name;
3491         char *path;
3492
3493         char **aliases;
3494         char **wanted_by;
3495 } InstallInfo;
3496
3497 static Hashmap *will_install = NULL, *have_installed = NULL;
3498 static Set *remove_symlinks_to = NULL;
3499 static unsigned n_symlinks = 0;
3500
3501 static void install_info_free(InstallInfo *i) {
3502         assert(i);
3503
3504         free(i->name);
3505         free(i->path);
3506         strv_free(i->aliases);
3507         strv_free(i->wanted_by);
3508         free(i);
3509 }
3510
3511 static void install_info_hashmap_free(Hashmap *m) {
3512         InstallInfo *i;
3513
3514         while ((i = hashmap_steal_first(m)))
3515                 install_info_free(i);
3516
3517         hashmap_free(m);
3518 }
3519
3520 static int install_info_add(const char *name) {
3521         InstallInfo *i;
3522         int r;
3523
3524         assert(will_install);
3525
3526         if (!unit_name_is_valid_no_type(name, true)) {
3527                 log_warning("Unit name %s is not a valid unit name.", name);
3528                 return -EINVAL;
3529         }
3530
3531         if (hashmap_get(have_installed, name) ||
3532             hashmap_get(will_install, name))
3533                 return 0;
3534
3535         if (!(i = new0(InstallInfo, 1))) {
3536                 r = -ENOMEM;
3537                 goto fail;
3538         }
3539
3540         if (!(i->name = strdup(name))) {
3541                 r = -ENOMEM;
3542                 goto fail;
3543         }
3544
3545         if ((r = hashmap_put(will_install, i->name, i)) < 0)
3546                 goto fail;
3547
3548         return 0;
3549
3550 fail:
3551         if (i)
3552                 install_info_free(i);
3553
3554         return r;
3555 }
3556
3557 static int config_parse_also(
3558                 const char *filename,
3559                 unsigned line,
3560                 const char *section,
3561                 const char *lvalue,
3562                 const char *rvalue,
3563                 void *data,
3564                 void *userdata) {
3565
3566         char *w;
3567         size_t l;
3568         char *state;
3569
3570         assert(filename);
3571         assert(lvalue);
3572         assert(rvalue);
3573
3574         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3575                 char *n;
3576                 int r;
3577
3578                 if (!(n = strndup(w, l)))
3579                         return -ENOMEM;
3580
3581                 if ((r = install_info_add(n)) < 0) {
3582                         log_warning("Cannot install unit %s: %s", n, strerror(-r));
3583                         free(n);
3584                         return r;
3585                 }
3586
3587                 free(n);
3588         }
3589
3590         return 0;
3591 }
3592
3593 static int mark_symlink_for_removal(const char *p) {
3594         char *n;
3595         int r;
3596
3597         assert(p);
3598         assert(path_is_absolute(p));
3599
3600         if (!remove_symlinks_to)
3601                 return 0;
3602
3603         if (!(n = strdup(p)))
3604                 return -ENOMEM;
3605
3606         path_kill_slashes(n);
3607
3608         if ((r = set_put(remove_symlinks_to, n)) < 0) {
3609                 free(n);
3610                 return r == -EEXIST ? 0 : r;
3611         }
3612
3613         return 0;
3614 }
3615
3616 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3617         int r = 0;
3618         DIR *d;
3619         struct dirent *de;
3620
3621         assert(fd >= 0);
3622         assert(root);
3623         assert(deleted);
3624
3625         if (!(d = fdopendir(fd))) {
3626                 close_nointr_nofail(fd);
3627                 return -errno;
3628         }
3629
3630         rewinddir(d);
3631
3632         while ((de = readdir(d))) {
3633                 bool is_dir = false, is_link = false;
3634
3635                 if (ignore_file(de->d_name))
3636                         continue;
3637
3638                 if (de->d_type == DT_LNK)
3639                         is_link = true;
3640                 else if (de->d_type == DT_DIR)
3641                         is_dir = true;
3642                 else if (de->d_type == DT_UNKNOWN) {
3643                         struct stat st;
3644
3645                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3646                                 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3647
3648                                 if (r == 0)
3649                                         r = -errno;
3650                                 continue;
3651                         }
3652
3653                         is_link = S_ISLNK(st.st_mode);
3654                         is_dir = S_ISDIR(st.st_mode);
3655                 } else
3656                         continue;
3657
3658                 if (is_dir) {
3659                         int nfd, q;
3660                         char *p;
3661
3662                         if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3663                                 log_error("Failed to open %s/%s: %m", root, de->d_name);
3664
3665                                 if (r == 0)
3666                                         r = -errno;
3667                                 continue;
3668                         }
3669
3670                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3671                                 log_error("Failed to allocate directory string.");
3672                                 close_nointr_nofail(nfd);
3673                                 r = -ENOMEM;
3674                                 break;
3675                         }
3676
3677                         /* This will close nfd, regardless whether it succeeds or not */
3678                         q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3679                         free(p);
3680
3681                         if (r == 0)
3682                                 r = q;
3683
3684                 } else if (is_link) {
3685                         char *p, *dest, *c;
3686                         int q;
3687
3688                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3689                                 log_error("Failed to allocate symlink string.");
3690                                 r = -ENOMEM;
3691                                 break;
3692                         }
3693
3694                         if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3695                                 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3696                                 free(p);
3697
3698                                 if (r == 0)
3699                                         r = q;
3700                                 continue;
3701                         }
3702
3703                         if ((c = canonicalize_file_name(dest))) {
3704                                 /* This might fail if the destination
3705                                  * is already removed */
3706
3707                                 free(dest);
3708                                 dest = c;
3709                         }
3710
3711                         path_kill_slashes(dest);
3712                         if (set_get(remove_symlinks_to, dest)) {
3713
3714                                 if (!arg_quiet)
3715                                         log_info("rm '%s'", p);
3716
3717                                 if (unlink(p) < 0) {
3718                                         log_error("Cannot unlink symlink %s: %m", p);
3719
3720                                         if (r == 0)
3721                                                 r = -errno;
3722                                 } else {
3723                                         rmdir_parents(p, config_path);
3724                                         path_kill_slashes(p);
3725
3726                                         if (!set_get(remove_symlinks_to, p)) {
3727
3728                                                 if ((r = mark_symlink_for_removal(p)) < 0) {
3729                                                         if (r == 0)
3730                                                                 r = q;
3731                                                 } else
3732                                                         *deleted = true;
3733                                         }
3734                                 }
3735                         }
3736
3737                         free(p);
3738                         free(dest);
3739                 }
3740         }
3741
3742         closedir(d);
3743
3744         return r;
3745 }
3746
3747 static int remove_marked_symlinks(const char *config_path) {
3748         int fd, r = 0;
3749         bool deleted;
3750
3751         assert(config_path);
3752
3753         if (set_size(remove_symlinks_to) <= 0)
3754                 return 0;
3755
3756         if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3757                 return -errno;
3758
3759         do {
3760                 int q, cfd;
3761                 deleted = false;
3762
3763                 if ((cfd = dup(fd)) < 0) {
3764                         r = -errno;
3765                         break;
3766                 }
3767
3768                 /* This takes possession of cfd and closes it */
3769                 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3770                         if (r == 0)
3771                                 r = q;
3772                 }
3773         } while (deleted);
3774
3775         close_nointr_nofail(fd);
3776
3777         return r;
3778 }
3779
3780 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3781         int r;
3782
3783         assert(old_path);
3784         assert(new_path);
3785         assert(verb);
3786
3787         if (streq(verb, "enable")) {
3788                 char *dest;
3789
3790                 mkdir_parents(new_path, 0755);
3791
3792                 if (symlink(old_path, new_path) >= 0) {
3793
3794                         if (!arg_quiet)
3795                                 log_info("ln -s '%s' '%s'", old_path, new_path);
3796
3797                         return 0;
3798                 }
3799
3800                 if (errno != EEXIST) {
3801                         log_error("Cannot link %s to %s: %m", old_path, new_path);
3802                         return -errno;
3803                 }
3804
3805                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3806
3807                         if (errno == EINVAL) {
3808                                 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3809                                 return -EEXIST;
3810                         }
3811
3812                         log_error("readlink() failed: %s", strerror(-r));
3813                         return r;
3814                 }
3815
3816                 if (streq(dest, old_path)) {
3817                         free(dest);
3818                         return 0;
3819                 }
3820
3821                 if (!arg_force) {
3822                         log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3823                         free(dest);
3824                         return -EEXIST;
3825                 }
3826
3827                 free(dest);
3828                 unlink(new_path);
3829
3830                 if (!arg_quiet)
3831                         log_info("ln -s '%s' '%s'", old_path, new_path);
3832
3833                 if (symlink(old_path, new_path) >= 0)
3834                         return 0;
3835
3836                 log_error("Cannot link %s to %s: %m", old_path, new_path);
3837                 return -errno;
3838
3839         } else if (streq(verb, "disable")) {
3840                 char *dest;
3841
3842                 if ((r = mark_symlink_for_removal(old_path)) < 0)
3843                         return r;
3844
3845                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3846                         if (errno == ENOENT)
3847                                 return 0;
3848
3849                         if (errno == EINVAL) {
3850                                 log_warning("File %s not a symlink, ignoring.", old_path);
3851                                 return 0;
3852                         }
3853
3854                         log_error("readlink() failed: %s", strerror(-r));
3855                         return r;
3856                 }
3857
3858                 if (!streq(dest, old_path)) {
3859                         log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3860                         free(dest);
3861                         return 0;
3862                 }
3863
3864                 free(dest);
3865
3866                 if ((r = mark_symlink_for_removal(new_path)) < 0)
3867                         return r;
3868
3869                 if (!arg_quiet)
3870                         log_info("rm '%s'", new_path);
3871
3872                 if (unlink(new_path) >= 0)
3873                         return 0;
3874
3875                 log_error("Cannot unlink %s: %m", new_path);
3876                 return -errno;
3877
3878         } else if (streq(verb, "is-enabled")) {
3879                 char *dest;
3880
3881                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3882
3883                         if (errno == ENOENT || errno == EINVAL)
3884                                 return 0;
3885
3886                         log_error("readlink() failed: %s", strerror(-r));
3887                         return r;
3888                 }
3889
3890                 if (streq(dest, old_path)) {
3891                         free(dest);
3892                         return 1;
3893                 }
3894
3895                 return 0;
3896         }
3897
3898         assert_not_reached("Unknown action.");
3899 }
3900
3901 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3902         char **s;
3903         char *alias_path = NULL;
3904         int r;
3905
3906         assert(verb);
3907         assert(i);
3908         assert(config_path);
3909
3910         STRV_FOREACH(s, i->aliases) {
3911
3912                 free(alias_path);
3913                 if (!(alias_path = path_make_absolute(*s, config_path))) {
3914                         log_error("Out of memory");
3915                         r = -ENOMEM;
3916                         goto finish;
3917                 }
3918
3919                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3920                         goto finish;
3921
3922                 if (streq(verb, "disable"))
3923                         rmdir_parents(alias_path, config_path);
3924         }
3925         r = 0;
3926
3927 finish:
3928         free(alias_path);
3929
3930         return r;
3931 }
3932
3933 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3934         char **s;
3935         char *alias_path = NULL;
3936         int r;
3937
3938         assert(verb);
3939         assert(i);
3940         assert(config_path);
3941
3942         STRV_FOREACH(s, i->wanted_by) {
3943                 if (!unit_name_is_valid_no_type(*s, true)) {
3944                         log_error("Invalid name %s.", *s);
3945                         r = -EINVAL;
3946                         goto finish;
3947                 }
3948
3949                 free(alias_path);
3950                 alias_path = NULL;
3951
3952                 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3953                         log_error("Out of memory");
3954                         r = -ENOMEM;
3955                         goto finish;
3956                 }
3957
3958                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3959                         goto finish;
3960
3961                 if (streq(verb, "disable"))
3962                         rmdir_parents(alias_path, config_path);
3963         }
3964
3965         r = 0;
3966
3967 finish:
3968         free(alias_path);
3969
3970         return r;
3971 }
3972
3973 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3974
3975         const ConfigItem items[] = {
3976                 { "Alias",    config_parse_strv, &i->aliases,   "Install" },
3977                 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3978                 { "Also",     config_parse_also, NULL,          "Install" },
3979
3980                 { NULL, NULL, NULL, NULL }
3981         };
3982
3983         char **p;
3984         char *filename = NULL;
3985         FILE *f = NULL;
3986         int r;
3987
3988         assert(paths);
3989         assert(i);
3990
3991         STRV_FOREACH(p, paths->unit_path) {
3992                 int fd;
3993
3994                 if (!(filename = path_make_absolute(i->name, *p))) {
3995                         log_error("Out of memory");
3996                         return -ENOMEM;
3997                 }
3998
3999                 /* Ensure that we don't follow symlinks */
4000                 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4001                         if ((f = fdopen(fd, "re")))
4002                                 break;
4003
4004                 if (errno == ELOOP) {
4005                         log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4006                         free(filename);
4007                         return -errno;
4008                 }
4009
4010                 if (errno != ENOENT) {
4011                         log_error("Failed to open %s: %m", filename);
4012                         free(filename);
4013                         return -errno;
4014                 }
4015
4016                 free(filename);
4017                 filename = NULL;
4018         }
4019
4020         if (!f) {
4021 #if defined(TARGET_FEDORA) && defined (HAVE_SYSV_COMPAT)
4022
4023                 if (endswith(i->name, ".service")) {
4024                         char *sysv;
4025                         bool exists;
4026
4027                         if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4028                                 log_error("Out of memory");
4029                                 return -ENOMEM;
4030                         }
4031
4032                         sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4033                         exists = access(sysv, F_OK) >= 0;
4034
4035                         if (exists) {
4036                                 pid_t pid;
4037                                 siginfo_t status;
4038
4039                                 const char *argv[] = {
4040                                         "/sbin/chkconfig",
4041                                         NULL,
4042                                         NULL,
4043                                         NULL
4044                                 };
4045
4046                                 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4047
4048                                 argv[1] = file_name_from_path(sysv);
4049                                 argv[2] =
4050                                         streq(verb, "enable") ? "on" :
4051                                         streq(verb, "disable") ? "off" : NULL;
4052
4053                                 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4054
4055                                 if ((pid = fork()) < 0) {
4056                                         log_error("Failed to fork: %m");
4057                                         free(sysv);
4058                                         return -errno;
4059                                 } else if (pid == 0) {
4060                                         execv(argv[0], (char**) argv);
4061                                         _exit(EXIT_FAILURE);
4062                                 }
4063
4064                                 free(sysv);
4065
4066                                 if ((r = wait_for_terminate(pid, &status)) < 0)
4067                                         return r;
4068
4069                                 if (status.si_code == CLD_EXITED) {
4070                                         if (status.si_status == 0 && (streq(verb, "enable") || streq(verb, "disable")))
4071                                                 n_symlinks ++;
4072
4073                                         return status.si_status == 0 ? 0 : -EINVAL;
4074                                 } else
4075                                         return -EPROTO;
4076                         }
4077
4078                         free(sysv);
4079                 }
4080
4081 #endif
4082
4083                 log_error("Couldn't find %s.", i->name);
4084                 return -ENOENT;
4085         }
4086
4087         i->path = filename;
4088
4089         if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4090                 fclose(f);
4091                 return r;
4092         }
4093
4094         n_symlinks += strv_length(i->aliases);
4095         n_symlinks += strv_length(i->wanted_by);
4096
4097         fclose(f);
4098
4099         if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4100                 return r;
4101
4102         if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4103                 return r;
4104
4105         if ((r = mark_symlink_for_removal(filename)) < 0)
4106                 return r;
4107
4108         if ((r = remove_marked_symlinks(config_path)) < 0)
4109                 return r;
4110
4111         return 0;
4112 }
4113
4114 static char *get_config_path(void) {
4115
4116         if (arg_user && arg_global)
4117                 return strdup(USER_CONFIG_UNIT_PATH);
4118
4119         if (arg_user) {
4120                 char *p;
4121
4122                 if (user_config_home(&p) < 0)
4123                         return NULL;
4124
4125                 return p;
4126         }
4127
4128         return strdup(SYSTEM_CONFIG_UNIT_PATH);
4129 }
4130
4131 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4132         DBusError error;
4133         int r;
4134         LookupPaths paths;
4135         char *config_path = NULL;
4136         unsigned j;
4137         InstallInfo *i;
4138         const char *verb = args[0];
4139
4140         dbus_error_init(&error);
4141
4142         zero(paths);
4143         if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
4144                 log_error("Failed to determine lookup paths: %s", strerror(-r));
4145                 goto finish;
4146         }
4147
4148         if (!(config_path = get_config_path())) {
4149                 log_error("Failed to determine config path");
4150                 r = -ENOMEM;
4151                 goto finish;
4152         }
4153
4154         will_install = hashmap_new(string_hash_func, string_compare_func);
4155         have_installed = hashmap_new(string_hash_func, string_compare_func);
4156
4157         if (!will_install || !have_installed) {
4158                 log_error("Failed to allocate unit sets.");
4159                 r = -ENOMEM;
4160                 goto finish;
4161         }
4162
4163         if (!arg_defaults && streq(verb, "disable"))
4164                 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4165                         log_error("Failed to allocate symlink sets.");
4166                         r = -ENOMEM;
4167                         goto finish;
4168                 }
4169
4170         for (j = 1; j < n; j++)
4171                 if ((r = install_info_add(args[j])) < 0) {
4172                         log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
4173                         goto finish;
4174                 }
4175
4176         while ((i = hashmap_first(will_install))) {
4177                 int q;
4178
4179                 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4180
4181                 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4182
4183                         if (q < 0) {
4184                                 if (r == 0)
4185                                         r = q;
4186                                 goto finish;
4187                         }
4188
4189                         /* In test mode and found something */
4190                         r = 1;
4191                         break;
4192                 }
4193         }
4194
4195         if (streq(verb, "is-enabled"))
4196                 r = r > 0 ? 0 : -ENOENT;
4197         else {
4198                 if (n_symlinks <= 0)
4199                         log_warning("Unit files contain no applicable installation information. Ignoring.");
4200
4201                 if (bus &&
4202                     /* Don't try to reload anything if the user asked us to not do this */
4203                     !arg_no_reload &&
4204                     /* Don't try to reload anything when updating a unit globally */
4205                     !arg_global &&
4206                     /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
4207                     (arg_user || sd_booted() > 0) &&
4208                     /* Don't try to reload anything if we are running in a chroot environment */
4209                     (arg_user || running_in_chroot() <= 0) ) {
4210                         int q;
4211
4212                         if ((q = daemon_reload(bus, args, n)) < 0)
4213                                 r = q;
4214                 }
4215         }
4216
4217 finish:
4218         install_info_hashmap_free(will_install);
4219         install_info_hashmap_free(have_installed);
4220
4221         set_free_free(remove_symlinks_to);
4222
4223         lookup_paths_free(&paths);
4224
4225         free(config_path);
4226
4227         return r;
4228 }
4229
4230 static int systemctl_help(void) {
4231
4232         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
4233                "Send control commands to or query the systemd manager.\n\n"
4234                "  -h --help           Show this help\n"
4235                "     --version        Show package version\n"
4236                "  -t --type=TYPE      List only units of a particular type\n"
4237                "  -p --property=NAME  Show only properties by this name\n"
4238                "  -a --all            Show all units/properties, including dead/empty ones\n"
4239                "     --failed         Show only failed units\n"
4240                "     --full           Don't ellipsize unit names on output\n"
4241                "     --fail           When queueing a new job, fail if conflicting jobs are\n"
4242                "                      pending\n"
4243                "     --ignore-dependencies\n"
4244                "                      When queueing a new job, ignore all its dependencies\n"
4245                "  -q --quiet          Suppress output\n"
4246                "     --no-block       Do not wait until operation finished\n"
4247                "     --no-pager       Do not pipe output into a pager.\n"
4248                "     --system         Connect to system manager\n"
4249                "     --user           Connect to user service manager\n"
4250                "     --order          When generating graph for dot, show only order\n"
4251                "     --require        When generating graph for dot, show only requirement\n"
4252                "     --no-wall        Don't send wall message before halt/power-off/reboot\n"
4253                "     --global         Enable/disable unit files globally\n"
4254                "     --no-reload      When enabling/disabling unit files, don't reload daemon\n"
4255                "                      configuration\n"
4256                "     --no-ask-password\n"
4257                "                      Do not ask for system passwords\n"
4258                "     --kill-mode=MODE How to send signal\n"
4259                "     --kill-who=WHO   Who to send signal to\n"
4260                "  -s --signal=SIGNAL  Which signal to send\n"
4261                "  -f --force          When enabling unit files, override existing symlinks\n"
4262                "                      When shutting down, execute action immediately\n"
4263                "     --defaults       When disabling unit files, remove default symlinks only\n\n"
4264                "Commands:\n"
4265                "  list-units                      List units\n"
4266                "  start [NAME...]                 Start (activate) one or more units\n"
4267                "  stop [NAME...]                  Stop (deactivate) one or more units\n"
4268                "  reload [NAME...]                Reload one or more units\n"
4269                "  restart [NAME...]               Start or restart one or more units\n"
4270                "  try-restart [NAME...]           Restart one or more units if active\n"
4271                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
4272                "                                  otherwise start or restart\n"
4273                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4274                "                                  otherwise restart if active\n"
4275                "  isolate [NAME]                  Start one unit and stop all others\n"
4276                "  kill [NAME...]                  Send signal to processes of a unit\n"
4277                "  is-active [NAME...]             Check whether units are active\n"
4278                "  status [NAME...|PID...]         Show runtime status of one or more units\n"
4279                "  show [NAME...|JOB...]           Show properties of one or more\n"
4280                "                                  units/jobs or the manager\n"
4281                "  reset-failed [NAME...]          Reset failed state for all, one, or more\n"
4282                "                                  units\n"
4283                "  enable [NAME...]                Enable one or more unit files\n"
4284                "  disable [NAME...]               Disable one or more unit files\n"
4285                "  is-enabled [NAME...]            Check whether unit files are enabled\n"
4286                "  load [NAME...]                  Load one or more units\n"
4287                "  list-jobs                       List jobs\n"
4288                "  cancel [JOB...]                 Cancel all, one, or more jobs\n"
4289                "  monitor                         Monitor unit/job changes\n"
4290                "  dump                            Dump server status\n"
4291                "  dot                             Dump dependency graph for dot(1)\n"
4292                "  snapshot [NAME]                 Create a snapshot\n"
4293                "  delete [NAME...]                Remove one or more snapshots\n"
4294                "  daemon-reload                   Reload systemd manager configuration\n"
4295                "  daemon-reexec                   Reexecute systemd manager\n"
4296                "  show-environment                Dump environment\n"
4297                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
4298                "  unset-environment [NAME...]     Unset one or more environment variables\n"
4299                "  default                         Enter system default mode\n"
4300                "  rescue                          Enter system rescue mode\n"
4301                "  emergency                       Enter system emergency mode\n"
4302                "  halt                            Shut down and halt the system\n"
4303                "  poweroff                        Shut down and power-off the system\n"
4304                "  reboot                          Shut down and reboot the system\n"
4305                "  kexec                           Shut down and reboot the system with kexec\n"
4306                "  exit                            Ask for user instance termination\n",
4307                program_invocation_short_name);
4308
4309         return 0;
4310 }
4311
4312 static int halt_help(void) {
4313
4314         printf("%s [OPTIONS...]\n\n"
4315                "%s the system.\n\n"
4316                "     --help      Show this help\n"
4317                "     --halt      Halt the machine\n"
4318                "  -p --poweroff  Switch off the machine\n"
4319                "     --reboot    Reboot the machine\n"
4320                "  -f --force     Force immediate halt/power-off/reboot\n"
4321                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
4322                "  -d --no-wtmp   Don't write wtmp record\n"
4323                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
4324                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
4325                program_invocation_short_name,
4326                arg_action == ACTION_REBOOT   ? "Reboot" :
4327                arg_action == ACTION_POWEROFF ? "Power off" :
4328                                                "Halt");
4329
4330         return 0;
4331 }
4332
4333 static int shutdown_help(void) {
4334
4335         printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4336                "Shut down the system.\n\n"
4337                "     --help      Show this help\n"
4338                "  -H --halt      Halt the machine\n"
4339                "  -P --poweroff  Power-off the machine\n"
4340                "  -r --reboot    Reboot the machine\n"
4341                "  -h             Equivalent to --poweroff, overriden by --halt\n"
4342                "  -k             Don't halt/power-off/reboot, just send warnings\n"
4343                "     --no-wall   Don't send wall message before halt/power-off/reboot\n"
4344                "  -c             Cancel a pending shutdown\n",
4345                program_invocation_short_name);
4346
4347         return 0;
4348 }
4349
4350 static int telinit_help(void) {
4351
4352         printf("%s [OPTIONS...] {COMMAND}\n\n"
4353                "Send control commands to the init daemon.\n\n"
4354                "     --help      Show this help\n"
4355                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
4356                "Commands:\n"
4357                "  0              Power-off the machine\n"
4358                "  6              Reboot the machine\n"
4359                "  2, 3, 4, 5     Start runlevelX.target unit\n"
4360                "  1, s, S        Enter rescue mode\n"
4361                "  q, Q           Reload init daemon configuration\n"
4362                "  u, U           Reexecute init daemon\n",
4363                program_invocation_short_name);
4364
4365         return 0;
4366 }
4367
4368 static int runlevel_help(void) {
4369
4370         printf("%s [OPTIONS...]\n\n"
4371                "Prints the previous and current runlevel of the init system.\n\n"
4372                "     --help      Show this help\n",
4373                program_invocation_short_name);
4374
4375         return 0;
4376 }
4377
4378 static int systemctl_parse_argv(int argc, char *argv[]) {
4379
4380         enum {
4381                 ARG_FAIL = 0x100,
4382                 ARG_IGNORE_DEPENDENCIES,
4383                 ARG_VERSION,
4384                 ARG_USER,
4385                 ARG_SYSTEM,
4386                 ARG_GLOBAL,
4387                 ARG_NO_BLOCK,
4388                 ARG_NO_PAGER,
4389                 ARG_NO_WALL,
4390                 ARG_ORDER,
4391                 ARG_REQUIRE,
4392                 ARG_FULL,
4393                 ARG_NO_RELOAD,
4394                 ARG_DEFAULTS,
4395                 ARG_KILL_MODE,
4396                 ARG_KILL_WHO,
4397                 ARG_NO_ASK_PASSWORD,
4398                 ARG_FAILED
4399         };
4400
4401         static const struct option options[] = {
4402                 { "help",      no_argument,       NULL, 'h'           },
4403                 { "version",   no_argument,       NULL, ARG_VERSION   },
4404                 { "type",      required_argument, NULL, 't'           },
4405                 { "property",  required_argument, NULL, 'p'           },
4406                 { "all",       no_argument,       NULL, 'a'           },
4407                 { "failed",    no_argument,       NULL, ARG_FAILED    },
4408                 { "full",      no_argument,       NULL, ARG_FULL      },
4409                 { "fail",      no_argument,       NULL, ARG_FAIL      },
4410                 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4411                 { "user",      no_argument,       NULL, ARG_USER      },
4412                 { "system",    no_argument,       NULL, ARG_SYSTEM    },
4413                 { "global",    no_argument,       NULL, ARG_GLOBAL    },
4414                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
4415                 { "no-pager",  no_argument,       NULL, ARG_NO_PAGER  },
4416                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL   },
4417                 { "quiet",     no_argument,       NULL, 'q'           },
4418                 { "order",     no_argument,       NULL, ARG_ORDER     },
4419                 { "require",   no_argument,       NULL, ARG_REQUIRE   },
4420                 { "force",     no_argument,       NULL, 'f'           },
4421                 { "no-reload", no_argument,       NULL, ARG_NO_RELOAD },
4422                 { "defaults",  no_argument,       NULL, ARG_DEFAULTS  },
4423                 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4424                 { "kill-who",  required_argument, NULL, ARG_KILL_WHO  },
4425                 { "signal",    required_argument, NULL, 's'           },
4426                 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4427                 { NULL,        0,                 NULL, 0             }
4428         };
4429
4430         int c;
4431
4432         assert(argc >= 0);
4433         assert(argv);
4434
4435         /* Only when running as systemctl we ask for passwords */
4436         arg_ask_password = true;
4437
4438         while ((c = getopt_long(argc, argv, "ht:p:aqfs:", options, NULL)) >= 0) {
4439
4440                 switch (c) {
4441
4442                 case 'h':
4443                         systemctl_help();
4444                         return 0;
4445
4446                 case ARG_VERSION:
4447                         puts(PACKAGE_STRING);
4448                         puts(DISTRIBUTION);
4449                         puts(SYSTEMD_FEATURES);
4450                         return 0;
4451
4452                 case 't':
4453                         arg_type = optarg;
4454                         break;
4455
4456                 case 'p': {
4457                         char **l;
4458
4459                         if (!(l = strv_append(arg_property, optarg)))
4460                                 return -ENOMEM;
4461
4462                         strv_free(arg_property);
4463                         arg_property = l;
4464
4465                         /* If the user asked for a particular
4466                          * property, show it to him, even if it is
4467                          * empty. */
4468                         arg_all = true;
4469                         break;
4470                 }
4471
4472                 case 'a':
4473                         arg_all = true;
4474                         break;
4475
4476                 case ARG_FAIL:
4477                         arg_job_mode = "fail";
4478                         break;
4479
4480                 case ARG_IGNORE_DEPENDENCIES:
4481                         arg_job_mode = "ignore-dependencies";
4482                         break;
4483
4484                 case ARG_USER:
4485                         arg_user = true;
4486                         break;
4487
4488                 case ARG_SYSTEM:
4489                         arg_user = false;
4490                         break;
4491
4492                 case ARG_NO_BLOCK:
4493                         arg_no_block = true;
4494                         break;
4495
4496                 case ARG_NO_PAGER:
4497                         arg_no_pager = true;
4498                         break;
4499
4500                 case ARG_NO_WALL:
4501                         arg_no_wall = true;
4502                         break;
4503
4504                 case ARG_ORDER:
4505                         arg_dot = DOT_ORDER;
4506                         break;
4507
4508                 case ARG_REQUIRE:
4509                         arg_dot = DOT_REQUIRE;
4510                         break;
4511
4512                 case ARG_FULL:
4513                         arg_full = true;
4514                         break;
4515
4516                 case ARG_FAILED:
4517                         arg_failed = true;
4518                         break;
4519
4520                 case 'q':
4521                         arg_quiet = true;
4522                         break;
4523
4524                 case 'f':
4525                         arg_force = true;
4526                         break;
4527
4528                 case ARG_NO_RELOAD:
4529                         arg_no_reload = true;
4530                         break;
4531
4532                 case ARG_GLOBAL:
4533                         arg_global = true;
4534                         arg_user = true;
4535                         break;
4536
4537                 case ARG_DEFAULTS:
4538                         arg_defaults = true;
4539                         break;
4540
4541                 case ARG_KILL_WHO:
4542                         arg_kill_who = optarg;
4543                         break;
4544
4545                 case ARG_KILL_MODE:
4546                         arg_kill_mode = optarg;
4547                         break;
4548
4549                 case 's':
4550                         if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4551                                 log_error("Failed to parse signal string %s.", optarg);
4552                                 return -EINVAL;
4553                         }
4554                         break;
4555
4556                 case ARG_NO_ASK_PASSWORD:
4557                         arg_ask_password = false;
4558                         break;
4559
4560                 case '?':
4561                         return -EINVAL;
4562
4563                 default:
4564                         log_error("Unknown option code %c", c);
4565                         return -EINVAL;
4566                 }
4567         }
4568
4569         return 1;
4570 }
4571
4572 static int halt_parse_argv(int argc, char *argv[]) {
4573
4574         enum {
4575                 ARG_HELP = 0x100,
4576                 ARG_HALT,
4577                 ARG_REBOOT,
4578                 ARG_NO_WALL
4579         };
4580
4581         static const struct option options[] = {
4582                 { "help",      no_argument,       NULL, ARG_HELP    },
4583                 { "halt",      no_argument,       NULL, ARG_HALT    },
4584                 { "poweroff",  no_argument,       NULL, 'p'         },
4585                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
4586                 { "force",     no_argument,       NULL, 'f'         },
4587                 { "wtmp-only", no_argument,       NULL, 'w'         },
4588                 { "no-wtmp",   no_argument,       NULL, 'd'         },
4589                 { "no-sync",   no_argument,       NULL, 'n'         },
4590                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4591                 { NULL,        0,                 NULL, 0           }
4592         };
4593
4594         int c, runlevel;
4595
4596         assert(argc >= 0);
4597         assert(argv);
4598
4599         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4600                 if (runlevel == '0' || runlevel == '6')
4601                         arg_immediate = true;
4602
4603         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4604                 switch (c) {
4605
4606                 case ARG_HELP:
4607                         halt_help();
4608                         return 0;
4609
4610                 case ARG_HALT:
4611                         arg_action = ACTION_HALT;
4612                         break;
4613
4614                 case 'p':
4615                         if (arg_action != ACTION_REBOOT)
4616                                 arg_action = ACTION_POWEROFF;
4617                         break;
4618
4619                 case ARG_REBOOT:
4620                         arg_action = ACTION_REBOOT;
4621                         break;
4622
4623                 case 'f':
4624                         arg_immediate = true;
4625                         break;
4626
4627                 case 'w':
4628                         arg_dry = true;
4629                         break;
4630
4631                 case 'd':
4632                         arg_no_wtmp = true;
4633                         break;
4634
4635                 case 'n':
4636                         arg_no_sync = true;
4637                         break;
4638
4639                 case ARG_NO_WALL:
4640                         arg_no_wall = true;
4641                         break;
4642
4643                 case 'i':
4644                 case 'h':
4645                         /* Compatibility nops */
4646                         break;
4647
4648                 case '?':
4649                         return -EINVAL;
4650
4651                 default:
4652                         log_error("Unknown option code %c", c);
4653                         return -EINVAL;
4654                 }
4655         }
4656
4657         if (optind < argc) {
4658                 log_error("Too many arguments.");
4659                 return -EINVAL;
4660         }
4661
4662         return 1;
4663 }
4664
4665 static int parse_time_spec(const char *t, usec_t *_u) {
4666         assert(t);
4667         assert(_u);
4668
4669         if (streq(t, "now"))
4670                 *_u = 0;
4671         else if (t[0] == '+') {
4672                 uint64_t u;
4673
4674                 if (safe_atou64(t + 1, &u) < 0)
4675                         return -EINVAL;
4676
4677                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4678         } else {
4679                 char *e = NULL;
4680                 long hour, minute;
4681                 struct tm tm;
4682                 time_t s;
4683                 usec_t n;
4684
4685                 errno = 0;
4686                 hour = strtol(t, &e, 10);
4687                 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4688                         return -EINVAL;
4689
4690                 minute = strtol(e+1, &e, 10);
4691                 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4692                         return -EINVAL;
4693
4694                 n = now(CLOCK_REALTIME);
4695                 s = (time_t) (n / USEC_PER_SEC);
4696
4697                 zero(tm);
4698                 assert_se(localtime_r(&s, &tm));
4699
4700                 tm.tm_hour = (int) hour;
4701                 tm.tm_min = (int) minute;
4702                 tm.tm_sec = 0;
4703
4704                 assert_se(s = mktime(&tm));
4705
4706                 *_u = (usec_t) s * USEC_PER_SEC;
4707
4708                 while (*_u <= n)
4709                         *_u += USEC_PER_DAY;
4710         }
4711
4712         return 0;
4713 }
4714
4715 static bool kexec_loaded(void) {
4716        bool loaded = false;
4717        char *s;
4718
4719        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4720                if (s[0] == '1')
4721                        loaded = true;
4722                free(s);
4723        }
4724        return loaded;
4725 }
4726
4727 static int shutdown_parse_argv(int argc, char *argv[]) {
4728
4729         enum {
4730                 ARG_HELP = 0x100,
4731                 ARG_NO_WALL
4732         };
4733
4734         static const struct option options[] = {
4735                 { "help",      no_argument,       NULL, ARG_HELP    },
4736                 { "halt",      no_argument,       NULL, 'H'         },
4737                 { "poweroff",  no_argument,       NULL, 'P'         },
4738                 { "reboot",    no_argument,       NULL, 'r'         },
4739                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4740                 { NULL,        0,                 NULL, 0           }
4741         };
4742
4743         int c, r;
4744
4745         assert(argc >= 0);
4746         assert(argv);
4747
4748         while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4749                 switch (c) {
4750
4751                 case ARG_HELP:
4752                         shutdown_help();
4753                         return 0;
4754
4755                 case 'H':
4756                         arg_action = ACTION_HALT;
4757                         break;
4758
4759                 case 'P':
4760                         arg_action = ACTION_POWEROFF;
4761                         break;
4762
4763                 case 'r':
4764                         if (kexec_loaded())
4765                                 arg_action = ACTION_KEXEC;
4766                         else
4767                                 arg_action = ACTION_REBOOT;
4768                         break;
4769
4770                 case 'h':
4771                         if (arg_action != ACTION_HALT)
4772                                 arg_action = ACTION_POWEROFF;
4773                         break;
4774
4775                 case 'k':
4776                         arg_dry = true;
4777                         break;
4778
4779                 case ARG_NO_WALL:
4780                         arg_no_wall = true;
4781                         break;
4782
4783                 case 't':
4784                 case 'a':
4785                         /* Compatibility nops */
4786                         break;
4787
4788                 case 'c':
4789                         arg_action = ACTION_CANCEL_SHUTDOWN;
4790                         break;
4791
4792                 case '?':
4793                         return -EINVAL;
4794
4795                 default:
4796                         log_error("Unknown option code %c", c);
4797                         return -EINVAL;
4798                 }
4799         }
4800
4801         if (argc > optind) {
4802                 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4803                         log_error("Failed to parse time specification: %s", argv[optind]);
4804                         return r;
4805                 }
4806         } else
4807                 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4808
4809         /* We skip the time argument */
4810         if (argc > optind + 1)
4811                 arg_wall = argv + optind + 1;
4812
4813         optind = argc;
4814
4815         return 1;
4816 }
4817
4818 static int telinit_parse_argv(int argc, char *argv[]) {
4819
4820         enum {
4821                 ARG_HELP = 0x100,
4822                 ARG_NO_WALL
4823         };
4824
4825         static const struct option options[] = {
4826                 { "help",      no_argument,       NULL, ARG_HELP    },
4827                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4828                 { NULL,        0,                 NULL, 0           }
4829         };
4830
4831         static const struct {
4832                 char from;
4833                 enum action to;
4834         } table[] = {
4835                 { '0', ACTION_POWEROFF },
4836                 { '6', ACTION_REBOOT },
4837                 { '1', ACTION_RESCUE },
4838                 { '2', ACTION_RUNLEVEL2 },
4839                 { '3', ACTION_RUNLEVEL3 },
4840                 { '4', ACTION_RUNLEVEL4 },
4841                 { '5', ACTION_RUNLEVEL5 },
4842                 { 's', ACTION_RESCUE },
4843                 { 'S', ACTION_RESCUE },
4844                 { 'q', ACTION_RELOAD },
4845                 { 'Q', ACTION_RELOAD },
4846                 { 'u', ACTION_REEXEC },
4847                 { 'U', ACTION_REEXEC }
4848         };
4849
4850         unsigned i;
4851         int c;
4852
4853         assert(argc >= 0);
4854         assert(argv);
4855
4856         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4857                 switch (c) {
4858
4859                 case ARG_HELP:
4860                         telinit_help();
4861                         return 0;
4862
4863                 case ARG_NO_WALL:
4864                         arg_no_wall = true;
4865                         break;
4866
4867                 case '?':
4868                         return -EINVAL;
4869
4870                 default:
4871                         log_error("Unknown option code %c", c);
4872                         return -EINVAL;
4873                 }
4874         }
4875
4876         if (optind >= argc) {
4877                 telinit_help();
4878                 return -EINVAL;
4879         }
4880
4881         if (optind + 1 < argc) {
4882                 log_error("Too many arguments.");
4883                 return -EINVAL;
4884         }
4885
4886         if (strlen(argv[optind]) != 1) {
4887                 log_error("Expected single character argument.");
4888                 return -EINVAL;
4889         }
4890
4891         for (i = 0; i < ELEMENTSOF(table); i++)
4892                 if (table[i].from == argv[optind][0])
4893                         break;
4894
4895         if (i >= ELEMENTSOF(table)) {
4896                 log_error("Unknown command %s.", argv[optind]);
4897                 return -EINVAL;
4898         }
4899
4900         arg_action = table[i].to;
4901
4902         optind ++;
4903
4904         return 1;
4905 }
4906
4907 static int runlevel_parse_argv(int argc, char *argv[]) {
4908
4909         enum {
4910                 ARG_HELP = 0x100,
4911         };
4912
4913         static const struct option options[] = {
4914                 { "help",      no_argument,       NULL, ARG_HELP    },
4915                 { NULL,        0,                 NULL, 0           }
4916         };
4917
4918         int c;
4919
4920         assert(argc >= 0);
4921         assert(argv);
4922
4923         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4924                 switch (c) {
4925
4926                 case ARG_HELP:
4927                         runlevel_help();
4928                         return 0;
4929
4930                 case '?':
4931                         return -EINVAL;
4932
4933                 default:
4934                         log_error("Unknown option code %c", c);
4935                         return -EINVAL;
4936                 }
4937         }
4938
4939         if (optind < argc) {
4940                 log_error("Too many arguments.");
4941                 return -EINVAL;
4942         }
4943
4944         return 1;
4945 }
4946
4947 static int parse_argv(int argc, char *argv[]) {
4948         assert(argc >= 0);
4949         assert(argv);
4950
4951         if (program_invocation_short_name) {
4952
4953                 if (strstr(program_invocation_short_name, "halt")) {
4954                         arg_action = ACTION_HALT;
4955                         return halt_parse_argv(argc, argv);
4956                 } else if (strstr(program_invocation_short_name, "poweroff")) {
4957                         arg_action = ACTION_POWEROFF;
4958                         return halt_parse_argv(argc, argv);
4959                 } else if (strstr(program_invocation_short_name, "reboot")) {
4960                         if (kexec_loaded())
4961                                 arg_action = ACTION_KEXEC;
4962                         else
4963                                 arg_action = ACTION_REBOOT;
4964                         return halt_parse_argv(argc, argv);
4965                 } else if (strstr(program_invocation_short_name, "shutdown")) {
4966                         arg_action = ACTION_POWEROFF;
4967                         return shutdown_parse_argv(argc, argv);
4968                 } else if (strstr(program_invocation_short_name, "init")) {
4969
4970                         if (sd_booted() > 0) {
4971                                 arg_action = ACTION_INVALID;
4972                                 return telinit_parse_argv(argc, argv);
4973                         } else {
4974                                 /* Hmm, so some other init system is
4975                                  * running, we need to forward this
4976                                  * request to it. For now we simply
4977                                  * guess that it is Upstart. */
4978
4979                                 execv("/lib/upstart/telinit", argv);
4980
4981                                 log_error("Couldn't find an alternative telinit implementation to spawn.");
4982                                 return -EIO;
4983                         }
4984
4985                 } else if (strstr(program_invocation_short_name, "runlevel")) {
4986                         arg_action = ACTION_RUNLEVEL;
4987                         return runlevel_parse_argv(argc, argv);
4988                 }
4989         }
4990
4991         arg_action = ACTION_SYSTEMCTL;
4992         return systemctl_parse_argv(argc, argv);
4993 }
4994
4995 static int action_to_runlevel(void) {
4996
4997         static const char table[_ACTION_MAX] = {
4998                 [ACTION_HALT] =      '0',
4999                 [ACTION_POWEROFF] =  '0',
5000                 [ACTION_REBOOT] =    '6',
5001                 [ACTION_RUNLEVEL2] = '2',
5002                 [ACTION_RUNLEVEL3] = '3',
5003                 [ACTION_RUNLEVEL4] = '4',
5004                 [ACTION_RUNLEVEL5] = '5',
5005                 [ACTION_RESCUE] =    '1'
5006         };
5007
5008         assert(arg_action < _ACTION_MAX);
5009
5010         return table[arg_action];
5011 }
5012
5013 static int talk_upstart(void) {
5014         DBusMessage *m = NULL, *reply = NULL;
5015         DBusError error;
5016         int previous, rl, r;
5017         char
5018                 env1_buf[] = "RUNLEVEL=X",
5019                 env2_buf[] = "PREVLEVEL=X";
5020         char *env1 = env1_buf, *env2 = env2_buf;
5021         const char *emit = "runlevel";
5022         dbus_bool_t b_false = FALSE;
5023         DBusMessageIter iter, sub;
5024         DBusConnection *bus;
5025
5026         dbus_error_init(&error);
5027
5028         if (!(rl = action_to_runlevel()))
5029                 return 0;
5030
5031         if (utmp_get_runlevel(&previous, NULL) < 0)
5032                 previous = 'N';
5033
5034         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
5035                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5036                         r = 0;
5037                         goto finish;
5038                 }
5039
5040                 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
5041                 r = -EIO;
5042                 goto finish;
5043         }
5044
5045         if ((r = bus_check_peercred(bus)) < 0) {
5046                 log_error("Failed to verify owner of bus.");
5047                 goto finish;
5048         }
5049
5050         if (!(m = dbus_message_new_method_call(
5051                               "com.ubuntu.Upstart",
5052                               "/com/ubuntu/Upstart",
5053                               "com.ubuntu.Upstart0_6",
5054                               "EmitEvent"))) {
5055
5056                 log_error("Could not allocate message.");
5057                 r = -ENOMEM;
5058                 goto finish;
5059         }
5060
5061         dbus_message_iter_init_append(m, &iter);
5062
5063         env1_buf[sizeof(env1_buf)-2] = rl;
5064         env2_buf[sizeof(env2_buf)-2] = previous;
5065
5066         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5067             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5068             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5069             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5070             !dbus_message_iter_close_container(&iter, &sub) ||
5071             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5072                 log_error("Could not append arguments to message.");
5073                 r = -ENOMEM;
5074                 goto finish;
5075         }
5076
5077         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5078
5079                 if (error_is_no_service(&error)) {
5080                         r = -EADDRNOTAVAIL;
5081                         goto finish;
5082                 }
5083
5084                 log_error("Failed to issue method call: %s", bus_error_message(&error));
5085                 r = -EIO;
5086                 goto finish;
5087         }
5088
5089         r = 0;
5090
5091 finish:
5092         if (m)
5093                 dbus_message_unref(m);
5094
5095         if (reply)
5096                 dbus_message_unref(reply);
5097
5098         if (bus) {
5099                 dbus_connection_flush(bus);
5100                 dbus_connection_close(bus);
5101                 dbus_connection_unref(bus);
5102         }
5103
5104         dbus_error_free(&error);
5105
5106         return r;
5107 }
5108
5109 static int talk_initctl(void) {
5110         struct init_request request;
5111         int r, fd;
5112         char rl;
5113
5114         if (!(rl = action_to_runlevel()))
5115                 return 0;
5116
5117         zero(request);
5118         request.magic = INIT_MAGIC;
5119         request.sleeptime = 0;
5120         request.cmd = INIT_CMD_RUNLVL;
5121         request.runlevel = rl;
5122
5123         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5124
5125                 if (errno == ENOENT)
5126                         return 0;
5127
5128                 log_error("Failed to open "INIT_FIFO": %m");
5129                 return -errno;
5130         }
5131
5132         errno = 0;
5133         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5134         close_nointr_nofail(fd);
5135
5136         if (r < 0) {
5137                 log_error("Failed to write to "INIT_FIFO": %m");
5138                 return errno ? -errno : -EIO;
5139         }
5140
5141         return 1;
5142 }
5143
5144 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
5145
5146         static const struct {
5147                 const char* verb;
5148                 const enum {
5149                         MORE,
5150                         LESS,
5151                         EQUAL
5152                 } argc_cmp;
5153                 const int argc;
5154                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5155         } verbs[] = {
5156                 { "list-units",            LESS,  1, list_units        },
5157                 { "list-jobs",             EQUAL, 1, list_jobs         },
5158                 { "clear-jobs",            EQUAL, 1, daemon_reload     },
5159                 { "load",                  MORE,  2, load_unit         },
5160                 { "cancel",                MORE,  2, cancel_job        },
5161                 { "start",                 MORE,  2, start_unit        },
5162                 { "stop",                  MORE,  2, start_unit        },
5163                 { "reload",                MORE,  2, start_unit        },
5164                 { "restart",               MORE,  2, start_unit        },
5165                 { "try-restart",           MORE,  2, start_unit        },
5166                 { "reload-or-restart",     MORE,  2, start_unit        },
5167                 { "reload-or-try-restart", MORE,  2, start_unit        },
5168                 { "force-reload",          MORE,  2, start_unit        }, /* For compatibility with SysV */
5169                 { "condrestart",           MORE,  2, start_unit        }, /* For compatibility with RH */
5170                 { "isolate",               EQUAL, 2, start_unit        },
5171                 { "kill",                  MORE,  2, kill_unit         },
5172                 { "is-active",             MORE,  2, check_unit        },
5173                 { "check",                 MORE,  2, check_unit        },
5174                 { "show",                  MORE,  1, show              },
5175                 { "status",                MORE,  2, show              },
5176                 { "monitor",               EQUAL, 1, monitor           },
5177                 { "dump",                  EQUAL, 1, dump              },
5178                 { "dot",                   EQUAL, 1, dot               },
5179                 { "snapshot",              LESS,  2, snapshot          },
5180                 { "delete",                MORE,  2, delete_snapshot   },
5181                 { "daemon-reload",         EQUAL, 1, daemon_reload     },
5182                 { "daemon-reexec",         EQUAL, 1, daemon_reload     },
5183                 { "show-environment",      EQUAL, 1, show_enviroment   },
5184                 { "set-environment",       MORE,  2, set_environment   },
5185                 { "unset-environment",     MORE,  2, set_environment   },
5186                 { "halt",                  EQUAL, 1, start_special     },
5187                 { "poweroff",              EQUAL, 1, start_special     },
5188                 { "reboot",                EQUAL, 1, start_special     },
5189                 { "kexec",                 EQUAL, 1, start_special     },
5190                 { "default",               EQUAL, 1, start_special     },
5191                 { "rescue",                EQUAL, 1, start_special     },
5192                 { "emergency",             EQUAL, 1, start_special     },
5193                 { "exit",                  EQUAL, 1, start_special     },
5194                 { "reset-failed",          MORE,  1, reset_failed      },
5195                 { "enable",                MORE,  2, enable_unit       },
5196                 { "disable",               MORE,  2, enable_unit       },
5197                 { "is-enabled",            MORE,  2, enable_unit       }
5198         };
5199
5200         int left;
5201         unsigned i;
5202
5203         assert(argc >= 0);
5204         assert(argv);
5205         assert(error);
5206
5207         left = argc - optind;
5208
5209         if (left <= 0)
5210                 /* Special rule: no arguments means "list-units" */
5211                 i = 0;
5212         else {
5213                 if (streq(argv[optind], "help")) {
5214                         systemctl_help();
5215                         return 0;
5216                 }
5217
5218                 for (i = 0; i < ELEMENTSOF(verbs); i++)
5219                         if (streq(argv[optind], verbs[i].verb))
5220                                 break;
5221
5222                 if (i >= ELEMENTSOF(verbs)) {
5223                         log_error("Unknown operation %s", argv[optind]);
5224                         return -EINVAL;
5225                 }
5226         }
5227
5228         switch (verbs[i].argc_cmp) {
5229
5230         case EQUAL:
5231                 if (left != verbs[i].argc) {
5232                         log_error("Invalid number of arguments.");
5233                         return -EINVAL;
5234                 }
5235
5236                 break;
5237
5238         case MORE:
5239                 if (left < verbs[i].argc) {
5240                         log_error("Too few arguments.");
5241                         return -EINVAL;
5242                 }
5243
5244                 break;
5245
5246         case LESS:
5247                 if (left > verbs[i].argc) {
5248                         log_error("Too many arguments.");
5249                         return -EINVAL;
5250                 }
5251
5252                 break;
5253
5254         default:
5255                 assert_not_reached("Unknown comparison operator.");
5256         }
5257
5258         /* Require a bus connection for all operations but
5259          * enable/disable */
5260         if (!streq(verbs[i].verb, "enable") &&
5261             !streq(verbs[i].verb, "disable") &&
5262             !bus) {
5263                 log_error("Failed to get D-Bus connection: %s", error->message);
5264                 return -EIO;
5265         }
5266
5267         return verbs[i].dispatch(bus, argv + optind, left);
5268 }
5269
5270 static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
5271         int fd = -1;
5272         struct msghdr msghdr;
5273         struct iovec iovec;
5274         union sockaddr_union sockaddr;
5275         struct shutdownd_command c;
5276
5277         zero(c);
5278         c.elapse = t;
5279         c.mode = mode;
5280         c.warn_wall = warn;
5281
5282         if (message)
5283                 strncpy(c.wall_message, message, sizeof(c.wall_message));
5284
5285         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5286                 return -errno;
5287
5288         zero(sockaddr);
5289         sockaddr.sa.sa_family = AF_UNIX;
5290         sockaddr.un.sun_path[0] = 0;
5291         strncpy(sockaddr.un.sun_path+1, "/org/freedesktop/systemd1/shutdownd", sizeof(sockaddr.un.sun_path)-1);
5292
5293         zero(iovec);
5294         iovec.iov_base = (char*) &c;
5295         iovec.iov_len = sizeof(c);
5296
5297         zero(msghdr);
5298         msghdr.msg_name = &sockaddr;
5299         msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + 1 + sizeof("/org/freedesktop/systemd1/shutdownd") - 1;
5300
5301         msghdr.msg_iov = &iovec;
5302         msghdr.msg_iovlen = 1;
5303
5304         if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5305                 close_nointr_nofail(fd);
5306                 return -errno;
5307         }
5308
5309         close_nointr_nofail(fd);
5310         return 0;
5311 }
5312
5313 static int reload_with_fallback(DBusConnection *bus) {
5314
5315         if (bus) {
5316                 /* First, try systemd via D-Bus. */
5317                 if (daemon_reload(bus, NULL, 0) > 0)
5318                         return 0;
5319         }
5320
5321         /* Nothing else worked, so let's try signals */
5322         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5323
5324         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5325                 log_error("kill() failed: %m");
5326                 return -errno;
5327         }
5328
5329         return 0;
5330 }
5331
5332 static int start_with_fallback(DBusConnection *bus) {
5333
5334         if (bus) {
5335                 /* First, try systemd via D-Bus. */
5336                 if (start_unit(bus, NULL, 0) >= 0)
5337                         goto done;
5338         }
5339
5340         /* Hmm, talking to systemd via D-Bus didn't work. Then
5341          * let's try to talk to Upstart via D-Bus. */
5342         if (talk_upstart() > 0)
5343                 goto done;
5344
5345         /* Nothing else worked, so let's try
5346          * /dev/initctl */
5347         if (talk_initctl() > 0)
5348                 goto done;
5349
5350         log_error("Failed to talk to init daemon.");
5351         return -EIO;
5352
5353 done:
5354         warn_wall(arg_action);
5355         return 0;
5356 }
5357
5358 static int halt_main(DBusConnection *bus) {
5359         int r;
5360
5361         if (geteuid() != 0) {
5362                 log_error("Must be root.");
5363                 return -EPERM;
5364         }
5365
5366         if (arg_when > 0) {
5367                 char *m;
5368                 char date[FORMAT_TIMESTAMP_MAX];
5369
5370                 m = strv_join(arg_wall, " ");
5371                 r = send_shutdownd(arg_when,
5372                                    arg_action == ACTION_HALT     ? 'H' :
5373                                    arg_action == ACTION_POWEROFF ? 'P' :
5374                                                                    'r',
5375                                    !arg_no_wall,
5376                                    m);
5377                 free(m);
5378
5379                 if (r < 0)
5380                         log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5381                 else {
5382                         log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5383                                  format_timestamp(date, sizeof(date), arg_when));
5384                         return 0;
5385                 }
5386         }
5387
5388         if (!arg_dry && !arg_immediate)
5389                 return start_with_fallback(bus);
5390
5391         if (!arg_no_wtmp) {
5392                 if (sd_booted() > 0)
5393                         log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5394                 else if ((r = utmp_put_shutdown(0)) < 0)
5395                         log_warning("Failed to write utmp record: %s", strerror(-r));
5396         }
5397
5398         if (!arg_no_sync)
5399                 sync();
5400
5401         if (arg_dry)
5402                 return 0;
5403
5404         /* Make sure C-A-D is handled by the kernel from this
5405          * point on... */
5406         reboot(RB_ENABLE_CAD);
5407
5408         switch (arg_action) {
5409
5410         case ACTION_HALT:
5411                 log_info("Halting.");
5412                 reboot(RB_HALT_SYSTEM);
5413                 break;
5414
5415         case ACTION_POWEROFF:
5416                 log_info("Powering off.");
5417                 reboot(RB_POWER_OFF);
5418                 break;
5419
5420         case ACTION_REBOOT:
5421                 log_info("Rebooting.");
5422                 reboot(RB_AUTOBOOT);
5423                 break;
5424
5425         default:
5426                 assert_not_reached("Unknown halt action.");
5427         }
5428
5429         /* We should never reach this. */
5430         return -ENOSYS;
5431 }
5432
5433 static int runlevel_main(void) {
5434         int r, runlevel, previous;
5435
5436         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
5437                 printf("unknown\n");
5438                 return r;
5439         }
5440
5441         printf("%c %c\n",
5442                previous <= 0 ? 'N' : previous,
5443                runlevel <= 0 ? 'N' : runlevel);
5444
5445         return 0;
5446 }
5447
5448 static void pager_open(void) {
5449         int fd[2];
5450         const char *pager;
5451         pid_t parent_pid;
5452
5453         if (pager_pid > 0)
5454                 return;
5455
5456         if (!on_tty() || arg_no_pager)
5457                 return;
5458
5459         if ((pager = getenv("PAGER")))
5460                 if (!*pager || streq(pager, "cat"))
5461                         return;
5462
5463         /* Determine and cache number of columns before we spawn the
5464          * pager so that we get the value from the actual tty */
5465         columns();
5466
5467         if (pipe(fd) < 0) {
5468                 log_error("Failed to create pager pipe: %m");
5469                 return;
5470         }
5471
5472         parent_pid = getpid();
5473
5474         pager_pid = fork();
5475         if (pager_pid < 0) {
5476                 log_error("Failed to fork pager: %m");
5477                 close_pipe(fd);
5478                 return;
5479         }
5480
5481         /* In the child start the pager */
5482         if (pager_pid == 0) {
5483
5484                 dup2(fd[0], STDIN_FILENO);
5485                 close_pipe(fd);
5486
5487                 setenv("LESS", "FRSX", 0);
5488
5489                 /* Make sure the pager goes away when the parent dies */
5490                 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5491                         _exit(EXIT_FAILURE);
5492
5493                 /* Check whether our parent died before we were able
5494                  * to set the death signal */
5495                 if (getppid() != parent_pid)
5496                         _exit(EXIT_SUCCESS);
5497
5498                 if (pager) {
5499                         execlp(pager, pager, NULL);
5500                         execl("/bin/sh", "sh", "-c", pager, NULL);
5501                 } else {
5502                         /* Debian's alternatives command for pagers is
5503                          * called 'pager'. Note that we do not call
5504                          * sensible-pagers here, since that is just a
5505                          * shell script that implements a logic that
5506                          * is similar to this one anyway, but is
5507                          * Debian-specific. */
5508                         execlp("pager", "pager", NULL);
5509
5510                         execlp("less", "less", NULL);
5511                         execlp("more", "more", NULL);
5512                 }
5513
5514                 log_error("Unable to execute pager: %m");
5515                 _exit(EXIT_FAILURE);
5516         }
5517
5518         /* Return in the parent */
5519         if (dup2(fd[1], STDOUT_FILENO) < 0)
5520                 log_error("Failed to duplicate pager pipe: %m");
5521
5522         close_pipe(fd);
5523 }
5524
5525 static void pager_close(void) {
5526         siginfo_t dummy;
5527
5528         if (pager_pid <= 0)
5529                 return;
5530
5531         /* Inform pager that we are done */
5532         fclose(stdout);
5533         wait_for_terminate(pager_pid, &dummy);
5534         pager_pid = 0;
5535 }
5536
5537 static void agent_close(void) {
5538         siginfo_t dummy;
5539
5540         if (agent_pid <= 0)
5541                 return;
5542
5543         /* Inform agent that we are done */
5544         kill(agent_pid, SIGTERM);
5545         wait_for_terminate(agent_pid, &dummy);
5546         agent_pid = 0;
5547 }
5548
5549 int main(int argc, char*argv[]) {
5550         int r, retval = EXIT_FAILURE;
5551         DBusConnection *bus = NULL;
5552         DBusError error;
5553
5554         dbus_error_init(&error);
5555
5556         log_parse_environment();
5557         log_open();
5558
5559         if ((r = parse_argv(argc, argv)) < 0)
5560                 goto finish;
5561         else if (r == 0) {
5562                 retval = EXIT_SUCCESS;
5563                 goto finish;
5564         }
5565
5566         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5567          * let's shortcut this */
5568         if (arg_action == ACTION_RUNLEVEL) {
5569                 r = runlevel_main();
5570                 retval = r < 0 ? EXIT_FAILURE : r;
5571                 goto finish;
5572         }
5573
5574         bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5575
5576         switch (arg_action) {
5577
5578         case ACTION_SYSTEMCTL:
5579                 r = systemctl_main(bus, argc, argv, &error);
5580                 break;
5581
5582         case ACTION_HALT:
5583         case ACTION_POWEROFF:
5584         case ACTION_REBOOT:
5585         case ACTION_KEXEC:
5586                 r = halt_main(bus);
5587                 break;
5588
5589         case ACTION_RUNLEVEL2:
5590         case ACTION_RUNLEVEL3:
5591         case ACTION_RUNLEVEL4:
5592         case ACTION_RUNLEVEL5:
5593         case ACTION_RESCUE:
5594         case ACTION_EMERGENCY:
5595         case ACTION_DEFAULT:
5596                 r = start_with_fallback(bus);
5597                 break;
5598
5599         case ACTION_RELOAD:
5600         case ACTION_REEXEC:
5601                 r = reload_with_fallback(bus);
5602                 break;
5603
5604         case ACTION_CANCEL_SHUTDOWN:
5605                 r = send_shutdownd(0, 0, false, NULL);
5606                 break;
5607
5608         case ACTION_INVALID:
5609         case ACTION_RUNLEVEL:
5610         default:
5611                 assert_not_reached("Unknown action");
5612         }
5613
5614         retval = r < 0 ? EXIT_FAILURE : r;
5615
5616 finish:
5617
5618         if (bus) {
5619                 dbus_connection_flush(bus);
5620                 dbus_connection_close(bus);
5621                 dbus_connection_unref(bus);
5622         }
5623
5624         dbus_error_free(&error);
5625
5626         dbus_shutdown();
5627
5628         strv_free(arg_property);
5629
5630         pager_close();
5631         agent_close();
5632
5633         return retval;
5634 }