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