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