chiark / gitweb /
dbus: export unit file state
[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
2479                 break;
2480         }
2481
2482         case DBUS_TYPE_ARRAY:
2483
2484                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2485                         DBusMessageIter sub, sub2;
2486
2487                         dbus_message_iter_recurse(iter, &sub);
2488                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2489                                 const char *path;
2490                                 dbus_bool_t ignore;
2491
2492                                 dbus_message_iter_recurse(&sub, &sub2);
2493
2494                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2495                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2496                                         printf("EnvironmentFile=%s (ignore_errors=%s)\n", path, yes_no(ignore));
2497
2498                                 dbus_message_iter_next(&sub);
2499                         }
2500
2501                         return 0;
2502
2503                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2504                         DBusMessageIter sub, sub2;
2505
2506                         dbus_message_iter_recurse(iter, &sub);
2507                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2508                                 const char *type, *path;
2509
2510                                 dbus_message_iter_recurse(&sub, &sub2);
2511
2512                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2513                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2514                                         printf("%s=%s\n", type, path);
2515
2516                                 dbus_message_iter_next(&sub);
2517                         }
2518
2519                         return 0;
2520
2521                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2522                         DBusMessageIter sub, sub2;
2523
2524                         dbus_message_iter_recurse(iter, &sub);
2525                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2526                                 const char *base;
2527                                 uint64_t value, next_elapse;
2528
2529                                 dbus_message_iter_recurse(&sub, &sub2);
2530
2531                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2532                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
2533                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2534                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2535
2536                                         printf("%s={ value=%s ; next_elapse=%s }\n",
2537                                                base,
2538                                                format_timespan(timespan1, sizeof(timespan1), value),
2539                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
2540                                 }
2541
2542                                 dbus_message_iter_next(&sub);
2543                         }
2544
2545                         return 0;
2546
2547                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2548                         DBusMessageIter sub;
2549
2550                         dbus_message_iter_recurse(iter, &sub);
2551                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2552                                 ExecStatusInfo info;
2553
2554                                 zero(info);
2555                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
2556                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
2557                                         char *t;
2558
2559                                         t = strv_join(info.argv, " ");
2560
2561                                         printf("%s={ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
2562                                                name,
2563                                                strna(info.path),
2564                                                strna(t),
2565                                                yes_no(info.ignore),
2566                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2567                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2568                                                (unsigned) info. pid,
2569                                                sigchld_code_to_string(info.code),
2570                                                info.status,
2571                                                info.code == CLD_EXITED ? "" : "/",
2572                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
2573
2574                                         free(t);
2575                                 }
2576
2577                                 free(info.path);
2578                                 strv_free(info.argv);
2579
2580                                 dbus_message_iter_next(&sub);
2581                         }
2582
2583                         return 0;
2584                 }
2585
2586                 break;
2587         }
2588
2589         if (generic_print_property(name, iter, arg_all) > 0)
2590                 return 0;
2591
2592         if (arg_all)
2593                 printf("%s=[unprintable]\n", name);
2594
2595         return 0;
2596 }
2597
2598 static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
2599         DBusMessage *m = NULL, *reply = NULL;
2600         const char *interface = "";
2601         int r;
2602         DBusError error;
2603         DBusMessageIter iter, sub, sub2, sub3;
2604         UnitStatusInfo info;
2605         ExecStatusInfo *p;
2606
2607         assert(bus);
2608         assert(path);
2609         assert(new_line);
2610
2611         zero(info);
2612         dbus_error_init(&error);
2613
2614         if (!(m = dbus_message_new_method_call(
2615                               "org.freedesktop.systemd1",
2616                               path,
2617                               "org.freedesktop.DBus.Properties",
2618                               "GetAll"))) {
2619                 log_error("Could not allocate message.");
2620                 r = -ENOMEM;
2621                 goto finish;
2622         }
2623
2624         if (!dbus_message_append_args(m,
2625                                       DBUS_TYPE_STRING, &interface,
2626                                       DBUS_TYPE_INVALID)) {
2627                 log_error("Could not append arguments to message.");
2628                 r = -ENOMEM;
2629                 goto finish;
2630         }
2631
2632         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2633                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2634                 r = -EIO;
2635                 goto finish;
2636         }
2637
2638         if (!dbus_message_iter_init(reply, &iter) ||
2639             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2640             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
2641                 log_error("Failed to parse reply.");
2642                 r = -EIO;
2643                 goto finish;
2644         }
2645
2646         dbus_message_iter_recurse(&iter, &sub);
2647
2648         if (*new_line)
2649                 printf("\n");
2650
2651         *new_line = true;
2652
2653         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2654                 const char *name;
2655
2656                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2657                         log_error("Failed to parse reply.");
2658                         r = -EIO;
2659                         goto finish;
2660                 }
2661
2662                 dbus_message_iter_recurse(&sub, &sub2);
2663
2664                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2665                         log_error("Failed to parse reply.");
2666                         r = -EIO;
2667                         goto finish;
2668                 }
2669
2670                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
2671                         log_error("Failed to parse reply.");
2672                         r = -EIO;
2673                         goto finish;
2674                 }
2675
2676                 dbus_message_iter_recurse(&sub2, &sub3);
2677
2678                 if (show_properties)
2679                         r = print_property(name, &sub3);
2680                 else
2681                         r = status_property(name, &sub3, &info);
2682
2683                 if (r < 0) {
2684                         log_error("Failed to parse reply.");
2685                         r = -EIO;
2686                         goto finish;
2687                 }
2688
2689                 dbus_message_iter_next(&sub);
2690         }
2691
2692         r = 0;
2693
2694         if (!show_properties)
2695                 print_status_info(&info);
2696
2697         if (!streq_ptr(info.active_state, "active") &&
2698             !streq_ptr(info.active_state, "reloading") &&
2699             streq(verb, "status"))
2700                 /* According to LSB: "program not running" */
2701                 r = 3;
2702
2703         while ((p = info.exec)) {
2704                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2705                 exec_status_info_free(p);
2706         }
2707
2708 finish:
2709         if (m)
2710                 dbus_message_unref(m);
2711
2712         if (reply)
2713                 dbus_message_unref(reply);
2714
2715         dbus_error_free(&error);
2716
2717         return r;
2718 }
2719
2720 static int show(DBusConnection *bus, char **args) {
2721         DBusMessage *m = NULL, *reply = NULL;
2722         int r, ret = 0;
2723         DBusError error;
2724         bool show_properties, new_line = false;
2725         char **name;
2726
2727         assert(bus);
2728         assert(args);
2729
2730         dbus_error_init(&error);
2731
2732         show_properties = !streq(args[0], "status");
2733
2734         if (show_properties)
2735                 pager_open_if_enabled();
2736
2737         if (show_properties && strv_length(args) <= 1) {
2738                 /* If not argument is specified inspect the manager
2739                  * itself */
2740
2741                 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2742                 goto finish;
2743         }
2744
2745         STRV_FOREACH(name, args+1) {
2746                 const char *path = NULL;
2747                 uint32_t id;
2748
2749                 if (safe_atou32(*name, &id) < 0) {
2750
2751                         /* Interpret as unit name */
2752
2753                         if (!(m = dbus_message_new_method_call(
2754                                               "org.freedesktop.systemd1",
2755                                               "/org/freedesktop/systemd1",
2756                                               "org.freedesktop.systemd1.Manager",
2757                                               "LoadUnit"))) {
2758                                 log_error("Could not allocate message.");
2759                                 ret = -ENOMEM;
2760                                 goto finish;
2761                         }
2762
2763                         if (!dbus_message_append_args(m,
2764                                                       DBUS_TYPE_STRING, name,
2765                                                       DBUS_TYPE_INVALID)) {
2766                                 log_error("Could not append arguments to message.");
2767                                 ret = -ENOMEM;
2768                                 goto finish;
2769                         }
2770
2771                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2772
2773                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2774                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2775                                         ret = -EIO;
2776                                         goto finish;
2777                                 }
2778
2779                                 dbus_error_free(&error);
2780
2781                                 dbus_message_unref(m);
2782                                 if (!(m = dbus_message_new_method_call(
2783                                                       "org.freedesktop.systemd1",
2784                                                       "/org/freedesktop/systemd1",
2785                                                       "org.freedesktop.systemd1.Manager",
2786                                                       "GetUnit"))) {
2787                                         log_error("Could not allocate message.");
2788                                         ret = -ENOMEM;
2789                                         goto finish;
2790                                 }
2791
2792                                 if (!dbus_message_append_args(m,
2793                                                               DBUS_TYPE_STRING, name,
2794                                                               DBUS_TYPE_INVALID)) {
2795                                         log_error("Could not append arguments to message.");
2796                                         ret = -ENOMEM;
2797                                         goto finish;
2798                                 }
2799
2800                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2801                                         log_error("Failed to issue method call: %s", bus_error_message(&error));
2802
2803                                         if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2804                                                 ret = 4; /* According to LSB: "program or service status is unknown" */
2805                                         else
2806                                                 ret = -EIO;
2807                                         goto finish;
2808                                 }
2809                         }
2810
2811                 } else if (show_properties) {
2812
2813                         /* Interpret as job id */
2814
2815                         if (!(m = dbus_message_new_method_call(
2816                                               "org.freedesktop.systemd1",
2817                                               "/org/freedesktop/systemd1",
2818                                               "org.freedesktop.systemd1.Manager",
2819                                               "GetJob"))) {
2820                                 log_error("Could not allocate message.");
2821                                 ret = -ENOMEM;
2822                                 goto finish;
2823                         }
2824
2825                         if (!dbus_message_append_args(m,
2826                                                       DBUS_TYPE_UINT32, &id,
2827                                                       DBUS_TYPE_INVALID)) {
2828                                 log_error("Could not append arguments to message.");
2829                                 ret = -ENOMEM;
2830                                 goto finish;
2831                         }
2832
2833                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2834                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2835                                 ret = -EIO;
2836                                 goto finish;
2837                         }
2838                 } else {
2839
2840                         /* Interpret as PID */
2841
2842                         if (!(m = dbus_message_new_method_call(
2843                                               "org.freedesktop.systemd1",
2844                                               "/org/freedesktop/systemd1",
2845                                               "org.freedesktop.systemd1.Manager",
2846                                               "GetUnitByPID"))) {
2847                                 log_error("Could not allocate message.");
2848                                 ret = -ENOMEM;
2849                                 goto finish;
2850                         }
2851
2852                         if (!dbus_message_append_args(m,
2853                                                       DBUS_TYPE_UINT32, &id,
2854                                                       DBUS_TYPE_INVALID)) {
2855                                 log_error("Could not append arguments to message.");
2856                                 ret = -ENOMEM;
2857                                 goto finish;
2858                         }
2859
2860                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2861                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2862                                 ret = -EIO;
2863                                 goto finish;
2864                         }
2865                 }
2866
2867                 if (!dbus_message_get_args(reply, &error,
2868                                            DBUS_TYPE_OBJECT_PATH, &path,
2869                                            DBUS_TYPE_INVALID)) {
2870                         log_error("Failed to parse reply: %s", bus_error_message(&error));
2871                         ret = -EIO;
2872                         goto finish;
2873                 }
2874
2875                 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
2876                         ret = r;
2877
2878                 dbus_message_unref(m);
2879                 dbus_message_unref(reply);
2880                 m = reply = NULL;
2881         }
2882
2883 finish:
2884         if (m)
2885                 dbus_message_unref(m);
2886
2887         if (reply)
2888                 dbus_message_unref(reply);
2889
2890         dbus_error_free(&error);
2891
2892         return ret;
2893 }
2894
2895 static int dump(DBusConnection *bus, char **args) {
2896         DBusMessage *m = NULL, *reply = NULL;
2897         DBusError error;
2898         int r;
2899         const char *text;
2900
2901         dbus_error_init(&error);
2902
2903         pager_open_if_enabled();
2904
2905         if (!(m = dbus_message_new_method_call(
2906                               "org.freedesktop.systemd1",
2907                               "/org/freedesktop/systemd1",
2908                               "org.freedesktop.systemd1.Manager",
2909                               "Dump"))) {
2910                 log_error("Could not allocate message.");
2911                 return -ENOMEM;
2912         }
2913
2914         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2915                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2916                 r = -EIO;
2917                 goto finish;
2918         }
2919
2920         if (!dbus_message_get_args(reply, &error,
2921                                    DBUS_TYPE_STRING, &text,
2922                                    DBUS_TYPE_INVALID)) {
2923                 log_error("Failed to parse reply: %s", bus_error_message(&error));
2924                 r = -EIO;
2925                 goto finish;
2926         }
2927
2928         fputs(text, stdout);
2929
2930         r = 0;
2931
2932 finish:
2933         if (m)
2934                 dbus_message_unref(m);
2935
2936         if (reply)
2937                 dbus_message_unref(reply);
2938
2939         dbus_error_free(&error);
2940
2941         return r;
2942 }
2943
2944 static int snapshot(DBusConnection *bus, char **args) {
2945         DBusMessage *m = NULL, *reply = NULL;
2946         DBusError error;
2947         int r;
2948         const char *name = "", *path, *id;
2949         dbus_bool_t cleanup = FALSE;
2950         DBusMessageIter iter, sub;
2951         const char
2952                 *interface = "org.freedesktop.systemd1.Unit",
2953                 *property = "Id";
2954
2955         dbus_error_init(&error);
2956
2957         if (!(m = dbus_message_new_method_call(
2958                               "org.freedesktop.systemd1",
2959                               "/org/freedesktop/systemd1",
2960                               "org.freedesktop.systemd1.Manager",
2961                               "CreateSnapshot"))) {
2962                 log_error("Could not allocate message.");
2963                 return -ENOMEM;
2964         }
2965
2966         if (strv_length(args) > 1)
2967                 name = args[1];
2968
2969         if (!dbus_message_append_args(m,
2970                                       DBUS_TYPE_STRING, &name,
2971                                       DBUS_TYPE_BOOLEAN, &cleanup,
2972                                       DBUS_TYPE_INVALID)) {
2973                 log_error("Could not append arguments to message.");
2974                 r = -ENOMEM;
2975                 goto finish;
2976         }
2977
2978         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2979                 log_error("Failed to issue method call: %s", bus_error_message(&error));
2980                 r = -EIO;
2981                 goto finish;
2982         }
2983
2984         if (!dbus_message_get_args(reply, &error,
2985                                    DBUS_TYPE_OBJECT_PATH, &path,
2986                                    DBUS_TYPE_INVALID)) {
2987                 log_error("Failed to parse reply: %s", bus_error_message(&error));
2988                 r = -EIO;
2989                 goto finish;
2990         }
2991
2992         dbus_message_unref(m);
2993         if (!(m = dbus_message_new_method_call(
2994                               "org.freedesktop.systemd1",
2995                               path,
2996                               "org.freedesktop.DBus.Properties",
2997                               "Get"))) {
2998                 log_error("Could not allocate message.");
2999                 return -ENOMEM;
3000         }
3001
3002         if (!dbus_message_append_args(m,
3003                                       DBUS_TYPE_STRING, &interface,
3004                                       DBUS_TYPE_STRING, &property,
3005                                       DBUS_TYPE_INVALID)) {
3006                 log_error("Could not append arguments to message.");
3007                 r = -ENOMEM;
3008                 goto finish;
3009         }
3010
3011         dbus_message_unref(reply);
3012         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3013                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3014                 r = -EIO;
3015                 goto finish;
3016         }
3017
3018         if (!dbus_message_iter_init(reply, &iter) ||
3019             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3020                 log_error("Failed to parse reply.");
3021                 r = -EIO;
3022                 goto finish;
3023         }
3024
3025         dbus_message_iter_recurse(&iter, &sub);
3026
3027         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
3028                 log_error("Failed to parse reply.");
3029                 r = -EIO;
3030                 goto finish;
3031         }
3032
3033         dbus_message_iter_get_basic(&sub, &id);
3034
3035         if (!arg_quiet)
3036                 puts(id);
3037         r = 0;
3038
3039 finish:
3040         if (m)
3041                 dbus_message_unref(m);
3042
3043         if (reply)
3044                 dbus_message_unref(reply);
3045
3046         dbus_error_free(&error);
3047
3048         return r;
3049 }
3050
3051 static int delete_snapshot(DBusConnection *bus, char **args) {
3052         DBusMessage *m = NULL, *reply = NULL;
3053         int r;
3054         DBusError error;
3055         char **name;
3056
3057         assert(bus);
3058         assert(args);
3059
3060         dbus_error_init(&error);
3061
3062         STRV_FOREACH(name, args+1) {
3063                 const char *path = NULL;
3064
3065                 if (!(m = dbus_message_new_method_call(
3066                                       "org.freedesktop.systemd1",
3067                                       "/org/freedesktop/systemd1",
3068                                       "org.freedesktop.systemd1.Manager",
3069                                       "GetUnit"))) {
3070                         log_error("Could not allocate message.");
3071                         r = -ENOMEM;
3072                         goto finish;
3073                 }
3074
3075                 if (!dbus_message_append_args(m,
3076                                               DBUS_TYPE_STRING, name,
3077                                               DBUS_TYPE_INVALID)) {
3078                         log_error("Could not append arguments to message.");
3079                         r = -ENOMEM;
3080                         goto finish;
3081                 }
3082
3083                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3084                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3085                         r = -EIO;
3086                         goto finish;
3087                 }
3088
3089                 if (!dbus_message_get_args(reply, &error,
3090                                            DBUS_TYPE_OBJECT_PATH, &path,
3091                                            DBUS_TYPE_INVALID)) {
3092                         log_error("Failed to parse reply: %s", bus_error_message(&error));
3093                         r = -EIO;
3094                         goto finish;
3095                 }
3096
3097                 dbus_message_unref(m);
3098                 if (!(m = dbus_message_new_method_call(
3099                                       "org.freedesktop.systemd1",
3100                                       path,
3101                                       "org.freedesktop.systemd1.Snapshot",
3102                                       "Remove"))) {
3103                         log_error("Could not allocate message.");
3104                         r = -ENOMEM;
3105                         goto finish;
3106                 }
3107
3108                 dbus_message_unref(reply);
3109                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3110                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3111                         r = -EIO;
3112                         goto finish;
3113                 }
3114
3115                 dbus_message_unref(m);
3116                 dbus_message_unref(reply);
3117                 m = reply = NULL;
3118         }
3119
3120         r = 0;
3121
3122 finish:
3123         if (m)
3124                 dbus_message_unref(m);
3125
3126         if (reply)
3127                 dbus_message_unref(reply);
3128
3129         dbus_error_free(&error);
3130
3131         return r;
3132 }
3133
3134 static int daemon_reload(DBusConnection *bus, char **args) {
3135         DBusMessage *m = NULL, *reply = NULL;
3136         DBusError error;
3137         int r;
3138         const char *method;
3139
3140         dbus_error_init(&error);
3141
3142         if (arg_action == ACTION_RELOAD)
3143                 method = "Reload";
3144         else if (arg_action == ACTION_REEXEC)
3145                 method = "Reexecute";
3146         else {
3147                 assert(arg_action == ACTION_SYSTEMCTL);
3148
3149                 method =
3150                         streq(args[0], "clear-jobs")    ||
3151                         streq(args[0], "cancel")        ? "ClearJobs" :
3152                         streq(args[0], "daemon-reexec") ? "Reexecute" :
3153                         streq(args[0], "reset-failed")  ? "ResetFailed" :
3154                         streq(args[0], "halt")          ? "Halt" :
3155                         streq(args[0], "poweroff")      ? "PowerOff" :
3156                         streq(args[0], "reboot")        ? "Reboot" :
3157                         streq(args[0], "kexec")         ? "KExec" :
3158                         streq(args[0], "exit")          ? "Exit" :
3159                                     /* "daemon-reload" */ "Reload";
3160         }
3161
3162         if (!(m = dbus_message_new_method_call(
3163                               "org.freedesktop.systemd1",
3164                               "/org/freedesktop/systemd1",
3165                               "org.freedesktop.systemd1.Manager",
3166                               method))) {
3167                 log_error("Could not allocate message.");
3168                 return -ENOMEM;
3169         }
3170
3171         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3172
3173                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3174                         /* There's always a fallback possible for
3175                          * legacy actions. */
3176                         r = -EADDRNOTAVAIL;
3177                         goto finish;
3178                 }
3179
3180                 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3181                         /* On reexecution, we expect a disconnect, not
3182                          * a reply */
3183                         r = 0;
3184                         goto finish;
3185                 }
3186
3187                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3188                 r = -EIO;
3189                 goto finish;
3190         }
3191
3192         r = 0;
3193
3194 finish:
3195         if (m)
3196                 dbus_message_unref(m);
3197
3198         if (reply)
3199                 dbus_message_unref(reply);
3200
3201         dbus_error_free(&error);
3202
3203         return r;
3204 }
3205
3206 static int reset_failed(DBusConnection *bus, char **args) {
3207         DBusMessage *m = NULL, *reply = NULL;
3208         int r;
3209         DBusError error;
3210         char **name;
3211
3212         assert(bus);
3213         dbus_error_init(&error);
3214
3215         if (strv_length(args) <= 1)
3216                 return daemon_reload(bus, args);
3217
3218         STRV_FOREACH(name, args+1) {
3219
3220                 if (!(m = dbus_message_new_method_call(
3221                                       "org.freedesktop.systemd1",
3222                                       "/org/freedesktop/systemd1",
3223                                       "org.freedesktop.systemd1.Manager",
3224                                       "ResetFailedUnit"))) {
3225                         log_error("Could not allocate message.");
3226                         r = -ENOMEM;
3227                         goto finish;
3228                 }
3229
3230                 if (!dbus_message_append_args(m,
3231                                               DBUS_TYPE_STRING, name,
3232                                               DBUS_TYPE_INVALID)) {
3233                         log_error("Could not append arguments to message.");
3234                         r = -ENOMEM;
3235                         goto finish;
3236                 }
3237
3238                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3239                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3240                         r = -EIO;
3241                         goto finish;
3242                 }
3243
3244                 dbus_message_unref(m);
3245                 dbus_message_unref(reply);
3246                 m = reply = NULL;
3247         }
3248
3249         r = 0;
3250
3251 finish:
3252         if (m)
3253                 dbus_message_unref(m);
3254
3255         if (reply)
3256                 dbus_message_unref(reply);
3257
3258         dbus_error_free(&error);
3259
3260         return r;
3261 }
3262
3263 static int show_enviroment(DBusConnection *bus, char **args) {
3264         DBusMessage *m = NULL, *reply = NULL;
3265         DBusError error;
3266         DBusMessageIter iter, sub, sub2;
3267         int r;
3268         const char
3269                 *interface = "org.freedesktop.systemd1.Manager",
3270                 *property = "Environment";
3271
3272         dbus_error_init(&error);
3273
3274         pager_open_if_enabled();
3275
3276         if (!(m = dbus_message_new_method_call(
3277                               "org.freedesktop.systemd1",
3278                               "/org/freedesktop/systemd1",
3279                               "org.freedesktop.DBus.Properties",
3280                               "Get"))) {
3281                 log_error("Could not allocate message.");
3282                 return -ENOMEM;
3283         }
3284
3285         if (!dbus_message_append_args(m,
3286                                       DBUS_TYPE_STRING, &interface,
3287                                       DBUS_TYPE_STRING, &property,
3288                                       DBUS_TYPE_INVALID)) {
3289                 log_error("Could not append arguments to message.");
3290                 r = -ENOMEM;
3291                 goto finish;
3292         }
3293
3294         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3295                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3296                 r = -EIO;
3297                 goto finish;
3298         }
3299
3300         if (!dbus_message_iter_init(reply, &iter) ||
3301             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
3302                 log_error("Failed to parse reply.");
3303                 r = -EIO;
3304                 goto finish;
3305         }
3306
3307         dbus_message_iter_recurse(&iter, &sub);
3308
3309         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3310             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
3311                 log_error("Failed to parse reply.");
3312                 r = -EIO;
3313                 goto finish;
3314         }
3315
3316         dbus_message_iter_recurse(&sub, &sub2);
3317
3318         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3319                 const char *text;
3320
3321                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3322                         log_error("Failed to parse reply.");
3323                         r = -EIO;
3324                         goto finish;
3325                 }
3326
3327                 dbus_message_iter_get_basic(&sub2, &text);
3328                 printf("%s\n", text);
3329
3330                 dbus_message_iter_next(&sub2);
3331         }
3332
3333         r = 0;
3334
3335 finish:
3336         if (m)
3337                 dbus_message_unref(m);
3338
3339         if (reply)
3340                 dbus_message_unref(reply);
3341
3342         dbus_error_free(&error);
3343
3344         return r;
3345 }
3346
3347 static int set_environment(DBusConnection *bus, char **args) {
3348         DBusMessage *m = NULL, *reply = NULL;
3349         DBusError error;
3350         int r;
3351         const char *method;
3352         DBusMessageIter iter, sub;
3353         char **name;
3354
3355         dbus_error_init(&error);
3356
3357         method = streq(args[0], "set-environment")
3358                 ? "SetEnvironment"
3359                 : "UnsetEnvironment";
3360
3361         if (!(m = dbus_message_new_method_call(
3362                               "org.freedesktop.systemd1",
3363                               "/org/freedesktop/systemd1",
3364                               "org.freedesktop.systemd1.Manager",
3365                               method))) {
3366
3367                 log_error("Could not allocate message.");
3368                 return -ENOMEM;
3369         }
3370
3371         dbus_message_iter_init_append(m, &iter);
3372
3373         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3374                 log_error("Could not append arguments to message.");
3375                 r = -ENOMEM;
3376                 goto finish;
3377         }
3378
3379         STRV_FOREACH(name, args+1)
3380                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, name)) {
3381                         log_error("Could not append arguments to message.");
3382                         r = -ENOMEM;
3383                         goto finish;
3384                 }
3385
3386         if (!dbus_message_iter_close_container(&iter, &sub)) {
3387                 log_error("Could not append arguments to message.");
3388                 r = -ENOMEM;
3389                 goto finish;
3390         }
3391
3392         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3393                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3394                 r = -EIO;
3395                 goto finish;
3396         }
3397
3398         r = 0;
3399
3400 finish:
3401         if (m)
3402                 dbus_message_unref(m);
3403
3404         if (reply)
3405                 dbus_message_unref(reply);
3406
3407         dbus_error_free(&error);
3408
3409         return r;
3410 }
3411
3412 static int enable_sysv_units(char **args) {
3413         int r = 0;
3414
3415 #if defined (HAVE_SYSV_COMPAT) && (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX))
3416         const char *verb = args[0];
3417         unsigned f = 1, t = 1;
3418         LookupPaths paths;
3419
3420         if (arg_scope != UNIT_FILE_SYSTEM)
3421                 return 0;
3422
3423         if (!streq(verb, "enable") &&
3424             !streq(verb, "disable") &&
3425             !streq(verb, "is-enabled"))
3426                 return 0;
3427
3428         /* Processes all SysV units, and reshuffles the array so that
3429          * afterwards only the native units remain */
3430
3431         zero(paths);
3432         r = lookup_paths_init(&paths, MANAGER_SYSTEM, false);
3433         if (r < 0)
3434                 return r;
3435
3436         r = 0;
3437
3438         for (f = 1; args[f]; f++) {
3439                 const char *name;
3440                 char *p;
3441                 bool found_native = false, found_sysv;
3442                 unsigned c = 1;
3443                 const char *argv[6] = { "/sbin/chkconfig", NULL, NULL, NULL, NULL };
3444                 char **k, *l, *q = NULL;
3445                 int j;
3446                 pid_t pid;
3447                 siginfo_t status;
3448
3449                 name = args[f];
3450
3451                 if (!endswith(name, ".service"))
3452                         continue;
3453
3454                 if (path_is_absolute(name))
3455                         continue;
3456
3457                 STRV_FOREACH(k, paths.unit_path) {
3458                         p = NULL;
3459
3460                         if (!isempty(arg_root))
3461                                 asprintf(&p, "%s/%s/%s", arg_root, *k, name);
3462                         else
3463                                 asprintf(&p, "%s/%s", *k, name);
3464
3465                         if (!p) {
3466                                 log_error("No memory");
3467                                 r = -ENOMEM;
3468                                 goto finish;
3469                         }
3470
3471                         found_native = access(p, F_OK) >= 0;
3472                         free(p);
3473
3474                         if (found_native)
3475                                 break;
3476                 }
3477
3478                 if (found_native)
3479                         continue;
3480
3481                 p = NULL;
3482                 if (!isempty(arg_root))
3483                         asprintf(&p, "%s/" SYSTEM_SYSVINIT_PATH "/%s", arg_root, name);
3484                 else
3485                         asprintf(&p, SYSTEM_SYSVINIT_PATH "/%s", name);
3486                 if (!p) {
3487                         log_error("No memory");
3488                         r = -ENOMEM;
3489                         goto finish;
3490                 }
3491
3492                 p[strlen(p) - sizeof(".service") + 1] = 0;
3493                 found_sysv = access(p, F_OK) >= 0;
3494
3495                 if (!found_sysv) {
3496                         free(p);
3497                         continue;
3498                 }
3499
3500                 /* Mark this entry, so that we don't try enabling it as native unit */
3501                 args[f] = (char*) "";
3502
3503                 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", name);
3504
3505                 if (!isempty(arg_root))
3506                         argv[c++] = q = strappend("--root=", arg_root);
3507
3508                 argv[c++] = file_name_from_path(p);
3509                 argv[c++] =
3510                         streq(verb, "enable") ? "on" :
3511                         streq(verb, "disable") ? "off" : "--level=5";
3512                 argv[c] = NULL;
3513
3514                 l = strv_join((char**)argv, " ");
3515                 if (!l) {
3516                         log_error("No memory.");
3517                         free(q);
3518                         free(p);
3519                         r = -ENOMEM;
3520                         goto finish;
3521                 }
3522
3523                 log_info("Executing %s", l);
3524                 free(l);
3525
3526                 pid = fork();
3527                 if (pid < 0) {
3528                         log_error("Failed to fork: %m");
3529                         free(p);
3530                         free(q);
3531                         r = -errno;
3532                         goto finish;
3533                 } else if (pid == 0) {
3534                         /* Child */
3535
3536                         execv(argv[0], (char**) argv);
3537                         _exit(EXIT_FAILURE);
3538                 }
3539
3540                 free(p);
3541                 free(q);
3542
3543                 j = wait_for_terminate(pid, &status);
3544                 if (j < 0) {
3545                         log_error("Failed to wait for child: %s", strerror(-r));
3546                         r = j;
3547                         goto finish;
3548                 }
3549
3550                 if (status.si_code == CLD_EXITED) {
3551                         if (streq(verb, "is-enabled")) {
3552                                 if (status.si_status == 0) {
3553                                         if (!arg_quiet)
3554                                                 puts("enabled");
3555                                         r = 1;
3556                                 } else {
3557                                         if (!arg_quiet)
3558                                                 puts("disabled");
3559                                 }
3560
3561                         } else if (status.si_status != 0) {
3562                                 r = -EINVAL;
3563                                 goto finish;
3564                         }
3565                 } else {
3566                         r = -EPROTO;
3567                         goto finish;
3568                 }
3569         }
3570
3571 finish:
3572         lookup_paths_free(&paths);
3573
3574         /* Drop all SysV units */
3575         for (f = 1, t = 1; args[f]; f++) {
3576
3577                 if (isempty(args[f]))
3578                         continue;
3579
3580                 args[t++] = args[f];
3581         }
3582
3583         args[t] = NULL;
3584
3585 #endif
3586         return r;
3587 }
3588
3589 static int enable_unit(DBusConnection *bus, char **args) {
3590         const char *verb = args[0];
3591         UnitFileChange *changes = NULL;
3592         unsigned n_changes = 0, i;
3593         int carries_install_info = -1;
3594         DBusMessage *m = NULL, *reply = NULL;
3595         int r;
3596         DBusError error;
3597
3598         dbus_error_init(&error);
3599
3600         r = enable_sysv_units(args);
3601         if (r < 0)
3602                 return r;
3603
3604         if (!bus || avoid_bus()) {
3605                 if (streq(verb, "enable")) {
3606                         r = unit_file_enable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3607                         carries_install_info = r;
3608                 } else if (streq(verb, "disable"))
3609                         r = unit_file_disable(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3610                 else if (streq(verb, "reenable")) {
3611                         r = unit_file_reenable(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3612                         carries_install_info = r;
3613                 } else if (streq(verb, "link"))
3614                         r = unit_file_link(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3615                 else if (streq(verb, "preset")) {
3616                         r = unit_file_preset(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3617                         carries_install_info = r;
3618                 } else if (streq(verb, "mask"))
3619                         r = unit_file_mask(arg_scope, arg_runtime, arg_root, args+1, arg_force, &changes, &n_changes);
3620                 else if (streq(verb, "unmask"))
3621                         r = unit_file_unmask(arg_scope, arg_runtime, arg_root, args+1, &changes, &n_changes);
3622                 else
3623                         assert_not_reached("Unknown verb");
3624
3625                 if (r < 0) {
3626                         log_error("Operation failed: %s", strerror(-r));
3627                         goto finish;
3628                 }
3629
3630                 for (i = 0; i < n_changes; i++) {
3631                         if (changes[i].type == UNIT_FILE_SYMLINK)
3632                                 log_info("ln -s '%s' '%s'", changes[i].source, changes[i].path);
3633                         else
3634                                 log_info("rm '%s'", changes[i].path);
3635                 }
3636
3637         } else {
3638                 const char *method;
3639                 bool send_force = true, expect_carries_install_info = false;
3640                 dbus_bool_t a, b;
3641                 DBusMessageIter iter, sub, sub2;
3642
3643                 if (streq(verb, "enable")) {
3644                         method = "EnableUnitFiles";
3645                         expect_carries_install_info = true;
3646                 } else if (streq(verb, "disable")) {
3647                         method = "DisableUnitFiles";
3648                         send_force = false;
3649                 } else if (streq(verb, "reenable")) {
3650                         method = "ReenableUnitFiles";
3651                         expect_carries_install_info = true;
3652                 } else if (streq(verb, "link"))
3653                         method = "LinkUnitFiles";
3654                 else if (streq(verb, "preset")) {
3655                         method = "PresetUnitFiles";
3656                         expect_carries_install_info = true;
3657                 } else if (streq(verb, "mask"))
3658                         method = "MaskUnitFiles";
3659                 else if (streq(verb, "unmask")) {
3660                         method = "UnmaskUnitFiles";
3661                         send_force = false;
3662                 } else
3663                         assert_not_reached("Unknown verb");
3664
3665                 m = dbus_message_new_method_call(
3666                                 "org.freedesktop.systemd1",
3667                                 "/org/freedesktop/systemd1",
3668                                 "org.freedesktop.systemd1.Manager",
3669                                 method);
3670                 if (!m) {
3671                         log_error("Out of memory");
3672                         r = -ENOMEM;
3673                         goto finish;
3674                 }
3675
3676                 dbus_message_iter_init_append(m, &iter);
3677
3678                 r = bus_append_strv_iter(&iter, args+1);
3679                 if (r < 0) {
3680                         log_error("Failed to append unit files.");
3681                         goto finish;
3682                 }
3683
3684                 a = arg_runtime;
3685                 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &a)) {
3686                         log_error("Failed to append runtime boolean.");
3687                         r = -ENOMEM;
3688                         goto finish;
3689                 }
3690
3691                 if (send_force) {
3692                         b = arg_force;
3693
3694                         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b)) {
3695                                 log_error("Failed to append force boolean.");
3696                                 r = -ENOMEM;
3697                                 goto finish;
3698                         }
3699                 }
3700
3701                 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3702                 if (!reply) {
3703                         log_error("Failed to issue method call: %s", bus_error_message(&error));
3704                         r = -EIO;
3705                         goto finish;
3706                 }
3707
3708                 if (!dbus_message_iter_init(reply, &iter)) {
3709                         log_error("Failed to initialize iterator.");
3710                         goto finish;
3711                 }
3712
3713                 if (expect_carries_install_info) {
3714                         r = bus_iter_get_basic_and_next(&iter, DBUS_TYPE_BOOLEAN, &b, true);
3715                         if (r < 0) {
3716                                 log_error("Failed to parse reply.");
3717                                 goto finish;
3718                         }
3719
3720                         carries_install_info = b;
3721                 }
3722
3723                 if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
3724                     dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
3725                         log_error("Failed to parse reply.");
3726                         r = -EIO;
3727                         goto finish;
3728                 }
3729
3730                 dbus_message_iter_recurse(&iter, &sub);
3731                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
3732                         const char *type, *path, *source;
3733
3734                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
3735                                 log_error("Failed to parse reply.");
3736                                 r = -EIO;
3737                                 goto finish;
3738                         }
3739
3740                         dbus_message_iter_recurse(&sub, &sub2);
3741
3742                         if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
3743                             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0 ||
3744                             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &source, false) < 0) {
3745                                 log_error("Failed to parse reply.");
3746                                 r = -EIO;
3747                                 goto finish;
3748                         }
3749
3750                         if (streq(type, "symlink"))
3751                                 log_info("ln -s '%s' '%s'", source, path);
3752                         else
3753                                 log_info("rm '%s'", path);
3754
3755                         dbus_message_iter_next(&sub);
3756                 }
3757
3758                 /* Try to reload if enabeld */
3759                 if (!arg_no_reload)
3760                         r = daemon_reload(bus, args);
3761         }
3762
3763         if (carries_install_info == 0)
3764                 log_warning("Warning: unit files do not carry install information. No operation executed.");
3765
3766 finish:
3767         if (m)
3768                 dbus_message_unref(m);
3769
3770         if (reply)
3771                 dbus_message_unref(reply);
3772
3773         unit_file_changes_free(changes, n_changes);
3774
3775         dbus_error_free(&error);
3776         return r;
3777 }
3778
3779 static int unit_is_enabled(DBusConnection *bus, char **args) {
3780         DBusError error;
3781         int r;
3782         DBusMessage *m = NULL, *reply = NULL;
3783         bool enabled;
3784         char **name;
3785
3786         dbus_error_init(&error);
3787
3788         r = enable_sysv_units(args);
3789         if (r < 0)
3790                 return r;
3791
3792         enabled = r > 0;
3793
3794         if (!bus || avoid_bus()) {
3795
3796                 STRV_FOREACH(name, args+1) {
3797                         UnitFileState state;
3798
3799                         state = unit_file_get_state(arg_scope, arg_root, *name);
3800                         if (state < 0) {
3801                                 r = state;
3802                                 goto finish;
3803                         }
3804
3805                         if (state == UNIT_FILE_ENABLED ||
3806                             state == UNIT_FILE_ENABLED_RUNTIME ||
3807                             state == UNIT_FILE_STATIC)
3808                                 enabled = true;
3809
3810                         if (!arg_quiet)
3811                                 puts(unit_file_state_to_string(state));
3812                 }
3813
3814         } else {
3815                 STRV_FOREACH(name, args+1) {
3816                         const char *s;
3817
3818                         m = dbus_message_new_method_call(
3819                                         "org.freedesktop.systemd1",
3820                                         "/org/freedesktop/systemd1",
3821                                         "org.freedesktop.systemd1.Manager",
3822                                         "GetUnitFileState");
3823                         if (!m) {
3824                                 log_error("Out of memory");
3825                                 r = -ENOMEM;
3826                                 goto finish;
3827                         }
3828
3829                         if (!dbus_message_append_args(m,
3830                                                       DBUS_TYPE_STRING, name,
3831                                                       DBUS_TYPE_INVALID)) {
3832                                 log_error("Could not append arguments to message.");
3833                                 r = -ENOMEM;
3834                                 goto finish;
3835                         }
3836
3837                         reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
3838                         if (!reply) {
3839                                 log_error("Failed to issue method call: %s", bus_error_message(&error));
3840                                 r = -EIO;
3841                                 goto finish;
3842                         }
3843
3844                         if (!dbus_message_get_args(reply, &error,
3845                                                    DBUS_TYPE_STRING, &s,
3846                                                    DBUS_TYPE_INVALID)) {
3847                                 log_error("Failed to parse reply: %s", bus_error_message(&error));
3848                                 r = -EIO;
3849                                 goto finish;
3850                         }
3851
3852                         dbus_message_unref(m);
3853                         dbus_message_unref(reply);
3854                         m = reply = NULL;
3855
3856                         if (streq(s, "enabled") ||
3857                             streq(s, "enabled-runtime") ||
3858                             streq(s, "static"))
3859                                 enabled = true;
3860
3861                         if (!arg_quiet)
3862                                 puts(s);
3863                 }
3864         }
3865
3866         r = enabled ? 0 : 1;
3867
3868 finish:
3869         if (m)
3870                 dbus_message_unref(m);
3871
3872         if (reply)
3873                 dbus_message_unref(reply);
3874
3875         dbus_error_free(&error);
3876         return r;
3877 }
3878
3879 static int systemctl_help(void) {
3880
3881         pager_open_if_enabled();
3882
3883         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
3884                "Query or send control commands to the systemd manager.\n\n"
3885                "  -h --help           Show this help\n"
3886                "     --version        Show package version\n"
3887                "  -t --type=TYPE      List only units of a particular type\n"
3888                "  -p --property=NAME  Show only properties by this name\n"
3889                "  -a --all            Show all units/properties, including dead/empty ones\n"
3890                "     --failed         Show only failed units\n"
3891                "     --full           Don't ellipsize unit names on output\n"
3892                "     --fail           When queueing a new job, fail if conflicting jobs are\n"
3893                "                      pending\n"
3894                "     --ignore-dependencies\n"
3895                "                      When queueing a new job, ignore all its dependencies\n"
3896                "     --kill-who=WHO   Who to send signal to\n"
3897                "  -s --signal=SIGNAL  Which signal to send\n"
3898                "  -H --host=[USER@]HOST\n"
3899                "                      Show information for remote host\n"
3900                "  -P --privileged     Acquire privileges before execution\n"
3901                "  -q --quiet          Suppress output\n"
3902                "     --no-block       Do not wait until operation finished\n"
3903                "     --no-wall        Don't send wall message before halt/power-off/reboot\n"
3904                "     --no-reload      When enabling/disabling unit files, don't reload daemon\n"
3905                "                      configuration\n"
3906                "     --no-pager       Do not pipe output into a pager\n"
3907                "     --no-ask-password\n"
3908                "                      Do not ask for system passwords\n"
3909                "     --order          When generating graph for dot, show only order\n"
3910                "     --require        When generating graph for dot, show only requirement\n"
3911                "     --system         Connect to system manager\n"
3912                "     --user           Connect to user service manager\n"
3913                "     --global         Enable/disable unit files globally\n"
3914                "  -f --force          When enabling unit files, override existing symlinks\n"
3915                "                      When shutting down, execute action immediately\n"
3916                "     --root=PATH      Enable unit files in the specified root directory\n"
3917                "     --runtime        Enable unit files only temporarily until next reboot\n\n"
3918                "Unit Commands:\n"
3919                "  list-units                      List loaded units\n"
3920                "  start [NAME...]                 Start (activate) one or more units\n"
3921                "  stop [NAME...]                  Stop (deactivate) one or more units\n"
3922                "  reload [NAME...]                Reload one or more units\n"
3923                "  restart [NAME...]               Start or restart one or more units\n"
3924                "  try-restart [NAME...]           Restart one or more units if active\n"
3925                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
3926                "                                  otherwise start or restart\n"
3927                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
3928                "                                  otherwise restart if active\n"
3929                "  isolate [NAME]                  Start one unit and stop all others\n"
3930                "  kill [NAME...]                  Send signal to processes of a unit\n"
3931                "  is-active [NAME...]             Check whether units are active\n"
3932                "  status [NAME...|PID...]         Show runtime status of one or more units\n"
3933                "  show [NAME...|JOB...]           Show properties of one or more\n"
3934                "                                  units/jobs or the manager\n"
3935                "  reset-failed [NAME...]          Reset failed state for all, one, or more\n"
3936                "                                  units\n"
3937                "  load [NAME...]                  Load one or more units\n\n"
3938                "Unit File Commands:\n"
3939                "  list-unit-files                 List installed unit files\n"
3940                "  enable [NAME...]                Enable one or more unit files\n"
3941                "  disable [NAME...]               Disable one or more unit files\n"
3942                "  reenable [NAME...]              Reenable one or more unit files\n"
3943                "  preset [NAME...]                Enable/disable one or more unit files\n"
3944                "                                  based on preset configuration\n"
3945                "  mask [NAME...]                  Mask one or more units\n"
3946                "  unmask [NAME...]                Unmask one or more units\n"
3947                "  link [PATH...]                  Link one or more units files into\n"
3948                "                                  the search path\n"
3949                "  is-enabled [NAME...]            Check whether unit files are enabled\n\n"
3950                "Job Commands:\n"
3951                "  list-jobs                       List jobs\n"
3952                "  cancel [JOB...]                 Cancel all, one, or more jobs\n\n"
3953                "Status Commands:\n"
3954                "  dump                            Dump server status\n"
3955                "  dot                             Dump dependency graph for dot(1)\n\n"
3956                "Snapshot Commands:\n"
3957                "  snapshot [NAME]                 Create a snapshot\n"
3958                "  delete [NAME...]                Remove one or more snapshots\n\n"
3959                "Environment Commands:\n"
3960                "  show-environment                Dump environment\n"
3961                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
3962                "  unset-environment [NAME...]     Unset one or more environment variables\n\n"
3963                "Manager Lifecycle Commands:\n"
3964                "  daemon-reload                   Reload systemd manager configuration\n"
3965                "  daemon-reexec                   Reexecute systemd manager\n\n"
3966                "System Commands:\n"
3967                "  default                         Enter system default mode\n"
3968                "  rescue                          Enter system rescue mode\n"
3969                "  emergency                       Enter system emergency mode\n"
3970                "  halt                            Shut down and halt the system\n"
3971                "  poweroff                        Shut down and power-off the system\n"
3972                "  reboot                          Shut down and reboot the system\n"
3973                "  kexec                           Shut down and reboot the system with kexec\n"
3974                "  exit                            Ask for user instance termination\n",
3975                program_invocation_short_name);
3976
3977         return 0;
3978 }
3979
3980 static int halt_help(void) {
3981
3982         printf("%s [OPTIONS...]\n\n"
3983                "%s the system.\n\n"
3984                "     --help      Show this help\n"
3985                "     --halt      Halt the machine\n"
3986                "  -p --poweroff  Switch off the machine\n"
3987                "     --reboot    Reboot the machine\n"
3988                "  -f --force     Force immediate halt/power-off/reboot\n"
3989                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
3990                "  -d --no-wtmp   Don't write wtmp record\n"
3991                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
3992                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
3993                program_invocation_short_name,
3994                arg_action == ACTION_REBOOT   ? "Reboot" :
3995                arg_action == ACTION_POWEROFF ? "Power off" :
3996                                                "Halt");
3997
3998         return 0;
3999 }
4000
4001 static int shutdown_help(void) {
4002
4003         printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
4004                "Shut down the system.\n\n"
4005                "     --help      Show this help\n"
4006                "  -H --halt      Halt the machine\n"
4007                "  -P --poweroff  Power-off the machine\n"
4008                "  -r --reboot    Reboot the machine\n"
4009                "  -h             Equivalent to --poweroff, overriden by --halt\n"
4010                "  -k             Don't halt/power-off/reboot, just send warnings\n"
4011                "     --no-wall   Don't send wall message before halt/power-off/reboot\n"
4012                "  -c             Cancel a pending shutdown\n",
4013                program_invocation_short_name);
4014
4015         return 0;
4016 }
4017
4018 static int telinit_help(void) {
4019
4020         printf("%s [OPTIONS...] {COMMAND}\n\n"
4021                "Send control commands to the init daemon.\n\n"
4022                "     --help      Show this help\n"
4023                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
4024                "Commands:\n"
4025                "  0              Power-off the machine\n"
4026                "  6              Reboot the machine\n"
4027                "  2, 3, 4, 5     Start runlevelX.target unit\n"
4028                "  1, s, S        Enter rescue mode\n"
4029                "  q, Q           Reload init daemon configuration\n"
4030                "  u, U           Reexecute init daemon\n",
4031                program_invocation_short_name);
4032
4033         return 0;
4034 }
4035
4036 static int runlevel_help(void) {
4037
4038         printf("%s [OPTIONS...]\n\n"
4039                "Prints the previous and current runlevel of the init system.\n\n"
4040                "     --help      Show this help\n",
4041                program_invocation_short_name);
4042
4043         return 0;
4044 }
4045
4046 static int systemctl_parse_argv(int argc, char *argv[]) {
4047
4048         enum {
4049                 ARG_FAIL = 0x100,
4050                 ARG_IGNORE_DEPENDENCIES,
4051                 ARG_VERSION,
4052                 ARG_USER,
4053                 ARG_SYSTEM,
4054                 ARG_GLOBAL,
4055                 ARG_NO_BLOCK,
4056                 ARG_NO_PAGER,
4057                 ARG_NO_WALL,
4058                 ARG_ORDER,
4059                 ARG_REQUIRE,
4060                 ARG_ROOT,
4061                 ARG_FULL,
4062                 ARG_NO_RELOAD,
4063                 ARG_KILL_MODE,
4064                 ARG_KILL_WHO,
4065                 ARG_NO_ASK_PASSWORD,
4066                 ARG_FAILED,
4067                 ARG_RUNTIME
4068         };
4069
4070         static const struct option options[] = {
4071                 { "help",      no_argument,       NULL, 'h'           },
4072                 { "version",   no_argument,       NULL, ARG_VERSION   },
4073                 { "type",      required_argument, NULL, 't'           },
4074                 { "property",  required_argument, NULL, 'p'           },
4075                 { "all",       no_argument,       NULL, 'a'           },
4076                 { "failed",    no_argument,       NULL, ARG_FAILED    },
4077                 { "full",      no_argument,       NULL, ARG_FULL      },
4078                 { "fail",      no_argument,       NULL, ARG_FAIL      },
4079                 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
4080                 { "user",      no_argument,       NULL, ARG_USER      },
4081                 { "system",    no_argument,       NULL, ARG_SYSTEM    },
4082                 { "global",    no_argument,       NULL, ARG_GLOBAL    },
4083                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
4084                 { "no-pager",  no_argument,       NULL, ARG_NO_PAGER  },
4085                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL   },
4086                 { "quiet",     no_argument,       NULL, 'q'           },
4087                 { "order",     no_argument,       NULL, ARG_ORDER     },
4088                 { "require",   no_argument,       NULL, ARG_REQUIRE   },
4089                 { "root",      required_argument, NULL, ARG_ROOT      },
4090                 { "force",     no_argument,       NULL, 'f'           },
4091                 { "no-reload", no_argument,       NULL, ARG_NO_RELOAD },
4092                 { "kill-mode", required_argument, NULL, ARG_KILL_MODE }, /* undocumented on purpose */
4093                 { "kill-who",  required_argument, NULL, ARG_KILL_WHO  },
4094                 { "signal",    required_argument, NULL, 's'           },
4095                 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
4096                 { "host",      required_argument, NULL, 'H'           },
4097                 { "privileged",no_argument,       NULL, 'P'           },
4098                 { "runtime",   no_argument,       NULL, ARG_RUNTIME   },
4099                 { NULL,        0,                 NULL, 0             }
4100         };
4101
4102         int c;
4103
4104         assert(argc >= 0);
4105         assert(argv);
4106
4107         /* Only when running as systemctl we ask for passwords */
4108         arg_ask_password = true;
4109
4110         while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
4111
4112                 switch (c) {
4113
4114                 case 'h':
4115                         systemctl_help();
4116                         return 0;
4117
4118                 case ARG_VERSION:
4119                         puts(PACKAGE_STRING);
4120                         puts(DISTRIBUTION);
4121                         puts(SYSTEMD_FEATURES);
4122                         return 0;
4123
4124                 case 't':
4125                         arg_type = optarg;
4126                         break;
4127
4128                 case 'p': {
4129                         char **l;
4130
4131                         if (!(l = strv_append(arg_property, optarg)))
4132                                 return -ENOMEM;
4133
4134                         strv_free(arg_property);
4135                         arg_property = l;
4136
4137                         /* If the user asked for a particular
4138                          * property, show it to him, even if it is
4139                          * empty. */
4140                         arg_all = true;
4141                         break;
4142                 }
4143
4144                 case 'a':
4145                         arg_all = true;
4146                         break;
4147
4148                 case ARG_FAIL:
4149                         arg_job_mode = "fail";
4150                         break;
4151
4152                 case ARG_IGNORE_DEPENDENCIES:
4153                         arg_job_mode = "ignore-dependencies";
4154                         break;
4155
4156                 case ARG_USER:
4157                         arg_scope = UNIT_FILE_USER;
4158                         break;
4159
4160                 case ARG_SYSTEM:
4161                         arg_scope = UNIT_FILE_SYSTEM;
4162                         break;
4163
4164                 case ARG_GLOBAL:
4165                         arg_scope = UNIT_FILE_GLOBAL;
4166                         break;
4167
4168                 case ARG_NO_BLOCK:
4169                         arg_no_block = true;
4170                         break;
4171
4172                 case ARG_NO_PAGER:
4173                         arg_no_pager = true;
4174                         break;
4175
4176                 case ARG_NO_WALL:
4177                         arg_no_wall = true;
4178                         break;
4179
4180                 case ARG_ORDER:
4181                         arg_dot = DOT_ORDER;
4182                         break;
4183
4184                 case ARG_REQUIRE:
4185                         arg_dot = DOT_REQUIRE;
4186                         break;
4187
4188                 case ARG_ROOT:
4189                         arg_root = optarg;
4190                         break;
4191
4192                 case ARG_FULL:
4193                         arg_full = true;
4194                         break;
4195
4196                 case ARG_FAILED:
4197                         arg_failed = true;
4198                         break;
4199
4200                 case 'q':
4201                         arg_quiet = true;
4202                         break;
4203
4204                 case 'f':
4205                         arg_force = true;
4206                         break;
4207
4208                 case ARG_NO_RELOAD:
4209                         arg_no_reload = true;
4210                         break;
4211
4212                 case ARG_KILL_WHO:
4213                         arg_kill_who = optarg;
4214                         break;
4215
4216                 case ARG_KILL_MODE:
4217                         arg_kill_mode = optarg;
4218                         break;
4219
4220                 case 's':
4221                         if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4222                                 log_error("Failed to parse signal string %s.", optarg);
4223                                 return -EINVAL;
4224                         }
4225                         break;
4226
4227                 case ARG_NO_ASK_PASSWORD:
4228                         arg_ask_password = false;
4229                         break;
4230
4231                 case 'P':
4232                         arg_transport = TRANSPORT_POLKIT;
4233                         break;
4234
4235                 case 'H':
4236                         arg_transport = TRANSPORT_SSH;
4237                         arg_host = optarg;
4238                         break;
4239
4240                 case ARG_RUNTIME:
4241                         arg_runtime = true;
4242                         break;
4243
4244                 case '?':
4245                         return -EINVAL;
4246
4247                 default:
4248                         log_error("Unknown option code %c", c);
4249                         return -EINVAL;
4250                 }
4251         }
4252
4253         if (arg_transport != TRANSPORT_NORMAL && arg_scope != UNIT_FILE_SYSTEM) {
4254                 log_error("Cannot access user instance remotely.");
4255                 return -EINVAL;
4256         }
4257
4258         return 1;
4259 }
4260
4261 static int halt_parse_argv(int argc, char *argv[]) {
4262
4263         enum {
4264                 ARG_HELP = 0x100,
4265                 ARG_HALT,
4266                 ARG_REBOOT,
4267                 ARG_NO_WALL
4268         };
4269
4270         static const struct option options[] = {
4271                 { "help",      no_argument,       NULL, ARG_HELP    },
4272                 { "halt",      no_argument,       NULL, ARG_HALT    },
4273                 { "poweroff",  no_argument,       NULL, 'p'         },
4274                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
4275                 { "force",     no_argument,       NULL, 'f'         },
4276                 { "wtmp-only", no_argument,       NULL, 'w'         },
4277                 { "no-wtmp",   no_argument,       NULL, 'd'         },
4278                 { "no-sync",   no_argument,       NULL, 'n'         },
4279                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4280                 { NULL,        0,                 NULL, 0           }
4281         };
4282
4283         int c, runlevel;
4284
4285         assert(argc >= 0);
4286         assert(argv);
4287
4288         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4289                 if (runlevel == '0' || runlevel == '6')
4290                         arg_immediate = true;
4291
4292         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4293                 switch (c) {
4294
4295                 case ARG_HELP:
4296                         halt_help();
4297                         return 0;
4298
4299                 case ARG_HALT:
4300                         arg_action = ACTION_HALT;
4301                         break;
4302
4303                 case 'p':
4304                         if (arg_action != ACTION_REBOOT)
4305                                 arg_action = ACTION_POWEROFF;
4306                         break;
4307
4308                 case ARG_REBOOT:
4309                         arg_action = ACTION_REBOOT;
4310                         break;
4311
4312                 case 'f':
4313                         arg_immediate = true;
4314                         break;
4315
4316                 case 'w':
4317                         arg_dry = true;
4318                         break;
4319
4320                 case 'd':
4321                         arg_no_wtmp = true;
4322                         break;
4323
4324                 case 'n':
4325                         arg_no_sync = true;
4326                         break;
4327
4328                 case ARG_NO_WALL:
4329                         arg_no_wall = true;
4330                         break;
4331
4332                 case 'i':
4333                 case 'h':
4334                         /* Compatibility nops */
4335                         break;
4336
4337                 case '?':
4338                         return -EINVAL;
4339
4340                 default:
4341                         log_error("Unknown option code %c", c);
4342                         return -EINVAL;
4343                 }
4344         }
4345
4346         if (optind < argc) {
4347                 log_error("Too many arguments.");
4348                 return -EINVAL;
4349         }
4350
4351         return 1;
4352 }
4353
4354 static int parse_time_spec(const char *t, usec_t *_u) {
4355         assert(t);
4356         assert(_u);
4357
4358         if (streq(t, "now"))
4359                 *_u = 0;
4360         else if (!strchr(t, ':')) {
4361                 uint64_t u;
4362
4363                 if (safe_atou64(t, &u) < 0)
4364                         return -EINVAL;
4365
4366                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4367         } else {
4368                 char *e = NULL;
4369                 long hour, minute;
4370                 struct tm tm;
4371                 time_t s;
4372                 usec_t n;
4373
4374                 errno = 0;
4375                 hour = strtol(t, &e, 10);
4376                 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4377                         return -EINVAL;
4378
4379                 minute = strtol(e+1, &e, 10);
4380                 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4381                         return -EINVAL;
4382
4383                 n = now(CLOCK_REALTIME);
4384                 s = (time_t) (n / USEC_PER_SEC);
4385
4386                 zero(tm);
4387                 assert_se(localtime_r(&s, &tm));
4388
4389                 tm.tm_hour = (int) hour;
4390                 tm.tm_min = (int) minute;
4391                 tm.tm_sec = 0;
4392
4393                 assert_se(s = mktime(&tm));
4394
4395                 *_u = (usec_t) s * USEC_PER_SEC;
4396
4397                 while (*_u <= n)
4398                         *_u += USEC_PER_DAY;
4399         }
4400
4401         return 0;
4402 }
4403
4404 static bool kexec_loaded(void) {
4405        bool loaded = false;
4406        char *s;
4407
4408        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4409                if (s[0] == '1')
4410                        loaded = true;
4411                free(s);
4412        }
4413        return loaded;
4414 }
4415
4416 static int shutdown_parse_argv(int argc, char *argv[]) {
4417
4418         enum {
4419                 ARG_HELP = 0x100,
4420                 ARG_NO_WALL
4421         };
4422
4423         static const struct option options[] = {
4424                 { "help",      no_argument,       NULL, ARG_HELP    },
4425                 { "halt",      no_argument,       NULL, 'H'         },
4426                 { "poweroff",  no_argument,       NULL, 'P'         },
4427                 { "reboot",    no_argument,       NULL, 'r'         },
4428                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4429                 { NULL,        0,                 NULL, 0           }
4430         };
4431
4432         int c, r;
4433
4434         assert(argc >= 0);
4435         assert(argv);
4436
4437         while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
4438                 switch (c) {
4439
4440                 case ARG_HELP:
4441                         shutdown_help();
4442                         return 0;
4443
4444                 case 'H':
4445                         arg_action = ACTION_HALT;
4446                         break;
4447
4448                 case 'P':
4449                         arg_action = ACTION_POWEROFF;
4450                         break;
4451
4452                 case 'r':
4453                         if (kexec_loaded())
4454                                 arg_action = ACTION_KEXEC;
4455                         else
4456                                 arg_action = ACTION_REBOOT;
4457                         break;
4458
4459                 case 'h':
4460                         if (arg_action != ACTION_HALT)
4461                                 arg_action = ACTION_POWEROFF;
4462                         break;
4463
4464                 case 'k':
4465                         arg_dry = true;
4466                         break;
4467
4468                 case ARG_NO_WALL:
4469                         arg_no_wall = true;
4470                         break;
4471
4472                 case 't':
4473                 case 'a':
4474                         /* Compatibility nops */
4475                         break;
4476
4477                 case 'c':
4478                         arg_action = ACTION_CANCEL_SHUTDOWN;
4479                         break;
4480
4481                 case '?':
4482                         return -EINVAL;
4483
4484                 default:
4485                         log_error("Unknown option code %c", c);
4486                         return -EINVAL;
4487                 }
4488         }
4489
4490         if (argc > optind) {
4491                 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4492                         log_error("Failed to parse time specification: %s", argv[optind]);
4493                         return r;
4494                 }
4495         } else
4496                 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
4497
4498         /* We skip the time argument */
4499         if (argc > optind + 1)
4500                 arg_wall = argv + optind + 1;
4501
4502         optind = argc;
4503
4504         return 1;
4505 }
4506
4507 static int telinit_parse_argv(int argc, char *argv[]) {
4508
4509         enum {
4510                 ARG_HELP = 0x100,
4511                 ARG_NO_WALL
4512         };
4513
4514         static const struct option options[] = {
4515                 { "help",      no_argument,       NULL, ARG_HELP    },
4516                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
4517                 { NULL,        0,                 NULL, 0           }
4518         };
4519
4520         static const struct {
4521                 char from;
4522                 enum action to;
4523         } table[] = {
4524                 { '0', ACTION_POWEROFF },
4525                 { '6', ACTION_REBOOT },
4526                 { '1', ACTION_RESCUE },
4527                 { '2', ACTION_RUNLEVEL2 },
4528                 { '3', ACTION_RUNLEVEL3 },
4529                 { '4', ACTION_RUNLEVEL4 },
4530                 { '5', ACTION_RUNLEVEL5 },
4531                 { 's', ACTION_RESCUE },
4532                 { 'S', ACTION_RESCUE },
4533                 { 'q', ACTION_RELOAD },
4534                 { 'Q', ACTION_RELOAD },
4535                 { 'u', ACTION_REEXEC },
4536                 { 'U', ACTION_REEXEC }
4537         };
4538
4539         unsigned i;
4540         int c;
4541
4542         assert(argc >= 0);
4543         assert(argv);
4544
4545         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4546                 switch (c) {
4547
4548                 case ARG_HELP:
4549                         telinit_help();
4550                         return 0;
4551
4552                 case ARG_NO_WALL:
4553                         arg_no_wall = true;
4554                         break;
4555
4556                 case '?':
4557                         return -EINVAL;
4558
4559                 default:
4560                         log_error("Unknown option code %c", c);
4561                         return -EINVAL;
4562                 }
4563         }
4564
4565         if (optind >= argc) {
4566                 telinit_help();
4567                 return -EINVAL;
4568         }
4569
4570         if (optind + 1 < argc) {
4571                 log_error("Too many arguments.");
4572                 return -EINVAL;
4573         }
4574
4575         if (strlen(argv[optind]) != 1) {
4576                 log_error("Expected single character argument.");
4577                 return -EINVAL;
4578         }
4579
4580         for (i = 0; i < ELEMENTSOF(table); i++)
4581                 if (table[i].from == argv[optind][0])
4582                         break;
4583
4584         if (i >= ELEMENTSOF(table)) {
4585                 log_error("Unknown command %s.", argv[optind]);
4586                 return -EINVAL;
4587         }
4588
4589         arg_action = table[i].to;
4590
4591         optind ++;
4592
4593         return 1;
4594 }
4595
4596 static int runlevel_parse_argv(int argc, char *argv[]) {
4597
4598         enum {
4599                 ARG_HELP = 0x100,
4600         };
4601
4602         static const struct option options[] = {
4603                 { "help",      no_argument,       NULL, ARG_HELP    },
4604                 { NULL,        0,                 NULL, 0           }
4605         };
4606
4607         int c;
4608
4609         assert(argc >= 0);
4610         assert(argv);
4611
4612         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4613                 switch (c) {
4614
4615                 case ARG_HELP:
4616                         runlevel_help();
4617                         return 0;
4618
4619                 case '?':
4620                         return -EINVAL;
4621
4622                 default:
4623                         log_error("Unknown option code %c", c);
4624                         return -EINVAL;
4625                 }
4626         }
4627
4628         if (optind < argc) {
4629                 log_error("Too many arguments.");
4630                 return -EINVAL;
4631         }
4632
4633         return 1;
4634 }
4635
4636 static int parse_argv(int argc, char *argv[]) {
4637         assert(argc >= 0);
4638         assert(argv);
4639
4640         if (program_invocation_short_name) {
4641
4642                 if (strstr(program_invocation_short_name, "halt")) {
4643                         arg_action = ACTION_HALT;
4644                         return halt_parse_argv(argc, argv);
4645                 } else if (strstr(program_invocation_short_name, "poweroff")) {
4646                         arg_action = ACTION_POWEROFF;
4647                         return halt_parse_argv(argc, argv);
4648                 } else if (strstr(program_invocation_short_name, "reboot")) {
4649                         if (kexec_loaded())
4650                                 arg_action = ACTION_KEXEC;
4651                         else
4652                                 arg_action = ACTION_REBOOT;
4653                         return halt_parse_argv(argc, argv);
4654                 } else if (strstr(program_invocation_short_name, "shutdown")) {
4655                         arg_action = ACTION_POWEROFF;
4656                         return shutdown_parse_argv(argc, argv);
4657                 } else if (strstr(program_invocation_short_name, "init")) {
4658
4659                         if (sd_booted() > 0) {
4660                                 arg_action = ACTION_INVALID;
4661                                 return telinit_parse_argv(argc, argv);
4662                         } else {
4663                                 /* Hmm, so some other init system is
4664                                  * running, we need to forward this
4665                                  * request to it. For now we simply
4666                                  * guess that it is Upstart. */
4667
4668                                 execv("/lib/upstart/telinit", argv);
4669
4670                                 log_error("Couldn't find an alternative telinit implementation to spawn.");
4671                                 return -EIO;
4672                         }
4673
4674                 } else if (strstr(program_invocation_short_name, "runlevel")) {
4675                         arg_action = ACTION_RUNLEVEL;
4676                         return runlevel_parse_argv(argc, argv);
4677                 }
4678         }
4679
4680         arg_action = ACTION_SYSTEMCTL;
4681         return systemctl_parse_argv(argc, argv);
4682 }
4683
4684 static int action_to_runlevel(void) {
4685
4686         static const char table[_ACTION_MAX] = {
4687                 [ACTION_HALT] =      '0',
4688                 [ACTION_POWEROFF] =  '0',
4689                 [ACTION_REBOOT] =    '6',
4690                 [ACTION_RUNLEVEL2] = '2',
4691                 [ACTION_RUNLEVEL3] = '3',
4692                 [ACTION_RUNLEVEL4] = '4',
4693                 [ACTION_RUNLEVEL5] = '5',
4694                 [ACTION_RESCUE] =    '1'
4695         };
4696
4697         assert(arg_action < _ACTION_MAX);
4698
4699         return table[arg_action];
4700 }
4701
4702 static int talk_upstart(void) {
4703         DBusMessage *m = NULL, *reply = NULL;
4704         DBusError error;
4705         int previous, rl, r;
4706         char
4707                 env1_buf[] = "RUNLEVEL=X",
4708                 env2_buf[] = "PREVLEVEL=X";
4709         char *env1 = env1_buf, *env2 = env2_buf;
4710         const char *emit = "runlevel";
4711         dbus_bool_t b_false = FALSE;
4712         DBusMessageIter iter, sub;
4713         DBusConnection *bus;
4714
4715         dbus_error_init(&error);
4716
4717         if (!(rl = action_to_runlevel()))
4718                 return 0;
4719
4720         if (utmp_get_runlevel(&previous, NULL) < 0)
4721                 previous = 'N';
4722
4723         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
4724                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
4725                         r = 0;
4726                         goto finish;
4727                 }
4728
4729                 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
4730                 r = -EIO;
4731                 goto finish;
4732         }
4733
4734         if ((r = bus_check_peercred(bus)) < 0) {
4735                 log_error("Failed to verify owner of bus.");
4736                 goto finish;
4737         }
4738
4739         if (!(m = dbus_message_new_method_call(
4740                               "com.ubuntu.Upstart",
4741                               "/com/ubuntu/Upstart",
4742                               "com.ubuntu.Upstart0_6",
4743                               "EmitEvent"))) {
4744
4745                 log_error("Could not allocate message.");
4746                 r = -ENOMEM;
4747                 goto finish;
4748         }
4749
4750         dbus_message_iter_init_append(m, &iter);
4751
4752         env1_buf[sizeof(env1_buf)-2] = rl;
4753         env2_buf[sizeof(env2_buf)-2] = previous;
4754
4755         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
4756             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
4757             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
4758             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
4759             !dbus_message_iter_close_container(&iter, &sub) ||
4760             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
4761                 log_error("Could not append arguments to message.");
4762                 r = -ENOMEM;
4763                 goto finish;
4764         }
4765
4766         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4767
4768                 if (error_is_no_service(&error)) {
4769                         r = -EADDRNOTAVAIL;
4770                         goto finish;
4771                 }
4772
4773                 log_error("Failed to issue method call: %s", bus_error_message(&error));
4774                 r = -EIO;
4775                 goto finish;
4776         }
4777
4778         r = 1;
4779
4780 finish:
4781         if (m)
4782                 dbus_message_unref(m);
4783
4784         if (reply)
4785                 dbus_message_unref(reply);
4786
4787         if (bus) {
4788                 dbus_connection_flush(bus);
4789                 dbus_connection_close(bus);
4790                 dbus_connection_unref(bus);
4791         }
4792
4793         dbus_error_free(&error);
4794
4795         return r;
4796 }
4797
4798 static int talk_initctl(void) {
4799         struct init_request request;
4800         int r, fd;
4801         char rl;
4802
4803         if (!(rl = action_to_runlevel()))
4804                 return 0;
4805
4806         zero(request);
4807         request.magic = INIT_MAGIC;
4808         request.sleeptime = 0;
4809         request.cmd = INIT_CMD_RUNLVL;
4810         request.runlevel = rl;
4811
4812         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
4813
4814                 if (errno == ENOENT)
4815                         return 0;
4816
4817                 log_error("Failed to open "INIT_FIFO": %m");
4818                 return -errno;
4819         }
4820
4821         errno = 0;
4822         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
4823         close_nointr_nofail(fd);
4824
4825         if (r < 0) {
4826                 log_error("Failed to write to "INIT_FIFO": %m");
4827                 return errno ? -errno : -EIO;
4828         }
4829
4830         return 1;
4831 }
4832
4833 static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
4834
4835         static const struct {
4836                 const char* verb;
4837                 const enum {
4838                         MORE,
4839                         LESS,
4840                         EQUAL
4841                 } argc_cmp;
4842                 const int argc;
4843                 int (* const dispatch)(DBusConnection *bus, char **args);
4844         } verbs[] = {
4845                 { "list-units",            LESS,  1, list_units        },
4846                 { "list-unit-files",       EQUAL, 1, list_unit_files   },
4847                 { "list-jobs",             EQUAL, 1, list_jobs         },
4848                 { "clear-jobs",            EQUAL, 1, daemon_reload     },
4849                 { "load",                  MORE,  2, load_unit         },
4850                 { "cancel",                MORE,  2, cancel_job        },
4851                 { "start",                 MORE,  2, start_unit        },
4852                 { "stop",                  MORE,  2, start_unit        },
4853                 { "condstop",              MORE,  2, start_unit        }, /* For compatibility with ALTLinux */
4854                 { "reload",                MORE,  2, start_unit        },
4855                 { "restart",               MORE,  2, start_unit        },
4856                 { "try-restart",           MORE,  2, start_unit        },
4857                 { "reload-or-restart",     MORE,  2, start_unit        },
4858                 { "reload-or-try-restart", MORE,  2, start_unit        },
4859                 { "force-reload",          MORE,  2, start_unit        }, /* For compatibility with SysV */
4860                 { "condreload",            MORE,  2, start_unit        }, /* For compatibility with ALTLinux */
4861                 { "condrestart",           MORE,  2, start_unit        }, /* For compatibility with RH */
4862                 { "isolate",               EQUAL, 2, start_unit        },
4863                 { "kill",                  MORE,  2, kill_unit         },
4864                 { "is-active",             MORE,  2, check_unit        },
4865                 { "check",                 MORE,  2, check_unit        },
4866                 { "show",                  MORE,  1, show              },
4867                 { "status",                MORE,  2, show              },
4868                 { "dump",                  EQUAL, 1, dump              },
4869                 { "dot",                   EQUAL, 1, dot               },
4870                 { "snapshot",              LESS,  2, snapshot          },
4871                 { "delete",                MORE,  2, delete_snapshot   },
4872                 { "daemon-reload",         EQUAL, 1, daemon_reload     },
4873                 { "daemon-reexec",         EQUAL, 1, daemon_reload     },
4874                 { "show-environment",      EQUAL, 1, show_enviroment   },
4875                 { "set-environment",       MORE,  2, set_environment   },
4876                 { "unset-environment",     MORE,  2, set_environment   },
4877                 { "halt",                  EQUAL, 1, start_special     },
4878                 { "poweroff",              EQUAL, 1, start_special     },
4879                 { "reboot",                EQUAL, 1, start_special     },
4880                 { "kexec",                 EQUAL, 1, start_special     },
4881                 { "default",               EQUAL, 1, start_special     },
4882                 { "rescue",                EQUAL, 1, start_special     },
4883                 { "emergency",             EQUAL, 1, start_special     },
4884                 { "exit",                  EQUAL, 1, start_special     },
4885                 { "reset-failed",          MORE,  1, reset_failed      },
4886                 { "enable",                MORE,  2, enable_unit       },
4887                 { "disable",               MORE,  2, enable_unit       },
4888                 { "is-enabled",            MORE,  2, unit_is_enabled   },
4889                 { "reenable",              MORE,  2, enable_unit       },
4890                 { "preset",                MORE,  2, enable_unit       },
4891                 { "mask",                  MORE,  2, enable_unit       },
4892                 { "unmask",                MORE,  2, enable_unit       },
4893                 { "link",                  MORE,  2, enable_unit       }
4894         };
4895
4896         int left;
4897         unsigned i;
4898
4899         assert(argc >= 0);
4900         assert(argv);
4901         assert(error);
4902
4903         left = argc - optind;
4904
4905         if (left <= 0)
4906                 /* Special rule: no arguments means "list-units" */
4907                 i = 0;
4908         else {
4909                 if (streq(argv[optind], "help")) {
4910                         systemctl_help();
4911                         return 0;
4912                 }
4913
4914                 for (i = 0; i < ELEMENTSOF(verbs); i++)
4915                         if (streq(argv[optind], verbs[i].verb))
4916                                 break;
4917
4918                 if (i >= ELEMENTSOF(verbs)) {
4919                         log_error("Unknown operation %s", argv[optind]);
4920                         return -EINVAL;
4921                 }
4922         }
4923
4924         switch (verbs[i].argc_cmp) {
4925
4926         case EQUAL:
4927                 if (left != verbs[i].argc) {
4928                         log_error("Invalid number of arguments.");
4929                         return -EINVAL;
4930                 }
4931
4932                 break;
4933
4934         case MORE:
4935                 if (left < verbs[i].argc) {
4936                         log_error("Too few arguments.");
4937                         return -EINVAL;
4938                 }
4939
4940                 break;
4941
4942         case LESS:
4943                 if (left > verbs[i].argc) {
4944                         log_error("Too many arguments.");
4945                         return -EINVAL;
4946                 }
4947
4948                 break;
4949
4950         default:
4951                 assert_not_reached("Unknown comparison operator.");
4952         }
4953
4954         /* Require a bus connection for all operations but
4955          * enable/disable */
4956         if (!streq(verbs[i].verb, "enable") &&
4957             !streq(verbs[i].verb, "disable") &&
4958             !streq(verbs[i].verb, "is-enable") &&
4959             !streq(verbs[i].verb, "reenable") &&
4960             !streq(verbs[i].verb, "preset") &&
4961             !streq(verbs[i].verb, "mask") &&
4962             !streq(verbs[i].verb, "unmask") &&
4963             !streq(verbs[i].verb, "link")) {
4964
4965                 if (running_in_chroot() > 0) {
4966                         log_info("Running in chroot, ignoring request.");
4967                         return 0;
4968                 }
4969
4970                 if (!bus && !avoid_bus()) {
4971                         log_error("Failed to get D-Bus connection: %s", error->message);
4972                         return -EIO;
4973                 }
4974         }
4975
4976         return verbs[i].dispatch(bus, argv + optind);
4977 }
4978
4979 static int send_shutdownd(usec_t t, char mode, bool dry_run, bool warn, const char *message) {
4980         int fd = -1;
4981         struct msghdr msghdr;
4982         struct iovec iovec;
4983         union sockaddr_union sockaddr;
4984         struct shutdownd_command c;
4985
4986         zero(c);
4987         c.elapse = t;
4988         c.mode = mode;
4989         c.dry_run = dry_run;
4990         c.warn_wall = warn;
4991
4992         if (message)
4993                 strncpy(c.wall_message, message, sizeof(c.wall_message));
4994
4995         if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
4996                 return -errno;
4997
4998         zero(sockaddr);
4999         sockaddr.sa.sa_family = AF_UNIX;
5000         sockaddr.un.sun_path[0] = 0;
5001         strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
5002
5003         zero(iovec);
5004         iovec.iov_base = (char*) &c;
5005         iovec.iov_len = sizeof(c);
5006
5007         zero(msghdr);
5008         msghdr.msg_name = &sockaddr;
5009         msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
5010
5011         msghdr.msg_iov = &iovec;
5012         msghdr.msg_iovlen = 1;
5013
5014         if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5015                 close_nointr_nofail(fd);
5016                 return -errno;
5017         }
5018
5019         close_nointr_nofail(fd);
5020         return 0;
5021 }
5022
5023 static int reload_with_fallback(DBusConnection *bus) {
5024
5025         if (bus) {
5026                 /* First, try systemd via D-Bus. */
5027                 if (daemon_reload(bus, NULL) > 0)
5028                         return 0;
5029         }
5030
5031         /* Nothing else worked, so let's try signals */
5032         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5033
5034         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5035                 log_error("kill() failed: %m");
5036                 return -errno;
5037         }
5038
5039         return 0;
5040 }
5041
5042 static int start_with_fallback(DBusConnection *bus) {
5043
5044         if (bus) {
5045                 /* First, try systemd via D-Bus. */
5046                 if (start_unit(bus, NULL) >= 0)
5047                         goto done;
5048         }
5049
5050         /* Hmm, talking to systemd via D-Bus didn't work. Then
5051          * let's try to talk to Upstart via D-Bus. */
5052         if (talk_upstart() > 0)
5053                 goto done;
5054
5055         /* Nothing else worked, so let's try
5056          * /dev/initctl */
5057         if (talk_initctl() > 0)
5058                 goto done;
5059
5060         log_error("Failed to talk to init daemon.");
5061         return -EIO;
5062
5063 done:
5064         warn_wall(arg_action);
5065         return 0;
5066 }
5067
5068 static int halt_main(DBusConnection *bus) {
5069         int r;
5070
5071         if (geteuid() != 0) {
5072                 log_error("Must be root.");
5073                 return -EPERM;
5074         }
5075
5076         if (arg_when > 0) {
5077                 char *m;
5078                 char date[FORMAT_TIMESTAMP_MAX];
5079
5080                 m = strv_join(arg_wall, " ");
5081                 r = send_shutdownd(arg_when,
5082                                    arg_action == ACTION_HALT     ? 'H' :
5083                                    arg_action == ACTION_POWEROFF ? 'P' :
5084                                                                    'r',
5085                                    arg_dry,
5086                                    !arg_no_wall,
5087                                    m);
5088                 free(m);
5089
5090                 if (r < 0)
5091                         log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
5092                 else {
5093                         log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5094                                  format_timestamp(date, sizeof(date), arg_when));
5095                         return 0;
5096                 }
5097         }
5098
5099         if (!arg_dry && !arg_immediate)
5100                 return start_with_fallback(bus);
5101
5102         if (!arg_no_wtmp) {
5103                 if (sd_booted() > 0)
5104                         log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5105                 else if ((r = utmp_put_shutdown(0)) < 0)
5106                         log_warning("Failed to write utmp record: %s", strerror(-r));
5107         }
5108
5109         if (!arg_no_sync)
5110                 sync();
5111
5112         if (arg_dry)
5113                 return 0;
5114
5115         /* Make sure C-A-D is handled by the kernel from this
5116          * point on... */
5117         reboot(RB_ENABLE_CAD);
5118
5119         switch (arg_action) {
5120
5121         case ACTION_HALT:
5122                 log_info("Halting.");
5123                 reboot(RB_HALT_SYSTEM);
5124                 break;
5125
5126         case ACTION_POWEROFF:
5127                 log_info("Powering off.");
5128                 reboot(RB_POWER_OFF);
5129                 break;
5130
5131         case ACTION_REBOOT:
5132                 log_info("Rebooting.");
5133                 reboot(RB_AUTOBOOT);
5134                 break;
5135
5136         default:
5137                 assert_not_reached("Unknown halt action.");
5138         }
5139
5140         /* We should never reach this. */
5141         return -ENOSYS;
5142 }
5143
5144 static int runlevel_main(void) {
5145         int r, runlevel, previous;
5146
5147         r = utmp_get_runlevel(&runlevel, &previous);
5148         if (r < 0) {
5149                 puts("unknown");
5150                 return r;
5151         }
5152
5153         printf("%c %c\n",
5154                previous <= 0 ? 'N' : previous,
5155                runlevel <= 0 ? 'N' : runlevel);
5156
5157         return 0;
5158 }
5159
5160 int main(int argc, char*argv[]) {
5161         int r, retval = EXIT_FAILURE;
5162         DBusConnection *bus = NULL;
5163         DBusError error;
5164
5165         dbus_error_init(&error);
5166
5167         log_parse_environment();
5168         log_open();
5169
5170         if ((r = parse_argv(argc, argv)) < 0)
5171                 goto finish;
5172         else if (r == 0) {
5173                 retval = EXIT_SUCCESS;
5174                 goto finish;
5175         }
5176
5177         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5178          * let's shortcut this */
5179         if (arg_action == ACTION_RUNLEVEL) {
5180                 r = runlevel_main();
5181                 retval = r < 0 ? EXIT_FAILURE : r;
5182                 goto finish;
5183         }
5184
5185         if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5186                 log_info("Running in chroot, ignoring request.");
5187                 retval = 0;
5188                 goto finish;
5189         }
5190
5191         if (!avoid_bus()) {
5192                 if (arg_transport == TRANSPORT_NORMAL)
5193                         bus_connect(arg_scope == UNIT_FILE_SYSTEM ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, &bus, &private_bus, &error);
5194                 else if (arg_transport == TRANSPORT_POLKIT) {
5195                         bus_connect_system_polkit(&bus, &error);
5196                         private_bus = false;
5197                 } else if (arg_transport == TRANSPORT_SSH) {
5198                         bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5199                         private_bus = false;
5200                 } else
5201                         assert_not_reached("Uh, invalid transport...");
5202         }
5203
5204         switch (arg_action) {
5205
5206         case ACTION_SYSTEMCTL:
5207                 r = systemctl_main(bus, argc, argv, &error);
5208                 break;
5209
5210         case ACTION_HALT:
5211         case ACTION_POWEROFF:
5212         case ACTION_REBOOT:
5213         case ACTION_KEXEC:
5214                 r = halt_main(bus);
5215                 break;
5216
5217         case ACTION_RUNLEVEL2:
5218         case ACTION_RUNLEVEL3:
5219         case ACTION_RUNLEVEL4:
5220         case ACTION_RUNLEVEL5:
5221         case ACTION_RESCUE:
5222         case ACTION_EMERGENCY:
5223         case ACTION_DEFAULT:
5224                 r = start_with_fallback(bus);
5225                 break;
5226
5227         case ACTION_RELOAD:
5228         case ACTION_REEXEC:
5229                 r = reload_with_fallback(bus);
5230                 break;
5231
5232         case ACTION_CANCEL_SHUTDOWN:
5233                 r = send_shutdownd(0, 0, false, false, NULL);
5234                 break;
5235
5236         case ACTION_INVALID:
5237         case ACTION_RUNLEVEL:
5238         default:
5239                 assert_not_reached("Unknown action");
5240         }
5241
5242         retval = r < 0 ? EXIT_FAILURE : r;
5243
5244 finish:
5245         if (bus) {
5246                 dbus_connection_flush(bus);
5247                 dbus_connection_close(bus);
5248                 dbus_connection_unref(bus);
5249         }
5250
5251         dbus_error_free(&error);
5252
5253         dbus_shutdown();
5254
5255         strv_free(arg_property);
5256
5257         pager_close();
5258         agent_close();
5259
5260         return retval;
5261 }