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