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