chiark / gitweb /
systemctl: properly detect whether taling to systemd via D-Bus worked before falling...
[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                 if ((r = wait_for_jobs(bus, s)) < 0)
1175                         goto finish;
1176
1177         r = 1;
1178
1179 finish:
1180         if (s)
1181                 set_free_free(s);
1182
1183         return r;
1184 }
1185
1186 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1187         int r;
1188
1189         assert(bus);
1190         assert(args);
1191
1192         r = start_unit(bus, args, n);
1193
1194         if (r >= 0)
1195                 warn_wall(verb_to_action(args[0]));
1196
1197         return r;
1198 }
1199
1200 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1201         DBusMessage *m = NULL, *reply = NULL;
1202         const char
1203                 *interface = "org.freedesktop.systemd1.Unit",
1204                 *property = "ActiveState";
1205         int r = -EADDRNOTAVAIL;
1206         DBusError error;
1207         unsigned i;
1208
1209         assert(bus);
1210         assert(args);
1211
1212         dbus_error_init(&error);
1213
1214         for (i = 1; i < n; i++) {
1215                 const char *path = NULL;
1216                 const char *state;
1217                 DBusMessageIter iter, sub;
1218
1219                 if (!(m = dbus_message_new_method_call(
1220                                       "org.freedesktop.systemd1",
1221                                       "/org/freedesktop/systemd1",
1222                                       "org.freedesktop.systemd1.Manager",
1223                                       "GetUnit"))) {
1224                         log_error("Could not allocate message.");
1225                         r = -ENOMEM;
1226                         goto finish;
1227                 }
1228
1229                 if (!dbus_message_append_args(m,
1230                                               DBUS_TYPE_STRING, &args[i],
1231                                               DBUS_TYPE_INVALID)) {
1232                         log_error("Could not append arguments to message.");
1233                         r = -ENOMEM;
1234                         goto finish;
1235                 }
1236
1237                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1238
1239                         /* Hmm, cannot figure out anything about this unit... */
1240                         if (!arg_quiet)
1241                                 puts("unknown");
1242
1243                         dbus_error_free(&error);
1244                         continue;
1245                 }
1246
1247                 if (!dbus_message_get_args(reply, &error,
1248                                            DBUS_TYPE_OBJECT_PATH, &path,
1249                                            DBUS_TYPE_INVALID)) {
1250                         log_error("Failed to parse reply: %s", error.message);
1251                         r = -EIO;
1252                         goto finish;
1253                 }
1254
1255                 dbus_message_unref(m);
1256                 if (!(m = dbus_message_new_method_call(
1257                                       "org.freedesktop.systemd1",
1258                                       path,
1259                                       "org.freedesktop.DBus.Properties",
1260                                       "Get"))) {
1261                         log_error("Could not allocate message.");
1262                         r = -ENOMEM;
1263                         goto finish;
1264                 }
1265
1266                 if (!dbus_message_append_args(m,
1267                                               DBUS_TYPE_STRING, &interface,
1268                                               DBUS_TYPE_STRING, &property,
1269                                               DBUS_TYPE_INVALID)) {
1270                         log_error("Could not append arguments to message.");
1271                         r = -ENOMEM;
1272                         goto finish;
1273                 }
1274
1275                 dbus_message_unref(reply);
1276                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1277                         log_error("Failed to issue method call: %s", error.message);
1278                         r = -EIO;
1279                         goto finish;
1280                 }
1281
1282                 if (!dbus_message_iter_init(reply, &iter) ||
1283                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1284                         log_error("Failed to parse reply.");
1285                         r = -EIO;
1286                         goto finish;
1287                 }
1288
1289                 dbus_message_iter_recurse(&iter, &sub);
1290
1291                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1292                         log_error("Failed to parse reply.");
1293                         r = -EIO;
1294                         goto finish;
1295                 }
1296
1297                 dbus_message_iter_get_basic(&sub, &state);
1298
1299                 if (!arg_quiet)
1300                         puts(state);
1301
1302                 if (streq(state, "active") || startswith(state, "reloading"))
1303                         r = 0;
1304
1305                 dbus_message_unref(m);
1306                 dbus_message_unref(reply);
1307                 m = reply = NULL;
1308         }
1309
1310 finish:
1311         if (m)
1312                 dbus_message_unref(m);
1313
1314         if (reply)
1315                 dbus_message_unref(reply);
1316
1317         dbus_error_free(&error);
1318
1319         return r;
1320 }
1321
1322 typedef struct ExecStatusInfo {
1323         char *path;
1324         char **argv;
1325
1326         bool ignore;
1327
1328         usec_t start_timestamp;
1329         usec_t exit_timestamp;
1330         pid_t pid;
1331         int code;
1332         int status;
1333
1334         LIST_FIELDS(struct ExecStatusInfo, exec);
1335 } ExecStatusInfo;
1336
1337 static void exec_status_info_free(ExecStatusInfo *i) {
1338         assert(i);
1339
1340         free(i->path);
1341         strv_free(i->argv);
1342         free(i);
1343 }
1344
1345 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1346         uint64_t start_timestamp, exit_timestamp;
1347         DBusMessageIter sub2, sub3;
1348         const char*path;
1349         unsigned n;
1350         uint32_t pid;
1351         int32_t code, status;
1352         dbus_bool_t ignore;
1353
1354         assert(i);
1355         assert(i);
1356
1357         if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1358                 return -EIO;
1359
1360         dbus_message_iter_recurse(sub, &sub2);
1361
1362         if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1363                 return -EIO;
1364
1365         if (!(i->path = strdup(path)))
1366                 return -ENOMEM;
1367
1368         if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1369             dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1370                 return -EIO;
1371
1372         n = 0;
1373         dbus_message_iter_recurse(&sub2, &sub3);
1374         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1375                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1376                 dbus_message_iter_next(&sub3);
1377                 n++;
1378         }
1379
1380
1381         if (!(i->argv = new0(char*, n+1)))
1382                 return -ENOMEM;
1383
1384         n = 0;
1385         dbus_message_iter_recurse(&sub2, &sub3);
1386         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1387                 const char *s;
1388
1389                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1390                 dbus_message_iter_get_basic(&sub3, &s);
1391                 dbus_message_iter_next(&sub3);
1392
1393                 if (!(i->argv[n++] = strdup(s)))
1394                         return -ENOMEM;
1395         }
1396
1397         if (!dbus_message_iter_next(&sub2) ||
1398             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1399             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1400             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1401             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1402             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1403             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1404                 return -EIO;
1405
1406         i->ignore = ignore;
1407         i->start_timestamp = (usec_t) start_timestamp;
1408         i->exit_timestamp = (usec_t) exit_timestamp;
1409         i->pid = (pid_t) pid;
1410         i->code = code;
1411         i->status = status;
1412
1413         return 0;
1414 }
1415
1416 typedef struct UnitStatusInfo {
1417         const char *id;
1418         const char *load_state;
1419         const char *active_state;
1420         const char *sub_state;
1421
1422         const char *description;
1423
1424         const char *path;
1425         const char *default_control_group;
1426
1427         bool need_daemon_reload;
1428
1429         /* Service */
1430         pid_t main_pid;
1431         pid_t control_pid;
1432         const char *status_text;
1433         bool running;
1434
1435         usec_t start_timestamp;
1436         usec_t exit_timestamp;
1437
1438         int exit_code, exit_status;
1439
1440         /* Socket */
1441         unsigned n_accepted;
1442         unsigned n_connections;
1443         bool accept;
1444
1445         /* Device */
1446         const char *sysfs_path;
1447
1448         /* Mount, Automount */
1449         const char *where;
1450
1451         /* Swap */
1452         const char *what;
1453
1454         LIST_HEAD(ExecStatusInfo, exec);
1455 } UnitStatusInfo;
1456
1457 static void print_status_info(UnitStatusInfo *i) {
1458         ExecStatusInfo *p;
1459         const char *on, *off, *ss;
1460
1461         assert(i);
1462
1463         /* This shows pretty information about a unit. See
1464          * print_property() for a low-level property printer */
1465
1466         printf("%s", strna(i->id));
1467
1468         if (i->description && !streq_ptr(i->id, i->description))
1469                 printf(" - %s", i->description);
1470
1471         printf("\n");
1472
1473         if (streq_ptr(i->load_state, "failed")) {
1474                 on = ansi_highlight(true);
1475                 off = ansi_highlight(false);
1476         } else
1477                 on = off = "";
1478
1479         if (i->path)
1480                 printf("\t  Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
1481         else
1482                 printf("\t  Loaded: %s%s%s\n", on, strna(i->load_state), off);
1483
1484         ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1485
1486         if (streq_ptr(i->active_state, "maintenance")) {
1487                 on = ansi_highlight(true);
1488                 off = ansi_highlight(false);
1489         } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1490                 on = ansi_highlight_green(true);
1491                 off = ansi_highlight_green(false);
1492         } else
1493                 on = off = "";
1494
1495         if (ss)
1496                 printf("\t  Active: %s%s (%s)%s\n",
1497                        on,
1498                        strna(i->active_state),
1499                        ss,
1500                        off);
1501         else
1502                 printf("\t  Active: %s%s%s\n",
1503                        on,
1504                        strna(i->active_state),
1505                        off);
1506
1507         if (i->sysfs_path)
1508                 printf("\t  Device: %s\n", i->sysfs_path);
1509         else if (i->where)
1510                 printf("\t   Where: %s\n", i->where);
1511         else if (i->what)
1512                 printf("\t    What: %s\n", i->what);
1513
1514         if (i->accept)
1515                 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1516
1517         LIST_FOREACH(exec, p, i->exec) {
1518                 char *t;
1519
1520                 /* Only show exited processes here */
1521                 if (p->code == 0)
1522                         continue;
1523
1524                 t = strv_join(p->argv, " ");
1525                 printf("\t  Exited: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1526                 free(t);
1527
1528                 if (p->code == CLD_EXITED)
1529                         printf("status=%i", p->status);
1530                 else
1531                         printf("signal=%s", signal_to_string(p->status));
1532                 printf(")\n");
1533
1534                 if (i->main_pid == p->pid &&
1535                     i->start_timestamp == p->start_timestamp &&
1536                     i->exit_timestamp == p->start_timestamp)
1537                         /* Let's not show this twice */
1538                         i->main_pid = 0;
1539
1540                 if (p->pid == i->control_pid)
1541                         i->control_pid = 0;
1542         }
1543
1544         if (i->main_pid > 0 || i->control_pid > 0) {
1545                 printf("\t");
1546
1547                 if (i->main_pid > 0) {
1548                         printf("    Main: %u", (unsigned) i->main_pid);
1549
1550                         if (i->running) {
1551                                 char *t = NULL;
1552                                 get_process_name(i->main_pid, &t);
1553                                 if (t) {
1554                                         printf(" (%s)", t);
1555                                         free(t);
1556                                 }
1557                         } else if (i->exit_code > 0) {
1558                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1559
1560                                 if (i->exit_code == CLD_EXITED)
1561                                         printf("status=%i", i->exit_status);
1562                                 else
1563                                         printf("signal=%s", signal_to_string(i->exit_status));
1564                                 printf(")");
1565                         }
1566                 }
1567
1568                 if (i->main_pid > 0 && i->control_pid > 0)
1569                         printf(";");
1570
1571                 if (i->control_pid > 0) {
1572                         char *t = NULL;
1573
1574                         printf(" Control: %u", (unsigned) i->control_pid);
1575
1576                         get_process_name(i->control_pid, &t);
1577                         if (t) {
1578                                 printf(" (%s)", t);
1579                                 free(t);
1580                         }
1581                 }
1582
1583                 printf("\n");
1584         }
1585
1586         if (i->status_text)
1587                 printf("\t  Status: \"%s\"\n", i->status_text);
1588
1589         if (i->default_control_group) {
1590                 unsigned c;
1591
1592                 printf("\t  CGroup: %s\n", i->default_control_group);
1593
1594                 if ((c = columns()) > 18)
1595                         c -= 18;
1596                 else
1597                         c = 0;
1598
1599                 show_cgroup_by_path(i->default_control_group, "\t\t  ", c);
1600         }
1601
1602         if (i->need_daemon_reload)
1603                 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1604                        ansi_highlight(true),
1605                        ansi_highlight(false),
1606                        arg_session ? "--session" : "--system");
1607 }
1608
1609 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1610
1611         switch (dbus_message_iter_get_arg_type(iter)) {
1612
1613         case DBUS_TYPE_STRING: {
1614                 const char *s;
1615
1616                 dbus_message_iter_get_basic(iter, &s);
1617
1618                 if (s[0]) {
1619                         if (streq(name, "Id"))
1620                                 i->id = s;
1621                         else if (streq(name, "LoadState"))
1622                                 i->load_state = s;
1623                         else if (streq(name, "ActiveState"))
1624                                 i->active_state = s;
1625                         else if (streq(name, "SubState"))
1626                                 i->sub_state = s;
1627                         else if (streq(name, "Description"))
1628                                 i->description = s;
1629                         else if (streq(name, "FragmentPath"))
1630                                 i->path = s;
1631                         else if (streq(name, "SysVPath"))
1632                                 i->path = s;
1633                         else if (streq(name, "DefaultControlGroup"))
1634                                 i->default_control_group = s;
1635                         else if (streq(name, "StatusText"))
1636                                 i->status_text = s;
1637                         else if (streq(name, "SysFSPath"))
1638                                 i->sysfs_path = s;
1639                         else if (streq(name, "Where"))
1640                                 i->where = s;
1641                         else if (streq(name, "What"))
1642                                 i->what = s;
1643                 }
1644
1645                 break;
1646         }
1647
1648         case DBUS_TYPE_BOOLEAN: {
1649                 dbus_bool_t b;
1650
1651                 dbus_message_iter_get_basic(iter, &b);
1652
1653                 if (streq(name, "Accept"))
1654                         i->accept = b;
1655                 else if (streq(name, "NeedDaemonReload"))
1656                         i->need_daemon_reload = b;
1657
1658                 break;
1659         }
1660
1661         case DBUS_TYPE_UINT32: {
1662                 uint32_t u;
1663
1664                 dbus_message_iter_get_basic(iter, &u);
1665
1666                 if (streq(name, "MainPID")) {
1667                         if (u > 0) {
1668                                 i->main_pid = (pid_t) u;
1669                                 i->running = true;
1670                         }
1671                 } else if (streq(name, "ControlPID"))
1672                         i->control_pid = (pid_t) u;
1673                 else if (streq(name, "ExecMainPID")) {
1674                         if (u > 0)
1675                                 i->main_pid = (pid_t) u;
1676                 } else if (streq(name, "NAccepted"))
1677                         i->n_accepted = u;
1678                 else if (streq(name, "NConnections"))
1679                         i->n_connections = u;
1680
1681                 break;
1682         }
1683
1684         case DBUS_TYPE_INT32: {
1685                 int32_t j;
1686
1687                 dbus_message_iter_get_basic(iter, &j);
1688
1689                 if (streq(name, "ExecMainCode"))
1690                         i->exit_code = (int) j;
1691                 else if (streq(name, "ExecMainStatus"))
1692                         i->exit_status = (int) j;
1693
1694                 break;
1695         }
1696
1697         case DBUS_TYPE_UINT64: {
1698                 uint64_t u;
1699
1700                 dbus_message_iter_get_basic(iter, &u);
1701
1702                 if (streq(name, "ExecMainStartTimestamp"))
1703                         i->start_timestamp = (usec_t) u;
1704                 else if (streq(name, "ExecMainExitTimestamp"))
1705                         i->exit_timestamp = (usec_t) u;
1706
1707                 break;
1708         }
1709
1710         case DBUS_TYPE_ARRAY: {
1711
1712                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1713                     startswith(name, "Exec")) {
1714                         DBusMessageIter sub;
1715
1716                         dbus_message_iter_recurse(iter, &sub);
1717                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1718                                 ExecStatusInfo *info;
1719                                 int r;
1720
1721                                 if (!(info = new0(ExecStatusInfo, 1)))
1722                                         return -ENOMEM;
1723
1724                                 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1725                                         free(info);
1726                                         return r;
1727                                 }
1728
1729                                 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1730
1731                                 dbus_message_iter_next(&sub);
1732                         }
1733                 }
1734
1735                 break;
1736         }
1737         }
1738
1739         return 0;
1740 }
1741
1742 static int print_property(const char *name, DBusMessageIter *iter) {
1743         assert(name);
1744         assert(iter);
1745
1746         /* This is a low-level property printer, see
1747          * print_status_info() for the nicer output */
1748
1749         if (arg_property && !strv_find(arg_property, name))
1750                 return 0;
1751
1752         switch (dbus_message_iter_get_arg_type(iter)) {
1753
1754         case DBUS_TYPE_STRING: {
1755                 const char *s;
1756                 dbus_message_iter_get_basic(iter, &s);
1757
1758                 if (arg_all || s[0])
1759                         printf("%s=%s\n", name, s);
1760
1761                 return 0;
1762         }
1763
1764         case DBUS_TYPE_BOOLEAN: {
1765                 dbus_bool_t b;
1766                 dbus_message_iter_get_basic(iter, &b);
1767                 printf("%s=%s\n", name, yes_no(b));
1768
1769                 return 0;
1770         }
1771
1772         case DBUS_TYPE_UINT64: {
1773                 uint64_t u;
1774                 dbus_message_iter_get_basic(iter, &u);
1775
1776                 /* Yes, heuristics! But we can change this check
1777                  * should it turn out to not be sufficient */
1778
1779                 if (strstr(name, "Timestamp")) {
1780                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1781
1782                         if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1783                                 printf("%s=%s\n", name, strempty(t));
1784                 } else if (strstr(name, "USec")) {
1785                         char timespan[FORMAT_TIMESPAN_MAX];
1786
1787                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1788                 } else
1789                         printf("%s=%llu\n", name, (unsigned long long) u);
1790
1791                 return 0;
1792         }
1793
1794         case DBUS_TYPE_UINT32: {
1795                 uint32_t u;
1796                 dbus_message_iter_get_basic(iter, &u);
1797
1798                 if (strstr(name, "UMask") || strstr(name, "Mode"))
1799                         printf("%s=%04o\n", name, u);
1800                 else
1801                         printf("%s=%u\n", name, (unsigned) u);
1802
1803                 return 0;
1804         }
1805
1806         case DBUS_TYPE_INT32: {
1807                 int32_t i;
1808                 dbus_message_iter_get_basic(iter, &i);
1809
1810                 printf("%s=%i\n", name, (int) i);
1811                 return 0;
1812         }
1813
1814         case DBUS_TYPE_STRUCT: {
1815                 DBusMessageIter sub;
1816                 dbus_message_iter_recurse(iter, &sub);
1817
1818                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1819                         uint32_t u;
1820
1821                         dbus_message_iter_get_basic(&sub, &u);
1822
1823                         if (u)
1824                                 printf("%s=%u\n", name, (unsigned) u);
1825                         else if (arg_all)
1826                                 printf("%s=\n", name);
1827
1828                         return 0;
1829                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1830                         const char *s;
1831
1832                         dbus_message_iter_get_basic(&sub, &s);
1833
1834                         if (arg_all || s[0])
1835                                 printf("%s=%s\n", name, s);
1836
1837                         return 0;
1838                 }
1839
1840                 break;
1841         }
1842
1843         case DBUS_TYPE_ARRAY:
1844
1845                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1846                         DBusMessageIter sub;
1847                         bool space = false;
1848
1849                         dbus_message_iter_recurse(iter, &sub);
1850                         if (arg_all ||
1851                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1852                                 printf("%s=", name);
1853
1854                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1855                                         const char *s;
1856
1857                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1858                                         dbus_message_iter_get_basic(&sub, &s);
1859                                         printf("%s%s", space ? " " : "", s);
1860
1861                                         space = true;
1862                                         dbus_message_iter_next(&sub);
1863                                 }
1864
1865                                 puts("");
1866                         }
1867
1868                         return 0;
1869
1870                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1871                         DBusMessageIter sub;
1872
1873                         dbus_message_iter_recurse(iter, &sub);
1874                         if (arg_all ||
1875                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1876                                 printf("%s=", name);
1877
1878                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1879                                         uint8_t u;
1880
1881                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1882                                         dbus_message_iter_get_basic(&sub, &u);
1883                                         printf("%02x", u);
1884
1885                                         dbus_message_iter_next(&sub);
1886                                 }
1887
1888                                 puts("");
1889                         }
1890
1891                         return 0;
1892
1893                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1894                         DBusMessageIter sub, sub2;
1895
1896                         dbus_message_iter_recurse(iter, &sub);
1897                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1898                                 const char *type, *path;
1899
1900                                 dbus_message_iter_recurse(&sub, &sub2);
1901
1902                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1903                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1904                                         printf("%s=%s\n", type, path);
1905
1906                                 dbus_message_iter_next(&sub);
1907                         }
1908
1909                         return 0;
1910
1911                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1912                         DBusMessageIter sub, sub2;
1913
1914                         dbus_message_iter_recurse(iter, &sub);
1915                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1916                                 const char *base;
1917                                 uint64_t value, next_elapse;
1918
1919                                 dbus_message_iter_recurse(&sub, &sub2);
1920
1921                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
1922                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
1923                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
1924                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
1925
1926                                         printf("%s={ value=%s ; next_elapse=%s }\n",
1927                                                base,
1928                                                format_timespan(timespan1, sizeof(timespan1), value),
1929                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
1930                                 }
1931
1932                                 dbus_message_iter_next(&sub);
1933                         }
1934
1935                         return 0;
1936
1937                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
1938                         DBusMessageIter sub;
1939
1940                         dbus_message_iter_recurse(iter, &sub);
1941                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1942                                 ExecStatusInfo info;
1943
1944                                 zero(info);
1945                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
1946                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
1947                                         char *t;
1948
1949                                         t = strv_join(info.argv, " ");
1950
1951                                         printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
1952                                                name,
1953                                                strna(info.path),
1954                                                strna(t),
1955                                                yes_no(info.ignore),
1956                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
1957                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
1958                                                (unsigned) info. pid,
1959                                                sigchld_code_to_string(info.code),
1960                                                info.status,
1961                                                info.code == CLD_EXITED ? "" : "/",
1962                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
1963
1964                                         free(t);
1965                                 }
1966
1967                                 free(info.path);
1968                                 strv_free(info.argv);
1969
1970                                 dbus_message_iter_next(&sub);
1971                         }
1972
1973                         return 0;
1974                 }
1975
1976                 break;
1977         }
1978
1979         if (arg_all)
1980                 printf("%s=[unprintable]\n", name);
1981
1982         return 0;
1983 }
1984
1985 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
1986         DBusMessage *m = NULL, *reply = NULL;
1987         const char *interface = "";
1988         int r;
1989         DBusError error;
1990         DBusMessageIter iter, sub, sub2, sub3;
1991         UnitStatusInfo info;
1992         ExecStatusInfo *p;
1993
1994         assert(bus);
1995         assert(path);
1996         assert(new_line);
1997
1998         zero(info);
1999         dbus_error_init(&error);
2000
2001         if (!(m = dbus_message_new_method_call(
2002                               "org.freedesktop.systemd1",
2003                               path,
2004                               "org.freedesktop.DBus.Properties",
2005                               "GetAll"))) {
2006                 log_error("Could not allocate message.");
2007                 r = -ENOMEM;
2008                 goto finish;
2009         }
2010
2011         if (!dbus_message_append_args(m,
2012                                       DBUS_TYPE_STRING, &interface,
2013                                       DBUS_TYPE_INVALID)) {
2014                 log_error("Could not append arguments to message.");
2015                 r = -ENOMEM;
2016                 goto finish;
2017         }
2018
2019         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2020                 log_error("Failed to issue method call: %s", error.message);
2021                 r = -EIO;
2022                 goto finish;
2023         }
2024
2025         if (!dbus_message_iter_init(reply, &iter) ||
2026             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2027             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
2028                 log_error("Failed to parse reply.");
2029                 r = -EIO;
2030                 goto finish;
2031         }
2032
2033         dbus_message_iter_recurse(&iter, &sub);
2034
2035         if (*new_line)
2036                 printf("\n");
2037
2038         *new_line = true;
2039
2040         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2041                 const char *name;
2042
2043                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2044                         log_error("Failed to parse reply.");
2045                         r = -EIO;
2046                         goto finish;
2047                 }
2048
2049                 dbus_message_iter_recurse(&sub, &sub2);
2050
2051                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2052                         log_error("Failed to parse reply.");
2053                         r = -EIO;
2054                         goto finish;
2055                 }
2056
2057                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
2058                         log_error("Failed to parse reply.");
2059                         r = -EIO;
2060                         goto finish;
2061                 }
2062
2063                 dbus_message_iter_recurse(&sub2, &sub3);
2064
2065                 if (show_properties)
2066                         r = print_property(name, &sub3);
2067                 else
2068                         r = status_property(name, &sub3, &info);
2069
2070                 if (r < 0) {
2071                         log_error("Failed to parse reply.");
2072                         r = -EIO;
2073                         goto finish;
2074                 }
2075
2076                 dbus_message_iter_next(&sub);
2077         }
2078
2079         if (!show_properties)
2080                 print_status_info(&info);
2081
2082         while ((p = info.exec)) {
2083                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2084                 exec_status_info_free(p);
2085         }
2086
2087         r = 0;
2088
2089 finish:
2090         if (m)
2091                 dbus_message_unref(m);
2092
2093         if (reply)
2094                 dbus_message_unref(reply);
2095
2096         dbus_error_free(&error);
2097
2098         return r;
2099 }
2100
2101 static int show(DBusConnection *bus, char **args, unsigned n) {
2102         DBusMessage *m = NULL, *reply = NULL;
2103         int r;
2104         DBusError error;
2105         unsigned i;
2106         bool show_properties, new_line = false;
2107
2108         assert(bus);
2109         assert(args);
2110
2111         dbus_error_init(&error);
2112
2113         show_properties = !streq(args[0], "status");
2114
2115         if (show_properties && n <= 1) {
2116                 /* If not argument is specified inspect the manager
2117                  * itself */
2118
2119                 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2120                 goto finish;
2121         }
2122
2123         for (i = 1; i < n; i++) {
2124                 const char *path = NULL;
2125                 uint32_t id;
2126
2127                 if (safe_atou32(args[i], &id) < 0) {
2128
2129                         /* Interpret as unit name */
2130
2131                         if (!(m = dbus_message_new_method_call(
2132                                               "org.freedesktop.systemd1",
2133                                               "/org/freedesktop/systemd1",
2134                                               "org.freedesktop.systemd1.Manager",
2135                                               "LoadUnit"))) {
2136                                 log_error("Could not allocate message.");
2137                                 r = -ENOMEM;
2138                                 goto finish;
2139                         }
2140
2141                         if (!dbus_message_append_args(m,
2142                                                       DBUS_TYPE_STRING, &args[i],
2143                                                       DBUS_TYPE_INVALID)) {
2144                                 log_error("Could not append arguments to message.");
2145                                 r = -ENOMEM;
2146                                 goto finish;
2147                         }
2148
2149                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2150
2151                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2152                                         log_error("Failed to issue method call: %s", error.message);
2153                                         r = -EIO;
2154                                         goto finish;
2155                                 }
2156
2157                                 dbus_error_free(&error);
2158
2159                                 dbus_message_unref(m);
2160                                 if (!(m = dbus_message_new_method_call(
2161                                                       "org.freedesktop.systemd1",
2162                                                       "/org/freedesktop/systemd1",
2163                                                       "org.freedesktop.systemd1.Manager",
2164                                                       "GetUnit"))) {
2165                                         log_error("Could not allocate message.");
2166                                         r = -ENOMEM;
2167                                         goto finish;
2168                                 }
2169
2170                                 if (!dbus_message_append_args(m,
2171                                                               DBUS_TYPE_STRING, &args[i],
2172                                                               DBUS_TYPE_INVALID)) {
2173                                         log_error("Could not append arguments to message.");
2174                                         r = -ENOMEM;
2175                                         goto finish;
2176                                 }
2177
2178                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2179                                         log_error("Failed to issue method call: %s", error.message);
2180                                         r = -EIO;
2181                                         goto finish;
2182                                 }
2183                         }
2184
2185                 } else if (show_properties) {
2186
2187                         /* Interpret as job id */
2188
2189                         if (!(m = dbus_message_new_method_call(
2190                                               "org.freedesktop.systemd1",
2191                                               "/org/freedesktop/systemd1",
2192                                               "org.freedesktop.systemd1.Manager",
2193                                               "GetJob"))) {
2194                                 log_error("Could not allocate message.");
2195                                 r = -ENOMEM;
2196                                 goto finish;
2197                         }
2198
2199                         if (!dbus_message_append_args(m,
2200                                                       DBUS_TYPE_UINT32, &id,
2201                                                       DBUS_TYPE_INVALID)) {
2202                                 log_error("Could not append arguments to message.");
2203                                 r = -ENOMEM;
2204                                 goto finish;
2205                         }
2206
2207                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2208                                 log_error("Failed to issue method call: %s", error.message);
2209                                 r = -EIO;
2210                                 goto finish;
2211                         }
2212                 } else {
2213
2214                         /* Interpret as PID */
2215
2216                         if (!(m = dbus_message_new_method_call(
2217                                               "org.freedesktop.systemd1",
2218                                               "/org/freedesktop/systemd1",
2219                                               "org.freedesktop.systemd1.Manager",
2220                                               "GetUnitByPID"))) {
2221                                 log_error("Could not allocate message.");
2222                                 r = -ENOMEM;
2223                                 goto finish;
2224                         }
2225
2226                         if (!dbus_message_append_args(m,
2227                                                       DBUS_TYPE_UINT32, &id,
2228                                                       DBUS_TYPE_INVALID)) {
2229                                 log_error("Could not append arguments to message.");
2230                                 r = -ENOMEM;
2231                                 goto finish;
2232                         }
2233
2234                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2235                                 log_error("Failed to issue method call: %s", error.message);
2236                                 r = -EIO;
2237                                 goto finish;
2238                         }
2239                 }
2240
2241                 if (!dbus_message_get_args(reply, &error,
2242                                            DBUS_TYPE_OBJECT_PATH, &path,
2243                                            DBUS_TYPE_INVALID)) {
2244                         log_error("Failed to parse reply: %s", error.message);
2245                         r = -EIO;
2246                         goto finish;
2247                 }
2248
2249                 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2250                         goto finish;
2251
2252                 dbus_message_unref(m);
2253                 dbus_message_unref(reply);
2254                 m = reply = NULL;
2255         }
2256
2257         r = 0;
2258
2259 finish:
2260         if (m)
2261                 dbus_message_unref(m);
2262
2263         if (reply)
2264                 dbus_message_unref(reply);
2265
2266         dbus_error_free(&error);
2267
2268         return r;
2269 }
2270
2271 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2272         DBusError error;
2273         DBusMessage *m = NULL, *reply = NULL;
2274
2275         assert(connection);
2276         assert(message);
2277
2278         dbus_error_init(&error);
2279
2280         log_debug("Got D-Bus request: %s.%s() on %s",
2281                   dbus_message_get_interface(message),
2282                   dbus_message_get_member(message),
2283                   dbus_message_get_path(message));
2284
2285         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2286                 log_error("Warning! D-Bus connection terminated.");
2287                 dbus_connection_close(connection);
2288
2289         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2290                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2291                 const char *id, *path;
2292
2293                 if (!dbus_message_get_args(message, &error,
2294                                            DBUS_TYPE_STRING, &id,
2295                                            DBUS_TYPE_OBJECT_PATH, &path,
2296                                            DBUS_TYPE_INVALID))
2297                         log_error("Failed to parse message: %s", error.message);
2298                 else if (streq(dbus_message_get_member(message), "UnitNew"))
2299                         printf("Unit %s added.\n", id);
2300                 else
2301                         printf("Unit %s removed.\n", id);
2302
2303         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2304                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2305                 uint32_t id;
2306                 const char *path;
2307
2308                 if (!dbus_message_get_args(message, &error,
2309                                            DBUS_TYPE_UINT32, &id,
2310                                            DBUS_TYPE_OBJECT_PATH, &path,
2311                                            DBUS_TYPE_INVALID))
2312                         log_error("Failed to parse message: %s", error.message);
2313                 else if (streq(dbus_message_get_member(message), "JobNew"))
2314                         printf("Job %u added.\n", id);
2315                 else
2316                         printf("Job %u removed.\n", id);
2317
2318
2319         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Unit", "Changed") ||
2320                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Job", "Changed")) {
2321
2322                 const char *path, *interface, *property = "Id";
2323                 DBusMessageIter iter, sub;
2324
2325                 path = dbus_message_get_path(message);
2326                 interface = dbus_message_get_interface(message);
2327
2328                 if (!(m = dbus_message_new_method_call(
2329                               "org.freedesktop.systemd1",
2330                               path,
2331                               "org.freedesktop.DBus.Properties",
2332                               "Get"))) {
2333                         log_error("Could not allocate message.");
2334                         goto oom;
2335                 }
2336
2337                 if (!dbus_message_append_args(m,
2338                                               DBUS_TYPE_STRING, &interface,
2339                                               DBUS_TYPE_STRING, &property,
2340                                               DBUS_TYPE_INVALID)) {
2341                         log_error("Could not append arguments to message.");
2342                         goto finish;
2343                 }
2344
2345                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2346                         log_error("Failed to issue method call: %s", error.message);
2347                         goto finish;
2348                 }
2349
2350                 if (!dbus_message_iter_init(reply, &iter) ||
2351                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2352                         log_error("Failed to parse reply.");
2353                         goto finish;
2354                 }
2355
2356                 dbus_message_iter_recurse(&iter, &sub);
2357
2358                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2359                         const char *id;
2360
2361                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2362                                 log_error("Failed to parse reply.");
2363                                 goto finish;
2364                         }
2365
2366                         dbus_message_iter_get_basic(&sub, &id);
2367                         printf("Unit %s changed.\n", id);
2368                 } else {
2369                         uint32_t id;
2370
2371                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2372                                 log_error("Failed to parse reply.");
2373                                 goto finish;
2374                         }
2375
2376                         dbus_message_iter_get_basic(&sub, &id);
2377                         printf("Job %u changed.\n", id);
2378                 }
2379         }
2380
2381 finish:
2382         if (m)
2383                 dbus_message_unref(m);
2384
2385         if (reply)
2386                 dbus_message_unref(reply);
2387
2388         dbus_error_free(&error);
2389         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2390
2391 oom:
2392         if (m)
2393                 dbus_message_unref(m);
2394
2395         if (reply)
2396                 dbus_message_unref(reply);
2397
2398         dbus_error_free(&error);
2399         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2400 }
2401
2402 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2403         DBusMessage *m = NULL, *reply = NULL;
2404         DBusError error;
2405         int r;
2406
2407         dbus_error_init(&error);
2408
2409         if (!private_bus) {
2410                 dbus_bus_add_match(bus,
2411                                    "type='signal',"
2412                                    "sender='org.freedesktop.systemd1',"
2413                                    "interface='org.freedesktop.systemd1.Manager',"
2414                                    "path='/org/freedesktop/systemd1'",
2415                                    &error);
2416
2417                 if (dbus_error_is_set(&error)) {
2418                         log_error("Failed to add match: %s", error.message);
2419                         r = -EIO;
2420                         goto finish;
2421                 }
2422
2423                 dbus_bus_add_match(bus,
2424                                    "type='signal',"
2425                                    "sender='org.freedesktop.systemd1',"
2426                                    "interface='org.freedesktop.systemd1.Unit',"
2427                                    "member='Changed'",
2428                                    &error);
2429
2430                 if (dbus_error_is_set(&error)) {
2431                         log_error("Failed to add match: %s", error.message);
2432                         r = -EIO;
2433                         goto finish;
2434                 }
2435
2436                 dbus_bus_add_match(bus,
2437                                    "type='signal',"
2438                                    "sender='org.freedesktop.systemd1',"
2439                                    "interface='org.freedesktop.systemd1.Job',"
2440                                    "member='Changed'",
2441                                    &error);
2442
2443                 if (dbus_error_is_set(&error)) {
2444                         log_error("Failed to add match: %s", error.message);
2445                         r = -EIO;
2446                         goto finish;
2447                 }
2448         }
2449
2450         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2451                 log_error("Failed to add filter.");
2452                 r = -ENOMEM;
2453                 goto finish;
2454         }
2455
2456         if (!(m = dbus_message_new_method_call(
2457                               "org.freedesktop.systemd1",
2458                               "/org/freedesktop/systemd1",
2459                               "org.freedesktop.systemd1.Manager",
2460                               "Subscribe"))) {
2461                 log_error("Could not allocate message.");
2462                 r = -ENOMEM;
2463                 goto finish;
2464         }
2465
2466         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2467                 log_error("Failed to issue method call: %s", error.message);
2468                 r = -EIO;
2469                 goto finish;
2470         }
2471
2472         while (dbus_connection_read_write_dispatch(bus, -1))
2473                 ;
2474
2475         r = 0;
2476
2477 finish:
2478
2479         /* This is slightly dirty, since we don't undo the filter or the matches. */
2480
2481         if (m)
2482                 dbus_message_unref(m);
2483
2484         if (reply)
2485                 dbus_message_unref(reply);
2486
2487         dbus_error_free(&error);
2488
2489         return r;
2490 }
2491
2492 static int dump(DBusConnection *bus, char **args, unsigned n) {
2493         DBusMessage *m = NULL, *reply = NULL;
2494         DBusError error;
2495         int r;
2496         const char *text;
2497
2498         dbus_error_init(&error);
2499
2500         if (!(m = dbus_message_new_method_call(
2501                               "org.freedesktop.systemd1",
2502                               "/org/freedesktop/systemd1",
2503                               "org.freedesktop.systemd1.Manager",
2504                               "Dump"))) {
2505                 log_error("Could not allocate message.");
2506                 return -ENOMEM;
2507         }
2508
2509         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2510                 log_error("Failed to issue method call: %s", error.message);
2511                 r = -EIO;
2512                 goto finish;
2513         }
2514
2515         if (!dbus_message_get_args(reply, &error,
2516                                    DBUS_TYPE_STRING, &text,
2517                                    DBUS_TYPE_INVALID)) {
2518                 log_error("Failed to parse reply: %s", error.message);
2519                 r = -EIO;
2520                 goto finish;
2521         }
2522
2523         fputs(text, stdout);
2524
2525         r = 0;
2526
2527 finish:
2528         if (m)
2529                 dbus_message_unref(m);
2530
2531         if (reply)
2532                 dbus_message_unref(reply);
2533
2534         dbus_error_free(&error);
2535
2536         return r;
2537 }
2538
2539 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2540         DBusMessage *m = NULL, *reply = NULL;
2541         DBusError error;
2542         int r;
2543         const char *name = "", *path, *id;
2544         dbus_bool_t cleanup = FALSE;
2545         DBusMessageIter iter, sub;
2546         const char
2547                 *interface = "org.freedesktop.systemd1.Unit",
2548                 *property = "Id";
2549
2550         dbus_error_init(&error);
2551
2552         if (!(m = dbus_message_new_method_call(
2553                               "org.freedesktop.systemd1",
2554                               "/org/freedesktop/systemd1",
2555                               "org.freedesktop.systemd1.Manager",
2556                               "CreateSnapshot"))) {
2557                 log_error("Could not allocate message.");
2558                 return -ENOMEM;
2559         }
2560
2561         if (n > 1)
2562                 name = args[1];
2563
2564         if (!dbus_message_append_args(m,
2565                                       DBUS_TYPE_STRING, &name,
2566                                       DBUS_TYPE_BOOLEAN, &cleanup,
2567                                       DBUS_TYPE_INVALID)) {
2568                 log_error("Could not append arguments to message.");
2569                 r = -ENOMEM;
2570                 goto finish;
2571         }
2572
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_get_args(reply, &error,
2580                                    DBUS_TYPE_OBJECT_PATH, &path,
2581                                    DBUS_TYPE_INVALID)) {
2582                 log_error("Failed to parse reply: %s", error.message);
2583                 r = -EIO;
2584                 goto finish;
2585         }
2586
2587         dbus_message_unref(m);
2588         if (!(m = dbus_message_new_method_call(
2589                               "org.freedesktop.systemd1",
2590                               path,
2591                               "org.freedesktop.DBus.Properties",
2592                               "Get"))) {
2593                 log_error("Could not allocate message.");
2594                 return -ENOMEM;
2595         }
2596
2597         if (!dbus_message_append_args(m,
2598                                       DBUS_TYPE_STRING, &interface,
2599                                       DBUS_TYPE_STRING, &property,
2600                                       DBUS_TYPE_INVALID)) {
2601                 log_error("Could not append arguments to message.");
2602                 r = -ENOMEM;
2603                 goto finish;
2604         }
2605
2606         dbus_message_unref(reply);
2607         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2608                 log_error("Failed to issue method call: %s", error.message);
2609                 r = -EIO;
2610                 goto finish;
2611         }
2612
2613         if (!dbus_message_iter_init(reply, &iter) ||
2614             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2615                 log_error("Failed to parse reply.");
2616                 r = -EIO;
2617                 goto finish;
2618         }
2619
2620         dbus_message_iter_recurse(&iter, &sub);
2621
2622         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2623                 log_error("Failed to parse reply.");
2624                 r = -EIO;
2625                 goto finish;
2626         }
2627
2628         dbus_message_iter_get_basic(&sub, &id);
2629
2630         if (!arg_quiet)
2631                 puts(id);
2632         r = 0;
2633
2634 finish:
2635         if (m)
2636                 dbus_message_unref(m);
2637
2638         if (reply)
2639                 dbus_message_unref(reply);
2640
2641         dbus_error_free(&error);
2642
2643         return r;
2644 }
2645
2646 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2647         DBusMessage *m = NULL, *reply = NULL;
2648         int r;
2649         DBusError error;
2650         unsigned i;
2651
2652         assert(bus);
2653         assert(args);
2654
2655         dbus_error_init(&error);
2656
2657         for (i = 1; i < n; i++) {
2658                 const char *path = NULL;
2659
2660                 if (!(m = dbus_message_new_method_call(
2661                                       "org.freedesktop.systemd1",
2662                                       "/org/freedesktop/systemd1",
2663                                       "org.freedesktop.systemd1.Manager",
2664                                       "GetUnit"))) {
2665                         log_error("Could not allocate message.");
2666                         r = -ENOMEM;
2667                         goto finish;
2668                 }
2669
2670                 if (!dbus_message_append_args(m,
2671                                               DBUS_TYPE_STRING, &args[i],
2672                                               DBUS_TYPE_INVALID)) {
2673                         log_error("Could not append arguments to message.");
2674                         r = -ENOMEM;
2675                         goto finish;
2676                 }
2677
2678                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2679                         log_error("Failed to issue method call: %s", error.message);
2680                         r = -EIO;
2681                         goto finish;
2682                 }
2683
2684                 if (!dbus_message_get_args(reply, &error,
2685                                            DBUS_TYPE_OBJECT_PATH, &path,
2686                                            DBUS_TYPE_INVALID)) {
2687                         log_error("Failed to parse reply: %s", error.message);
2688                         r = -EIO;
2689                         goto finish;
2690                 }
2691
2692                 dbus_message_unref(m);
2693                 if (!(m = dbus_message_new_method_call(
2694                                       "org.freedesktop.systemd1",
2695                                       path,
2696                                       "org.freedesktop.systemd1.Snapshot",
2697                                       "Remove"))) {
2698                         log_error("Could not allocate message.");
2699                         r = -ENOMEM;
2700                         goto finish;
2701                 }
2702
2703                 dbus_message_unref(reply);
2704                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2705                         log_error("Failed to issue method call: %s", error.message);
2706                         r = -EIO;
2707                         goto finish;
2708                 }
2709
2710                 dbus_message_unref(m);
2711                 dbus_message_unref(reply);
2712                 m = reply = NULL;
2713         }
2714
2715         r = 0;
2716
2717 finish:
2718         if (m)
2719                 dbus_message_unref(m);
2720
2721         if (reply)
2722                 dbus_message_unref(reply);
2723
2724         dbus_error_free(&error);
2725
2726         return r;
2727 }
2728
2729 static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
2730         DBusMessage *m = NULL, *reply = NULL;
2731         DBusError error;
2732         int r;
2733         const char *method;
2734
2735         dbus_error_init(&error);
2736
2737         if (arg_action == ACTION_RELOAD)
2738                 method = "Reload";
2739         else if (arg_action == ACTION_REEXEC)
2740                 method = "Reexecute";
2741         else {
2742                 assert(arg_action == ACTION_SYSTEMCTL);
2743
2744                 method =
2745                         streq(args[0], "clear-jobs")        ||
2746                         streq(args[0], "cancel")            ? "ClearJobs" :
2747                         streq(args[0], "daemon-reexec")     ? "Reexecute" :
2748                         streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2749                         streq(args[0], "daemon-exit")       ? "Exit" :
2750                                                               "Reload";
2751         }
2752
2753         if (!(m = dbus_message_new_method_call(
2754                               "org.freedesktop.systemd1",
2755                               "/org/freedesktop/systemd1",
2756                               "org.freedesktop.systemd1.Manager",
2757                               method))) {
2758                 log_error("Could not allocate message.");
2759                 return -ENOMEM;
2760         }
2761
2762         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2763
2764                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2765                         /* There's always a fallback possible for
2766                          * legacy actions. */
2767                         r = 0;
2768                         goto finish;
2769                 }
2770
2771                 log_error("Failed to issue method call: %s", error.message);
2772                 r = -EIO;
2773                 goto finish;
2774         }
2775
2776         r = 1;
2777
2778 finish:
2779         if (m)
2780                 dbus_message_unref(m);
2781
2782         if (reply)
2783                 dbus_message_unref(reply);
2784
2785         dbus_error_free(&error);
2786
2787         return r;
2788 }
2789
2790 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2791         DBusMessage *m = NULL, *reply = NULL;
2792         unsigned i;
2793         int r;
2794         DBusError error;
2795
2796         assert(bus);
2797         dbus_error_init(&error);
2798
2799         if (n <= 1)
2800                 return daemon_reload(bus, args, n);
2801
2802         for (i = 1; i < n; i++) {
2803
2804                 if (!(m = dbus_message_new_method_call(
2805                                       "org.freedesktop.systemd1",
2806                                       "/org/freedesktop/systemd1",
2807                                       "org.freedesktop.systemd1.Manager",
2808                                       "ResetMaintenanceUnit"))) {
2809                         log_error("Could not allocate message.");
2810                         r = -ENOMEM;
2811                         goto finish;
2812                 }
2813
2814                 if (!dbus_message_append_args(m,
2815                                               DBUS_TYPE_STRING, args + i,
2816                                               DBUS_TYPE_INVALID)) {
2817                         log_error("Could not append arguments to message.");
2818                         r = -ENOMEM;
2819                         goto finish;
2820                 }
2821
2822                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2823                         log_error("Failed to issue method call: %s", error.message);
2824                         r = -EIO;
2825                         goto finish;
2826                 }
2827
2828                 dbus_message_unref(m);
2829                 dbus_message_unref(reply);
2830                 m = reply = NULL;
2831         }
2832
2833         r = 0;
2834
2835 finish:
2836         if (m)
2837                 dbus_message_unref(m);
2838
2839         if (reply)
2840                 dbus_message_unref(reply);
2841
2842         dbus_error_free(&error);
2843
2844         return r;
2845 }
2846
2847 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2848         DBusMessage *m = NULL, *reply = NULL;
2849         DBusError error;
2850         DBusMessageIter iter, sub, sub2;
2851         int r;
2852         const char
2853                 *interface = "org.freedesktop.systemd1.Manager",
2854                 *property = "Environment";
2855
2856         dbus_error_init(&error);
2857
2858         if (!(m = dbus_message_new_method_call(
2859                               "org.freedesktop.systemd1",
2860                               "/org/freedesktop/systemd1",
2861                               "org.freedesktop.DBus.Properties",
2862                               "Get"))) {
2863                 log_error("Could not allocate message.");
2864                 return -ENOMEM;
2865         }
2866
2867         if (!dbus_message_append_args(m,
2868                                       DBUS_TYPE_STRING, &interface,
2869                                       DBUS_TYPE_STRING, &property,
2870                                       DBUS_TYPE_INVALID)) {
2871                 log_error("Could not append arguments to message.");
2872                 r = -ENOMEM;
2873                 goto finish;
2874         }
2875
2876         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2877                 log_error("Failed to issue method call: %s", error.message);
2878                 r = -EIO;
2879                 goto finish;
2880         }
2881
2882         if (!dbus_message_iter_init(reply, &iter) ||
2883             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2884                 log_error("Failed to parse reply.");
2885                 r = -EIO;
2886                 goto finish;
2887         }
2888
2889         dbus_message_iter_recurse(&iter, &sub);
2890
2891         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2892             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
2893                 log_error("Failed to parse reply.");
2894                 r = -EIO;
2895                 goto finish;
2896         }
2897
2898         dbus_message_iter_recurse(&sub, &sub2);
2899
2900         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2901                 const char *text;
2902
2903                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2904                         log_error("Failed to parse reply.");
2905                         r = -EIO;
2906                         goto finish;
2907                 }
2908
2909                 dbus_message_iter_get_basic(&sub2, &text);
2910                 printf("%s\n", text);
2911
2912                 dbus_message_iter_next(&sub2);
2913         }
2914
2915         r = 0;
2916
2917 finish:
2918         if (m)
2919                 dbus_message_unref(m);
2920
2921         if (reply)
2922                 dbus_message_unref(reply);
2923
2924         dbus_error_free(&error);
2925
2926         return r;
2927 }
2928
2929 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
2930         DBusMessage *m = NULL, *reply = NULL;
2931         DBusError error;
2932         int r;
2933         const char *method;
2934         DBusMessageIter iter, sub;
2935         unsigned i;
2936
2937         dbus_error_init(&error);
2938
2939         method = streq(args[0], "set-environment")
2940                 ? "SetEnvironment"
2941                 : "UnsetEnvironment";
2942
2943         if (!(m = dbus_message_new_method_call(
2944                               "org.freedesktop.systemd1",
2945                               "/org/freedesktop/systemd1",
2946                               "org.freedesktop.systemd1.Manager",
2947                               method))) {
2948
2949                 log_error("Could not allocate message.");
2950                 return -ENOMEM;
2951         }
2952
2953         dbus_message_iter_init_append(m, &iter);
2954
2955         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
2956                 log_error("Could not append arguments to message.");
2957                 r = -ENOMEM;
2958                 goto finish;
2959         }
2960
2961         for (i = 1; i < n; i++)
2962                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
2963                         log_error("Could not append arguments to message.");
2964                         r = -ENOMEM;
2965                         goto finish;
2966                 }
2967
2968         if (!dbus_message_iter_close_container(&iter, &sub)) {
2969                 log_error("Could not append arguments to message.");
2970                 r = -ENOMEM;
2971                 goto finish;
2972         }
2973
2974         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2975                 log_error("Failed to issue method call: %s", error.message);
2976                 r = -EIO;
2977                 goto finish;
2978         }
2979
2980         r = 0;
2981
2982 finish:
2983         if (m)
2984                 dbus_message_unref(m);
2985
2986         if (reply)
2987                 dbus_message_unref(reply);
2988
2989         dbus_error_free(&error);
2990
2991         return r;
2992 }
2993
2994 typedef struct {
2995         char *name;
2996         char *path;
2997
2998         char **aliases;
2999         char **wanted_by;
3000 } InstallInfo;
3001
3002 static Hashmap *will_install = NULL, *have_installed = NULL;
3003 static Set *remove_symlinks_to = NULL;
3004
3005 static void install_info_free(InstallInfo *i) {
3006         assert(i);
3007
3008         free(i->name);
3009         free(i->path);
3010         strv_free(i->aliases);
3011         strv_free(i->wanted_by);
3012         free(i);
3013 }
3014
3015 static void install_info_hashmap_free(Hashmap *m) {
3016         InstallInfo *i;
3017
3018         while ((i = hashmap_steal_first(m)))
3019                 install_info_free(i);
3020
3021         hashmap_free(m);
3022 }
3023
3024 static bool unit_name_valid(const char *name) {
3025
3026         /* This is a minimal version of unit_name_valid() from
3027          * unit-name.c */
3028
3029         if (!*name)
3030                 return false;
3031
3032         if (ignore_file(name))
3033                 return false;
3034
3035         return true;
3036 }
3037
3038 static int install_info_add(const char *name) {
3039         InstallInfo *i;
3040         int r;
3041
3042         assert(will_install);
3043
3044         if (!unit_name_valid(name))
3045                 return -EINVAL;
3046
3047         if (hashmap_get(have_installed, name) ||
3048             hashmap_get(will_install, name))
3049                 return 0;
3050
3051         if (!(i = new0(InstallInfo, 1))) {
3052                 r = -ENOMEM;
3053                 goto fail;
3054         }
3055
3056         if (!(i->name = strdup(name))) {
3057                 r = -ENOMEM;
3058                 goto fail;
3059         }
3060
3061         if ((r = hashmap_put(will_install, i->name, i)) < 0)
3062                 goto fail;
3063
3064         return 0;
3065
3066 fail:
3067         if (i)
3068                 install_info_free(i);
3069
3070         return r;
3071 }
3072
3073 static int config_parse_also(
3074                 const char *filename,
3075                 unsigned line,
3076                 const char *section,
3077                 const char *lvalue,
3078                 const char *rvalue,
3079                 void *data,
3080                 void *userdata) {
3081
3082         char *w;
3083         size_t l;
3084         char *state;
3085
3086         assert(filename);
3087         assert(lvalue);
3088         assert(rvalue);
3089
3090         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3091                 char *n;
3092                 int r;
3093
3094                 if (!(n = strndup(w, l)))
3095                         return -ENOMEM;
3096
3097                 r = install_info_add(n);
3098                 free(n);
3099
3100                 if (r < 0)
3101                         return r;
3102         }
3103
3104         return 0;
3105 }
3106
3107 static int mark_symlink_for_removal(const char *p) {
3108         char *n;
3109         int r;
3110
3111         assert(p);
3112         assert(path_is_absolute(p));
3113
3114         if (!remove_symlinks_to)
3115                 return 0;
3116
3117         if (!(n = strdup(p)))
3118                 return -ENOMEM;
3119
3120         path_kill_slashes(n);
3121
3122         if ((r = set_put(remove_symlinks_to, n)) < 0) {
3123                 free(n);
3124                 return r == -EEXIST ? 0 : r;
3125         }
3126
3127         return 0;
3128 }
3129
3130 static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3131         int r = 0;
3132         DIR *d;
3133         struct dirent *de;
3134
3135         assert(fd >= 0);
3136         assert(root);
3137         assert(deleted);
3138
3139         if (!(d = fdopendir(fd))) {
3140                 close_nointr_nofail(fd);
3141                 return -errno;
3142         }
3143
3144         rewinddir(d);
3145
3146         while ((de = readdir(d))) {
3147                 bool is_dir = false, is_link = false;
3148
3149                 if (ignore_file(de->d_name))
3150                         continue;
3151
3152                 if (de->d_type == DT_LNK)
3153                         is_link = true;
3154                 else if (de->d_type == DT_DIR)
3155                         is_dir = true;
3156                 else if (de->d_type == DT_UNKNOWN) {
3157                         struct stat st;
3158
3159                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3160                                 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3161
3162                                 if (r == 0)
3163                                         r = -errno;
3164                                 continue;
3165                         }
3166
3167                         is_link = S_ISLNK(st.st_mode);
3168                         is_dir = S_ISDIR(st.st_mode);
3169                 } else
3170                         continue;
3171
3172                 if (is_dir) {
3173                         int nfd, q;
3174                         char *p;
3175
3176                         if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3177                                 log_error("Failed to open %s/%s: %m", root, de->d_name);
3178
3179                                 if (r == 0)
3180                                         r = -errno;
3181                                 continue;
3182                         }
3183
3184                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3185                                 log_error("Failed to allocate directory string.");
3186                                 close_nointr_nofail(nfd);
3187                                 r = -ENOMEM;
3188                                 break;
3189                         }
3190
3191                         /* This will close nfd, regardless whether it succeeds or not */
3192                         q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3193                         free(p);
3194
3195                         if (r == 0)
3196                                 r = q;
3197
3198                 } else if (is_link) {
3199                         char *p, *dest, *c;
3200                         int q;
3201
3202                         if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3203                                 log_error("Failed to allocate symlink string.");
3204                                 r = -ENOMEM;
3205                                 break;
3206                         }
3207
3208                         if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3209                                 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3210                                 free(p);
3211
3212                                 if (r == 0)
3213                                         r = q;
3214                                 continue;
3215                         }
3216
3217                         if ((c = canonicalize_file_name(dest))) {
3218                                 /* This might fail if the destination
3219                                  * is already removed */
3220
3221                                 free(dest);
3222                                 dest = c;
3223                         }
3224
3225                         path_kill_slashes(dest);
3226                         if (set_get(remove_symlinks_to, dest)) {
3227
3228                                 if (!arg_quiet)
3229                                         log_info("rm '%s'", p);
3230
3231                                 if (unlink(p) < 0) {
3232                                         log_error("Cannot unlink symlink %s: %m", p);
3233
3234                                         if (r == 0)
3235                                                 r = -errno;
3236                                 } else {
3237                                         rmdir_parents(p, config_path);
3238                                         path_kill_slashes(p);
3239
3240                                         if (!set_get(remove_symlinks_to, p)) {
3241
3242                                                 if ((r = mark_symlink_for_removal(p)) < 0) {
3243                                                         if (r == 0)
3244                                                                 r = q;
3245                                                 } else
3246                                                         *deleted = true;
3247                                         }
3248                                 }
3249                         }
3250
3251                         free(p);
3252                         free(dest);
3253                 }
3254         }
3255
3256         closedir(d);
3257
3258         return r;
3259 }
3260
3261 static int remove_marked_symlinks(const char *config_path) {
3262         int fd, r = 0;
3263         bool deleted;
3264
3265         assert(config_path);
3266
3267         if (set_size(remove_symlinks_to) <= 0)
3268                 return 0;
3269
3270         if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3271                 return -errno;
3272
3273         do {
3274                 int q, cfd;
3275                 deleted = false;
3276
3277                 if ((cfd = dup(fd)) < 0) {
3278                         r = -errno;
3279                         break;
3280                 }
3281
3282                 /* This takes possession of cfd and closes it */
3283                 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3284                         if (r == 0)
3285                                 r = q;
3286                 }
3287         } while (deleted);
3288
3289         close_nointr_nofail(fd);
3290
3291         return r;
3292 }
3293
3294 static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3295         int r;
3296
3297         assert(old_path);
3298         assert(new_path);
3299         assert(verb);
3300
3301         if (streq(verb, "enable")) {
3302                 char *dest;
3303
3304                 mkdir_parents(new_path, 0755);
3305
3306                 if (symlink(old_path, new_path) >= 0) {
3307
3308                         if (!arg_quiet)
3309                                 log_info("ln -s '%s' '%s'", old_path, new_path);
3310
3311                         return 0;
3312                 }
3313
3314                 if (errno != EEXIST) {
3315                         log_error("Cannot link %s to %s: %m", old_path, new_path);
3316                         return -errno;
3317                 }
3318
3319                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3320
3321                         if (errno == EINVAL) {
3322                                 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3323                                 return -EEXIST;
3324                         }
3325
3326                         log_error("readlink() failed: %s", strerror(-r));
3327                         return r;
3328                 }
3329
3330                 if (streq(dest, old_path)) {
3331                         free(dest);
3332                         return 0;
3333                 }
3334
3335                 if (!arg_force) {
3336                         log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3337                         free(dest);
3338                         return -EEXIST;
3339                 }
3340
3341                 free(dest);
3342                 unlink(new_path);
3343
3344                 if (!arg_quiet)
3345                         log_info("ln -s '%s' '%s'", old_path, new_path);
3346
3347                 if (symlink(old_path, new_path) >= 0)
3348                         return 0;
3349
3350                 log_error("Cannot link %s to %s: %m", old_path, new_path);
3351                 return -errno;
3352
3353         } else if (streq(verb, "disable")) {
3354                 char *dest;
3355
3356                 if ((r = mark_symlink_for_removal(old_path)) < 0)
3357                         return r;
3358
3359                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3360                         if (errno == ENOENT)
3361                                 return 0;
3362
3363                         if (errno == EINVAL) {
3364                                 log_warning("File %s not a symlink, ignoring.", old_path);
3365                                 return 0;
3366                         }
3367
3368                         log_error("readlink() failed: %s", strerror(-r));
3369                         return r;
3370                 }
3371
3372                 if (!streq(dest, old_path)) {
3373                         log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3374                         free(dest);
3375                         return 0;
3376                 }
3377
3378                 free(dest);
3379
3380                 if ((r = mark_symlink_for_removal(new_path)) < 0)
3381                         return r;
3382
3383                 if (!arg_quiet)
3384                         log_info("rm '%s'", new_path);
3385
3386                 if (unlink(new_path) >= 0)
3387                         return 0;
3388
3389                 log_error("Cannot unlink %s: %m", new_path);
3390                 return -errno;
3391
3392         } else if (streq(verb, "is-enabled")) {
3393                 char *dest;
3394
3395                 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3396
3397                         if (errno == ENOENT || errno == EINVAL)
3398                                 return 0;
3399
3400                         log_error("readlink() failed: %s", strerror(-r));
3401                         return r;
3402                 }
3403
3404                 if (streq(dest, old_path)) {
3405                         free(dest);
3406                         return 1;
3407                 }
3408
3409                 return 0;
3410         }
3411
3412         assert_not_reached("Unknown action.");
3413 }
3414
3415 static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3416         char **s;
3417         char *alias_path = NULL;
3418         int r;
3419
3420         assert(verb);
3421         assert(i);
3422         assert(config_path);
3423
3424         STRV_FOREACH(s, i->aliases) {
3425
3426                 if (!unit_name_valid(*s)) {
3427                         log_error("Invalid name %s.", *s);
3428                         r = -EINVAL;
3429                         goto finish;
3430                 }
3431
3432                 free(alias_path);
3433                 if (!(alias_path = path_make_absolute(*s, config_path))) {
3434                         log_error("Out of memory");
3435                         r = -ENOMEM;
3436                         goto finish;
3437                 }
3438
3439                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3440                         goto finish;
3441
3442                 if (streq(verb, "disable"))
3443                         rmdir_parents(alias_path, config_path);
3444         }
3445
3446         r = 0;
3447
3448 finish:
3449         free(alias_path);
3450
3451         return r;
3452 }
3453
3454 static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
3455         char **s;
3456         char *alias_path = NULL;
3457         int r;
3458
3459         assert(verb);
3460         assert(i);
3461         assert(config_path);
3462
3463         STRV_FOREACH(s, i->wanted_by) {
3464                 if (!unit_name_valid(*s)) {
3465                         log_error("Invalid name %s.", *s);
3466                         r = -EINVAL;
3467                         goto finish;
3468                 }
3469
3470                 free(alias_path);
3471                 alias_path = NULL;
3472
3473                 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
3474                         log_error("Out of memory");
3475                         r = -ENOMEM;
3476                         goto finish;
3477                 }
3478
3479                 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3480                         goto finish;
3481
3482                 if (streq(verb, "disable"))
3483                         rmdir_parents(alias_path, config_path);
3484         }
3485
3486         r = 0;
3487
3488 finish:
3489         free(alias_path);
3490
3491         return r;
3492 }
3493
3494 static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
3495
3496         const ConfigItem items[] = {
3497                 { "Alias",    config_parse_strv, &i->aliases,   "Install" },
3498                 { "WantedBy", config_parse_strv, &i->wanted_by, "Install" },
3499                 { "Also",     config_parse_also, NULL,          "Install" },
3500
3501                 { NULL, NULL, NULL, NULL }
3502         };
3503
3504         char **p;
3505         char *filename = NULL;
3506         FILE *f = NULL;
3507         int r;
3508
3509         assert(paths);
3510         assert(i);
3511
3512         STRV_FOREACH(p, paths->unit_path) {
3513                 int fd;
3514
3515                 if (!(filename = path_make_absolute(i->name, *p))) {
3516                         log_error("Out of memory");
3517                         return -ENOMEM;
3518                 }
3519
3520                 /* Ensure that we don't follow symlinks */
3521                 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
3522                         if ((f = fdopen(fd, "re")))
3523                                 break;
3524
3525                 if (errno == ELOOP) {
3526                         log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
3527                         free(filename);
3528                         return -errno;
3529                 }
3530
3531                 if (errno != ENOENT) {
3532                         log_error("Failed to open %s: %m", filename);
3533                         free(filename);
3534                         return -errno;
3535                 }
3536
3537                 free(filename);
3538                 filename = NULL;
3539         }
3540
3541         if (!f) {
3542                 log_error("Couldn't find %s.", i->name);
3543                 return -ENOENT;
3544         }
3545
3546         i->path = filename;
3547
3548         if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
3549                 fclose(f);
3550                 return r;
3551         }
3552
3553         fclose(f);
3554
3555         if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
3556                 return r;
3557
3558         if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
3559                 return r;
3560
3561         if ((r = mark_symlink_for_removal(filename)) < 0)
3562                 return r;
3563
3564         if ((r = remove_marked_symlinks(config_path)) < 0)
3565                 return r;
3566
3567         return 0;
3568 }
3569
3570 static char *get_config_path(void) {
3571
3572         if (arg_session && arg_global)
3573                 return strdup(SESSION_CONFIG_UNIT_PATH);
3574
3575         if (arg_session) {
3576                 char *p;
3577
3578                 if (session_config_home(&p) < 0)
3579                         return NULL;
3580
3581                 return p;
3582         }
3583
3584         return strdup(SYSTEM_CONFIG_UNIT_PATH);
3585 }
3586
3587 static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
3588         DBusError error;
3589         int r;
3590         LookupPaths paths;
3591         char *config_path = NULL;
3592         unsigned j;
3593         InstallInfo *i;
3594         const char *verb = args[0];
3595
3596         dbus_error_init(&error);
3597
3598         zero(paths);
3599         if ((r = lookup_paths_init(&paths, arg_session ? MANAGER_SESSION : MANAGER_SYSTEM)) < 0) {
3600                 log_error("Failed to determine lookup paths: %s", strerror(-r));
3601                 goto finish;
3602         }
3603
3604         if (!(config_path = get_config_path())) {
3605                 log_error("Failed to determine config path");
3606                 r = -ENOMEM;
3607                 goto finish;
3608         }
3609
3610         will_install = hashmap_new(string_hash_func, string_compare_func);
3611         have_installed = hashmap_new(string_hash_func, string_compare_func);
3612
3613         if (!will_install || !have_installed) {
3614                 log_error("Failed to allocate unit sets.");
3615                 r = -ENOMEM;
3616                 goto finish;
3617         }
3618
3619         if (!arg_defaults && streq(verb, "disable"))
3620                 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
3621                         log_error("Failed to allocate symlink sets.");
3622                         r = -ENOMEM;
3623                         goto finish;
3624                 }
3625
3626         for (j = 1; j < n; j++)
3627                 if ((r = install_info_add(args[j])) < 0)
3628                         goto finish;
3629
3630         while ((i = hashmap_first(will_install))) {
3631                 int q;
3632
3633                 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
3634
3635                 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
3636
3637                         if (q < 0) {
3638                                 if (r == 0)
3639                                         r = q;
3640                                 goto finish;
3641                         }
3642
3643                         /* In test mode and found something */
3644                         r = 1;
3645                         break;
3646                 }
3647         }
3648
3649         if (streq(verb, "is-enabled"))
3650                 r = r > 0 ? 0 : -ENOENT;
3651         else if (bus &&
3652                  /* Don't try to reload anything if the user asked us to not do this */
3653                  !arg_no_reload &&
3654                  /* Don't try to reload anything when updating a unit globally */
3655                  !arg_global &&
3656                  /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
3657                  (arg_session || sd_booted() > 0) &&
3658                  /* Don't try to reload anything if we are running in a chroot environment */
3659                  (arg_session || running_in_chroot() <= 0) ) {
3660                 int q;
3661
3662                 if ((q = daemon_reload(bus, args, n)) < 0)
3663                         r = q;
3664         }
3665
3666 finish:
3667         install_info_hashmap_free(will_install);
3668         install_info_hashmap_free(have_installed);
3669
3670         set_free_free(remove_symlinks_to);
3671
3672         lookup_paths_free(&paths);
3673
3674         free(config_path);
3675
3676         return r;
3677 }
3678
3679 static int systemctl_help(void) {
3680
3681         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3682                "Send control commands to or query the systemd manager.\n\n"
3683                "  -h --help          Show this help\n"
3684                "  -t --type=TYPE     List only units of a particular type\n"
3685                "  -p --property=NAME Show only properties by this name\n"
3686                "  -a --all           Show all units/properties, including dead/empty ones\n"
3687                "     --full          Don't ellipsize unit names on output\n"
3688                "     --fail          When queueing a new job, fail if conflicting jobs are\n"
3689                "                     pending\n"
3690                "  -q --quiet         Suppress output\n"
3691                "     --no-block      Do not wait until operation finished\n"
3692                "     --system        Connect to system bus\n"
3693                "     --session       Connect to session bus\n"
3694                "     --order         When generating graph for dot, show only order\n"
3695                "     --require       When generating graph for dot, show only requirement\n"
3696                "     --no-wall       Don't send wall message before halt/power-off/reboot\n"
3697                "     --global        Enable/disable unit files globally\n"
3698                "     --no-reload     When enabling/disabling unit files, don't reload daemon\n"
3699                "                     configuration\n"
3700                "     --force         When enabling unit files, override existing symlinks\n"
3701                "     --defaults      When disabling unit files, remove default symlinks only\n\n"
3702                "Commands:\n"
3703                "  list-units                      List units\n"
3704                "  start [NAME...]                 Start (activate) one or more units\n"
3705                "  stop [NAME...]                  Stop (deactivate) one or more units\n"
3706                "  reload [NAME...]                Reload one or more units\n"
3707                "  restart [NAME...]               Start or restart one or more units\n"
3708                "  try-restart [NAME...]           Restart one or more units if active\n"
3709                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
3710                "                                  otherwise start or restart\n"
3711                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3712                "                                  otherwise restart if active\n"
3713                "  isolate [NAME]                  Start one unit and stop all others\n"
3714                "  is-active [NAME...]             Check whether units are active\n"
3715                "  status [NAME...|PID...]         Show runtime status of one or more units\n"
3716                "  show [NAME...|JOB...]           Show properties of one or more\n"
3717                "                                  units/jobs or the manager\n"
3718                "  reset-maintenance [NAME...]     Reset maintenance state for all, one,\n"
3719                "                                  or more units\n"
3720                "  enable [NAME...]                Enable one or more unit files\n"
3721                "  disable [NAME...]               Disable one or more unit files\n"
3722                "  is-enabled [NAME...]            Check whether unit files are enabled\n"
3723                "  load [NAME...]                  Load one or more units\n"
3724                "  list-jobs                       List jobs\n"
3725                "  cancel [JOB...]                 Cancel all, one, or more jobs\n"
3726                "  monitor                         Monitor unit/job changes\n"
3727                "  dump                            Dump server status\n"
3728                "  dot                             Dump dependency graph for dot(1)\n"
3729                "  snapshot [NAME]                 Create a snapshot\n"
3730                "  delete [NAME...]                Remove one or more snapshots\n"
3731                "  daemon-reload                   Reload systemd manager configuration\n"
3732                "  daemon-reexec                   Reexecute systemd manager\n"
3733                "  daemon-exit                     Ask the systemd manager to quit\n"
3734                "  show-environment                Dump environment\n"
3735                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
3736                "  unset-environment [NAME...]     Unset one or more environment variables\n"
3737                "  halt                            Shut down and halt the system\n"
3738                "  poweroff                        Shut down and power-off the system\n"
3739                "  reboot                          Shut down and reboot the system\n"
3740                "  rescue                          Enter system rescue mode\n"
3741                "  emergency                       Enter system emergency mode\n"
3742                "  default                         Enter system default mode\n",
3743                program_invocation_short_name);
3744
3745         return 0;
3746 }
3747
3748 static int halt_help(void) {
3749
3750         printf("%s [OPTIONS...]\n\n"
3751                "%s the system.\n\n"
3752                "     --help      Show this help\n"
3753                "     --halt      Halt the machine\n"
3754                "  -p --poweroff  Switch off the machine\n"
3755                "     --reboot    Reboot the machine\n"
3756                "  -f --force     Force immediate halt/power-off/reboot\n"
3757                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3758                "  -d --no-wtmp   Don't write wtmp record\n"
3759                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
3760                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
3761                program_invocation_short_name,
3762                arg_action == ACTION_REBOOT   ? "Reboot" :
3763                arg_action == ACTION_POWEROFF ? "Power off" :
3764                                                "Halt");
3765
3766         return 0;
3767 }
3768
3769 static int shutdown_help(void) {
3770
3771         printf("%s [OPTIONS...] [now] [WALL...]\n\n"
3772                "Shut down the system.\n\n"
3773                "     --help      Show this help\n"
3774                "  -H --halt      Halt the machine\n"
3775                "  -P --poweroff  Power-off the machine\n"
3776                "  -r --reboot    Reboot the machine\n"
3777                "  -h             Equivalent to --poweroff, overriden by --halt\n"
3778                "  -k             Don't halt/power-off/reboot, just send warnings\n"
3779                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
3780                program_invocation_short_name);
3781
3782         return 0;
3783 }
3784
3785 static int telinit_help(void) {
3786
3787         printf("%s [OPTIONS...] {COMMAND}\n\n"
3788                "Send control commands to the init daemon.\n\n"
3789                "     --help      Show this help\n"
3790                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
3791                "Commands:\n"
3792                "  0              Power-off the machine\n"
3793                "  6              Reboot the machine\n"
3794                "  2, 3, 4, 5     Start runlevelX.target unit\n"
3795                "  1, s, S        Enter rescue mode\n"
3796                "  q, Q           Reload init daemon configuration\n"
3797                "  u, U           Reexecute init daemon\n",
3798                program_invocation_short_name);
3799
3800         return 0;
3801 }
3802
3803 static int runlevel_help(void) {
3804
3805         printf("%s [OPTIONS...]\n\n"
3806                "Prints the previous and current runlevel of the init system.\n\n"
3807                "     --help      Show this help\n",
3808                program_invocation_short_name);
3809
3810         return 0;
3811 }
3812
3813 static int systemctl_parse_argv(int argc, char *argv[]) {
3814
3815         enum {
3816                 ARG_FAIL = 0x100,
3817                 ARG_SESSION,
3818                 ARG_SYSTEM,
3819                 ARG_GLOBAL,
3820                 ARG_NO_BLOCK,
3821                 ARG_NO_WALL,
3822                 ARG_ORDER,
3823                 ARG_REQUIRE,
3824                 ARG_FULL,
3825                 ARG_FORCE,
3826                 ARG_NO_RELOAD,
3827                 ARG_DEFAULTS
3828         };
3829
3830         static const struct option options[] = {
3831                 { "help",      no_argument,       NULL, 'h'           },
3832                 { "type",      required_argument, NULL, 't'           },
3833                 { "property",  required_argument, NULL, 'p'           },
3834                 { "all",       no_argument,       NULL, 'a'           },
3835                 { "full",      no_argument,       NULL, ARG_FULL      },
3836                 { "fail",      no_argument,       NULL, ARG_FAIL      },
3837                 { "session",   no_argument,       NULL, ARG_SESSION   },
3838                 { "system",    no_argument,       NULL, ARG_SYSTEM    },
3839                 { "global",    no_argument,       NULL, ARG_GLOBAL    },
3840                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
3841                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL   },
3842                 { "quiet",     no_argument,       NULL, 'q'           },
3843                 { "order",     no_argument,       NULL, ARG_ORDER     },
3844                 { "require",   no_argument,       NULL, ARG_REQUIRE   },
3845                 { "force",     no_argument,       NULL, ARG_FORCE     },
3846                 { "no-reload", no_argument,       NULL, ARG_NO_RELOAD },
3847                 { "defaults",   no_argument,      NULL, ARG_DEFAULTS  },
3848                 { NULL,        0,                 NULL, 0             }
3849         };
3850
3851         int c;
3852
3853         assert(argc >= 0);
3854         assert(argv);
3855
3856         while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3857
3858                 switch (c) {
3859
3860                 case 'h':
3861                         systemctl_help();
3862                         return 0;
3863
3864                 case 't':
3865                         arg_type = optarg;
3866                         break;
3867
3868                 case 'p': {
3869                         char **l;
3870
3871                         if (!(l = strv_append(arg_property, optarg)))
3872                                 return -ENOMEM;
3873
3874                         strv_free(arg_property);
3875                         arg_property = l;
3876
3877                         /* If the user asked for a particular
3878                          * property, show it to him, even if it is
3879                          * empty. */
3880                         arg_all = true;
3881                         break;
3882                 }
3883
3884                 case 'a':
3885                         arg_all = true;
3886                         break;
3887
3888                 case ARG_FAIL:
3889                         arg_fail = true;
3890                         break;
3891
3892                 case ARG_SESSION:
3893                         arg_session = true;
3894                         break;
3895
3896                 case ARG_SYSTEM:
3897                         arg_session = false;
3898                         break;
3899
3900                 case ARG_NO_BLOCK:
3901                         arg_no_block = true;
3902                         break;
3903
3904                 case ARG_NO_WALL:
3905                         arg_no_wall = true;
3906                         break;
3907
3908                 case ARG_ORDER:
3909                         arg_dot = DOT_ORDER;
3910                         break;
3911
3912                 case ARG_REQUIRE:
3913                         arg_dot = DOT_REQUIRE;
3914                         break;
3915
3916                 case ARG_FULL:
3917                         arg_full = true;
3918                         break;
3919
3920                 case 'q':
3921                         arg_quiet = true;
3922                         break;
3923
3924                 case ARG_FORCE:
3925                         arg_force = true;
3926                         break;
3927
3928                 case ARG_NO_RELOAD:
3929                         arg_no_reload = true;
3930                         break;
3931
3932                 case ARG_GLOBAL:
3933                         arg_global = true;
3934                         arg_session = true;
3935                         break;
3936
3937                 case ARG_DEFAULTS:
3938                         arg_defaults = true;
3939                         break;
3940
3941                 case '?':
3942                         return -EINVAL;
3943
3944                 default:
3945                         log_error("Unknown option code %c", c);
3946                         return -EINVAL;
3947                 }
3948         }
3949
3950         return 1;
3951 }
3952
3953 static int halt_parse_argv(int argc, char *argv[]) {
3954
3955         enum {
3956                 ARG_HELP = 0x100,
3957                 ARG_HALT,
3958                 ARG_REBOOT,
3959                 ARG_NO_WALL
3960         };
3961
3962         static const struct option options[] = {
3963                 { "help",      no_argument,       NULL, ARG_HELP    },
3964                 { "halt",      no_argument,       NULL, ARG_HALT    },
3965                 { "poweroff",  no_argument,       NULL, 'p'         },
3966                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
3967                 { "force",     no_argument,       NULL, 'f'         },
3968                 { "wtmp-only", no_argument,       NULL, 'w'         },
3969                 { "no-wtmp",   no_argument,       NULL, 'd'         },
3970                 { "no-sync",   no_argument,       NULL, 'n'         },
3971                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
3972                 { NULL,        0,                 NULL, 0           }
3973         };
3974
3975         int c, runlevel;
3976
3977         assert(argc >= 0);
3978         assert(argv);
3979
3980         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
3981                 if (runlevel == '0' || runlevel == '6')
3982                         arg_immediate = true;
3983
3984         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
3985                 switch (c) {
3986
3987                 case ARG_HELP:
3988                         halt_help();
3989                         return 0;
3990
3991                 case ARG_HALT:
3992                         arg_action = ACTION_HALT;
3993                         break;
3994
3995                 case 'p':
3996                         if (arg_action != ACTION_REBOOT)
3997                                 arg_action = ACTION_POWEROFF;
3998                         break;
3999
4000                 case ARG_REBOOT:
4001                         arg_action = ACTION_REBOOT;
4002                         break;
4003
4004                 case 'f':
4005                         arg_immediate = true;
4006                         break;
4007
4008                 case 'w':
4009                         arg_dry = true;
4010                         break;
4011
4012                 case 'd':
4013                         arg_no_wtmp = true;
4014                         break;
4015
4016                 case 'n':
4017                         arg_no_sync = true;
4018                         break;
4019
4020                 case ARG_NO_WALL:
4021                         arg_no_wall = true;
4022                         break;
4023
4024                 case 'i':
4025                 case 'h':
4026                         /* Compatibility nops */
4027                         break;
4028
4029                 case '?':
4030                         return -EINVAL;
4031
4032                 default:
4033                         log_error("Unknown option code %c", c);
4034                         return -EINVAL;
4035                 }
4036         }
4037
4038         if (optind < argc) {
4039                 log_error("Too many arguments.");
4040                 return -EINVAL;
4041         }
4042
4043         return 1;
4044 }
4045
4046 static int shutdown_parse_argv(int argc, char *argv[]) {
4047
4048         enum {
4049                 ARG_HELP = 0x100,
4050                 ARG_NO_WALL
4051         };
4052
4053         static const struct option options[] = {
4054                 { "help",      no_argument,       NULL, ARG_HELP    },
4055                 { "halt",      no_argument,       NULL, 'H'         },
4056                 { "poweroff",  no_argument,       NULL, 'P'         },
4057                 { "reboot",    no_argument,       NULL, 'r'         },
4058                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4059                 { NULL,        0,                 NULL, 0           }
4060         };
4061
4062         int c;
4063
4064         assert(argc >= 0);
4065         assert(argv);
4066
4067         while ((c = getopt_long(argc, argv, "HPrhkt:a", options, NULL)) >= 0) {
4068                 switch (c) {
4069
4070                 case ARG_HELP:
4071                         shutdown_help();
4072                         return 0;
4073
4074                 case 'H':
4075                         arg_action = ACTION_HALT;
4076                         break;
4077
4078                 case 'P':
4079                         arg_action = ACTION_POWEROFF;
4080                         break;
4081
4082                 case 'r':
4083                         arg_action = ACTION_REBOOT;
4084                         break;
4085
4086                 case 'h':
4087                         if (arg_action != ACTION_HALT)
4088                                 arg_action = ACTION_POWEROFF;
4089                         break;
4090
4091                 case 'k':
4092                         arg_dry = true;
4093                         break;
4094
4095                 case ARG_NO_WALL:
4096                         arg_no_wall = true;
4097                         break;
4098
4099                 case 't':
4100                 case 'a':
4101                         /* Compatibility nops */
4102                         break;
4103
4104                 case '?':
4105                         return -EINVAL;
4106
4107                 default:
4108                         log_error("Unknown option code %c", c);
4109                         return -EINVAL;
4110                 }
4111         }
4112
4113         if (argc > optind && !streq(argv[optind], "now"))
4114                 log_warning("First argument '%s' isn't 'now'. Ignoring.", argv[optind]);
4115
4116         /* We ignore the time argument */
4117         if (argc > optind + 1)
4118                 arg_wall = argv + optind + 1;
4119
4120         optind = argc;
4121
4122         return 1;
4123 }
4124
4125 static int telinit_parse_argv(int argc, char *argv[]) {
4126
4127         enum {
4128                 ARG_HELP = 0x100,
4129                 ARG_NO_WALL
4130         };
4131
4132         static const struct option options[] = {
4133                 { "help",      no_argument,       NULL, ARG_HELP    },
4134                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4135                 { NULL,        0,                 NULL, 0           }
4136         };
4137
4138         static const struct {
4139                 char from;
4140                 enum action to;
4141         } table[] = {
4142                 { '0', ACTION_POWEROFF },
4143                 { '6', ACTION_REBOOT },
4144                 { '1', ACTION_RESCUE },
4145                 { '2', ACTION_RUNLEVEL2 },
4146                 { '3', ACTION_RUNLEVEL3 },
4147                 { '4', ACTION_RUNLEVEL4 },
4148                 { '5', ACTION_RUNLEVEL5 },
4149                 { 's', ACTION_RESCUE },
4150                 { 'S', ACTION_RESCUE },
4151                 { 'q', ACTION_RELOAD },
4152                 { 'Q', ACTION_RELOAD },
4153                 { 'u', ACTION_REEXEC },
4154                 { 'U', ACTION_REEXEC }
4155         };
4156
4157         unsigned i;
4158         int c;
4159
4160         assert(argc >= 0);
4161         assert(argv);
4162
4163         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4164                 switch (c) {
4165
4166                 case ARG_HELP:
4167                         telinit_help();
4168                         return 0;
4169
4170                 case ARG_NO_WALL:
4171                         arg_no_wall = true;
4172                         break;
4173
4174                 case '?':
4175                         return -EINVAL;
4176
4177                 default:
4178                         log_error("Unknown option code %c", c);
4179                         return -EINVAL;
4180                 }
4181         }
4182
4183         if (optind >= argc) {
4184                 telinit_help();
4185                 return -EINVAL;
4186         }
4187
4188         if (optind + 1 < argc) {
4189                 log_error("Too many arguments.");
4190                 return -EINVAL;
4191         }
4192
4193         if (strlen(argv[optind]) != 1) {
4194                 log_error("Expected single character argument.");
4195                 return -EINVAL;
4196         }
4197
4198         for (i = 0; i < ELEMENTSOF(table); i++)
4199                 if (table[i].from == argv[optind][0])
4200                         break;
4201
4202         if (i >= ELEMENTSOF(table)) {
4203                 log_error("Unknown command %s.", argv[optind]);
4204                 return -EINVAL;
4205         }
4206
4207         arg_action = table[i].to;
4208
4209         optind ++;
4210
4211         return 1;
4212 }
4213
4214 static int runlevel_parse_argv(int argc, char *argv[]) {
4215
4216         enum {
4217                 ARG_HELP = 0x100,
4218         };
4219
4220         static const struct option options[] = {
4221                 { "help",      no_argument,       NULL, ARG_HELP    },
4222                 { NULL,        0,                 NULL, 0           }
4223         };
4224
4225         int c;
4226
4227         assert(argc >= 0);
4228         assert(argv);
4229
4230         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4231                 switch (c) {
4232
4233                 case ARG_HELP:
4234                         runlevel_help();
4235                         return 0;
4236
4237                 case '?':
4238                         return -EINVAL;
4239
4240                 default:
4241                         log_error("Unknown option code %c", c);
4242                         return -EINVAL;
4243                 }
4244         }
4245
4246         if (optind < argc) {
4247                 log_error("Too many arguments.");
4248                 return -EINVAL;
4249         }
4250
4251         return 1;
4252 }
4253
4254 static int parse_argv(int argc, char *argv[]) {
4255         assert(argc >= 0);
4256         assert(argv);
4257
4258         if (program_invocation_short_name) {
4259
4260                 if (strstr(program_invocation_short_name, "halt")) {
4261                         arg_action = ACTION_HALT;
4262                         return halt_parse_argv(argc, argv);
4263                 } else if (strstr(program_invocation_short_name, "poweroff")) {
4264                         arg_action = ACTION_POWEROFF;
4265                         return halt_parse_argv(argc, argv);
4266                 } else if (strstr(program_invocation_short_name, "reboot")) {
4267                         arg_action = ACTION_REBOOT;
4268                         return halt_parse_argv(argc, argv);
4269                 } else if (strstr(program_invocation_short_name, "shutdown")) {
4270                         arg_action = ACTION_POWEROFF;
4271                         return shutdown_parse_argv(argc, argv);
4272                 } else if (strstr(program_invocation_short_name, "init")) {
4273
4274                         if (sd_booted() > 0) {
4275                                 arg_action = ACTION_INVALID;
4276                                 return telinit_parse_argv(argc, argv);
4277                         } else {
4278                                 /* Hmm, so some other init system is
4279                                  * running, we need to forward this
4280                                  * request to it. For now we simply
4281                                  * guess that it is Upstart. */
4282
4283                                 execv("/lib/upstart/telinit", argv);
4284
4285                                 log_error("Couldn't find an alternative telinit implementation to spawn.");
4286                                 return -EIO;
4287                         }
4288
4289                 } else if (strstr(program_invocation_short_name, "runlevel")) {
4290                         arg_action = ACTION_RUNLEVEL;
4291                         return runlevel_parse_argv(argc, argv);
4292                 }
4293         }
4294
4295         arg_action = ACTION_SYSTEMCTL;
4296         return systemctl_parse_argv(argc, argv);
4297 }
4298
4299 static int action_to_runlevel(void) {
4300
4301         static const char table[_ACTION_MAX] = {
4302                 [ACTION_HALT] =      '0',
4303                 [ACTION_POWEROFF] =  '0',
4304                 [ACTION_REBOOT] =    '6',
4305                 [ACTION_RUNLEVEL2] = '2',
4306                 [ACTION_RUNLEVEL3] = '3',
4307                 [ACTION_RUNLEVEL4] = '4',
4308                 [ACTION_RUNLEVEL5] = '5',
4309                 [ACTION_RESCUE] =    '1'
4310         };
4311
4312         assert(arg_action < _ACTION_MAX);
4313
4314         return table[arg_action];
4315 }
4316
4317 static int talk_upstart(void) {
4318         DBusMessage *m = NULL, *reply = NULL;
4319         DBusError error;
4320         int previous, rl, r;
4321         char
4322                 env1_buf[] = "RUNLEVEL=X",
4323                 env2_buf[] = "PREVLEVEL=X";
4324         char *env1 = env1_buf, *env2 = env2_buf;
4325         const char *emit = "runlevel";
4326         dbus_bool_t b_false = FALSE;
4327         DBusMessageIter iter, sub;
4328         DBusConnection *bus;
4329
4330         dbus_error_init(&error);
4331
4332         if (!(rl = action_to_runlevel()))
4333                 return 0;
4334
4335         if (utmp_get_runlevel(&previous, NULL) < 0)
4336                 previous = 'N';
4337
4338         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4339                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4340                         r = 0;
4341                         goto finish;
4342                 }
4343
4344                 log_error("Failed to connect to Upstart bus: %s", error.message);
4345                 r = -EIO;
4346                 goto finish;
4347         }
4348
4349         if ((r = bus_check_peercred(bus)) < 0) {
4350                 log_error("Failed to verify owner of bus.");
4351                 goto finish;
4352         }
4353
4354         if (!(m = dbus_message_new_method_call(
4355                               "com.ubuntu.Upstart",
4356                               "/com/ubuntu/Upstart",
4357                               "com.ubuntu.Upstart0_6",
4358                               "EmitEvent"))) {
4359
4360                 log_error("Could not allocate message.");
4361                 r = -ENOMEM;
4362                 goto finish;
4363         }
4364
4365         dbus_message_iter_init_append(m, &iter);
4366
4367         env1_buf[sizeof(env1_buf)-2] = rl;
4368         env2_buf[sizeof(env2_buf)-2] = previous;
4369
4370         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4371             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4372             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4373             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4374             !dbus_message_iter_close_container(&iter, &sub) ||
4375             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4376                 log_error("Could not append arguments to message.");
4377                 r = -ENOMEM;
4378                 goto finish;
4379         }
4380
4381         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4382
4383                 if (error_is_no_service(&error)) {
4384                         r = 0;
4385                         goto finish;
4386                 }
4387
4388                 log_error("Failed to issue method call: %s", error.message);
4389                 r = -EIO;
4390                 goto finish;
4391         }
4392
4393         r = 1;
4394
4395 finish:
4396         if (m)
4397                 dbus_message_unref(m);
4398
4399         if (reply)
4400                 dbus_message_unref(reply);
4401
4402         if (bus) {
4403                 dbus_connection_close(bus);
4404                 dbus_connection_unref(bus);
4405         }
4406
4407         dbus_error_free(&error);
4408
4409         return r;
4410 }
4411
4412 static int talk_initctl(void) {
4413         struct init_request request;
4414         int r, fd;
4415         char rl;
4416
4417         if (!(rl = action_to_runlevel()))
4418                 return 0;
4419
4420         zero(request);
4421         request.magic = INIT_MAGIC;
4422         request.sleeptime = 0;
4423         request.cmd = INIT_CMD_RUNLVL;
4424         request.runlevel = rl;
4425
4426         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4427
4428                 if (errno == ENOENT)
4429                         return 0;
4430
4431                 log_error("Failed to open "INIT_FIFO": %m");
4432                 return -errno;
4433         }
4434
4435         errno = 0;
4436         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4437         close_nointr_nofail(fd);
4438
4439         if (r < 0) {
4440                 log_error("Failed to write to "INIT_FIFO": %m");
4441                 return errno ? -errno : -EIO;
4442         }
4443
4444         return 1;
4445 }
4446
4447 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4448
4449         static const struct {
4450                 const char* verb;
4451                 const enum {
4452                         MORE,
4453                         LESS,
4454                         EQUAL
4455                 } argc_cmp;
4456                 const int argc;
4457                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
4458         } verbs[] = {
4459                 { "list-units",            LESS,  1, list_units        },
4460                 { "list-jobs",             EQUAL, 1, list_jobs         },
4461                 { "clear-jobs",            EQUAL, 1, daemon_reload     },
4462                 { "load",                  MORE,  2, load_unit         },
4463                 { "cancel",                MORE,  2, cancel_job        },
4464                 { "start",                 MORE,  2, start_unit        },
4465                 { "stop",                  MORE,  2, start_unit        },
4466                 { "reload",                MORE,  2, start_unit        },
4467                 { "restart",               MORE,  2, start_unit        },
4468                 { "try-restart",           MORE,  2, start_unit        },
4469                 { "reload-or-restart",     MORE,  2, start_unit        },
4470                 { "reload-or-try-restart", MORE,  2, start_unit        },
4471                 { "force-reload",          MORE,  2, start_unit        }, /* For compatibility with SysV */
4472                 { "condrestart",           MORE,  2, start_unit        }, /* For compatibility with RH */
4473                 { "isolate",               EQUAL, 2, start_unit        },
4474                 { "is-active",             MORE,  2, check_unit        },
4475                 { "check",                 MORE,  2, check_unit        },
4476                 { "show",                  MORE,  1, show              },
4477                 { "status",                MORE,  2, show              },
4478                 { "monitor",               EQUAL, 1, monitor           },
4479                 { "dump",                  EQUAL, 1, dump              },
4480                 { "dot",                   EQUAL, 1, dot               },
4481                 { "snapshot",              LESS,  2, snapshot          },
4482                 { "delete",                MORE,  2, delete_snapshot   },
4483                 { "daemon-reload",         EQUAL, 1, daemon_reload     },
4484                 { "daemon-reexec",         EQUAL, 1, daemon_reload     },
4485                 { "daemon-exit",           EQUAL, 1, daemon_reload     },
4486                 { "show-environment",      EQUAL, 1, show_enviroment   },
4487                 { "set-environment",       MORE,  2, set_environment   },
4488                 { "unset-environment",     MORE,  2, set_environment   },
4489                 { "halt",                  EQUAL, 1, start_special     },
4490                 { "poweroff",              EQUAL, 1, start_special     },
4491                 { "reboot",                EQUAL, 1, start_special     },
4492                 { "default",               EQUAL, 1, start_special     },
4493                 { "rescue",                EQUAL, 1, start_special     },
4494                 { "emergency",             EQUAL, 1, start_special     },
4495                 { "reset-maintenance",     MORE,  1, reset_maintenance },
4496                 { "enable",                MORE,  2, enable_unit       },
4497                 { "disable",               MORE,  2, enable_unit       },
4498                 { "is-enabled",            MORE,  2, enable_unit       }
4499         };
4500
4501         int left;
4502         unsigned i;
4503
4504         assert(argc >= 0);
4505         assert(argv);
4506         assert(error);
4507
4508         left = argc - optind;
4509
4510         if (left <= 0)
4511                 /* Special rule: no arguments means "list-units" */
4512                 i = 0;
4513         else {
4514                 if (streq(argv[optind], "help")) {
4515                         systemctl_help();
4516                         return 0;
4517                 }
4518
4519                 for (i = 0; i < ELEMENTSOF(verbs); i++)
4520                         if (streq(argv[optind], verbs[i].verb))
4521                                 break;
4522
4523                 if (i >= ELEMENTSOF(verbs)) {
4524                         log_error("Unknown operation %s", argv[optind]);
4525                         return -EINVAL;
4526                 }
4527         }
4528
4529         switch (verbs[i].argc_cmp) {
4530
4531         case EQUAL:
4532                 if (left != verbs[i].argc) {
4533                         log_error("Invalid number of arguments.");
4534                         return -EINVAL;
4535                 }
4536
4537                 break;
4538
4539         case MORE:
4540                 if (left < verbs[i].argc) {
4541                         log_error("Too few arguments.");
4542                         return -EINVAL;
4543                 }
4544
4545                 break;
4546
4547         case LESS:
4548                 if (left > verbs[i].argc) {
4549                         log_error("Too many arguments.");
4550                         return -EINVAL;
4551                 }
4552
4553                 break;
4554
4555         default:
4556                 assert_not_reached("Unknown comparison operator.");
4557         }
4558
4559         /* Require a bus connection for all operations but
4560          * enable/disable */
4561         if (!streq(verbs[i].verb, "enable") &&
4562             !streq(verbs[i].verb, "disable") &&
4563             !bus) {
4564                 log_error("Failed to get D-Bus connection: %s", error->message);
4565                 return -EIO;
4566         }
4567
4568         return verbs[i].dispatch(bus, argv + optind, left);
4569 }
4570
4571 static int reload_with_fallback(DBusConnection *bus) {
4572
4573         if (bus) {
4574                 /* First, try systemd via D-Bus. */
4575                 if (daemon_reload(bus, NULL, 0) > 0)
4576                         return 0;
4577         }
4578
4579         /* Nothing else worked, so let's try signals */
4580         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
4581
4582         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
4583                 log_error("kill() failed: %m");
4584                 return -errno;
4585         }
4586
4587         return 0;
4588 }
4589
4590 static int start_with_fallback(DBusConnection *bus) {
4591
4592         if (bus) {
4593                 /* First, try systemd via D-Bus. */
4594                 if (start_unit(bus, NULL, 0) > 0)
4595                         goto done;
4596         }
4597
4598         /* Hmm, talking to systemd via D-Bus didn't work. Then
4599          * let's try to talk to Upstart via D-Bus. */
4600         if (talk_upstart() > 0)
4601                 goto done;
4602
4603         /* Nothing else worked, so let's try
4604          * /dev/initctl */
4605         if (talk_initctl() > 0)
4606                 goto done;
4607
4608         log_error("Failed to talk to init daemon.");
4609         return -EIO;
4610
4611 done:
4612         warn_wall(arg_action);
4613         return 0;
4614 }
4615
4616 static int halt_main(DBusConnection *bus) {
4617         int r;
4618
4619         if (geteuid() != 0) {
4620                 log_error("Must to be root.");
4621                 return -EPERM;
4622         }
4623
4624         if (!arg_dry && !arg_immediate)
4625                 return start_with_fallback(bus);
4626
4627         if (!arg_no_wtmp)
4628                 if ((r = utmp_put_shutdown(0)) < 0)
4629                         log_warning("Failed to write utmp record: %s", strerror(-r));
4630
4631         if (!arg_no_sync)
4632                 sync();
4633
4634         if (arg_dry)
4635                 return 0;
4636
4637         /* Make sure C-A-D is handled by the kernel from this
4638          * point on... */
4639         reboot(RB_ENABLE_CAD);
4640
4641         switch (arg_action) {
4642
4643         case ACTION_HALT:
4644                 log_info("Halting.");
4645                 reboot(RB_HALT_SYSTEM);
4646                 break;
4647
4648         case ACTION_POWEROFF:
4649                 log_info("Powering off.");
4650                 reboot(RB_POWER_OFF);
4651                 break;
4652
4653         case ACTION_REBOOT:
4654                 log_info("Rebooting.");
4655                 reboot(RB_AUTOBOOT);
4656                 break;
4657
4658         default:
4659                 assert_not_reached("Unknown halt action.");
4660         }
4661
4662         /* We should never reach this. */
4663         return -ENOSYS;
4664 }
4665
4666 static int runlevel_main(void) {
4667         int r, runlevel, previous;
4668
4669         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
4670                 printf("unknown\n");
4671                 return r;
4672         }
4673
4674         printf("%c %c\n",
4675                previous <= 0 ? 'N' : previous,
4676                runlevel <= 0 ? 'N' : runlevel);
4677
4678         return 0;
4679 }
4680
4681 int main(int argc, char*argv[]) {
4682         int r, retval = 1;
4683         DBusConnection *bus = NULL;
4684         DBusError error;
4685
4686         dbus_error_init(&error);
4687
4688         log_parse_environment();
4689
4690         if ((r = parse_argv(argc, argv)) < 0)
4691                 goto finish;
4692         else if (r == 0) {
4693                 retval = 0;
4694                 goto finish;
4695         }
4696
4697         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
4698          * let's shortcut this */
4699         if (arg_action == ACTION_RUNLEVEL) {
4700                 retval = runlevel_main() < 0;
4701                 goto finish;
4702         }
4703
4704         bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
4705
4706         switch (arg_action) {
4707
4708         case ACTION_SYSTEMCTL: {
4709                 retval = systemctl_main(bus, argc, argv, &error) < 0;
4710                 break;
4711         }
4712
4713         case ACTION_HALT:
4714         case ACTION_POWEROFF:
4715         case ACTION_REBOOT:
4716                 retval = halt_main(bus) < 0;
4717                 break;
4718
4719         case ACTION_RUNLEVEL2:
4720         case ACTION_RUNLEVEL3:
4721         case ACTION_RUNLEVEL4:
4722         case ACTION_RUNLEVEL5:
4723         case ACTION_RESCUE:
4724         case ACTION_EMERGENCY:
4725         case ACTION_DEFAULT:
4726                 retval = start_with_fallback(bus) < 0;
4727                 break;
4728
4729         case ACTION_RELOAD:
4730         case ACTION_REEXEC:
4731                 retval = reload_with_fallback(bus) < 0;
4732                 break;
4733
4734         case ACTION_INVALID:
4735         case ACTION_RUNLEVEL:
4736         default:
4737                 assert_not_reached("Unknown action");
4738         }
4739
4740 finish:
4741
4742         if (bus) {
4743                 dbus_connection_close(bus);
4744                 dbus_connection_unref(bus);
4745         }
4746
4747         dbus_error_free(&error);
4748
4749         dbus_shutdown();
4750
4751         strv_free(arg_property);
4752
4753         return retval;
4754 }