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