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