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