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