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