chiark / gitweb /
a couple of fixes to make llvm-analyze quiet
[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,