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