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