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