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