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