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