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