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