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