chiark / gitweb /
bdfd0cdf87f52ac7e599727d94d6597e9a6b96d1
[elogind.git] / src / systemctl.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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
34 #include <dbus/dbus.h>
35
36 #include "log.h"
37 #include "util.h"
38 #include "macro.h"
39 #include "set.h"
40 #include "utmp-wtmp.h"
41 #include "special.h"
42 #include "initreq.h"
43 #include "strv.h"
44 #include "dbus-common.h"
45 #include "cgroup-show.h"
46 #include "cgroup-util.h"
47 #include "list.h"
48
49 static const char *arg_type = NULL;
50 static const char *arg_property = NULL;
51 static bool arg_all = false;
52 static bool arg_fail = false;
53 static bool arg_session = false;
54 static bool arg_no_block = false;
55 static bool arg_immediate = false;
56 static bool arg_no_wtmp = false;
57 static bool arg_no_sync = false;
58 static bool arg_no_wall = false;
59 static bool arg_dry = false;
60 static bool arg_quiet = false;
61 static char arg_full = false;
62 static char **arg_wall = NULL;
63 static enum action {
64         ACTION_INVALID,
65         ACTION_SYSTEMCTL,
66         ACTION_HALT,
67         ACTION_POWEROFF,
68         ACTION_REBOOT,
69         ACTION_RUNLEVEL2,
70         ACTION_RUNLEVEL3,
71         ACTION_RUNLEVEL4,
72         ACTION_RUNLEVEL5,
73         ACTION_RESCUE,
74         ACTION_EMERGENCY,
75         ACTION_DEFAULT,
76         ACTION_RELOAD,
77         ACTION_REEXEC,
78         ACTION_RUNLEVEL,
79         _ACTION_MAX
80 } arg_action = ACTION_SYSTEMCTL;
81 static enum dot {
82         DOT_ALL,
83         DOT_ORDER,
84         DOT_REQUIRE
85 } arg_dot = DOT_ALL;
86
87 static bool private_bus = false;
88
89 static bool error_is_no_service(DBusError *error) {
90
91         assert(error);
92
93         if (!dbus_error_is_set(error))
94                 return false;
95
96         if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
97                 return true;
98
99         if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
100                 return true;
101
102         return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
103 }
104
105 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
106
107         assert(iter);
108         assert(data);
109
110         if (dbus_message_iter_get_arg_type(iter) != type)
111                 return -EIO;
112
113         dbus_message_iter_get_basic(iter, data);
114
115         if (!dbus_message_iter_next(iter) != !next)
116                 return -EIO;
117
118         return 0;
119 }
120
121 static void warn_wall(enum action action) {
122         static const char *table[_ACTION_MAX] = {
123                 [ACTION_HALT]      = "The system is going down for system halt NOW!",
124                 [ACTION_REBOOT]    = "The system is going down for reboot NOW!",
125                 [ACTION_POWEROFF]  = "The system is going down for power-off NOW!",
126                 [ACTION_RESCUE]    = "The system is going down to rescue mode NOW!",
127                 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
128         };
129
130         if (arg_no_wall)
131                 return;
132
133         if (arg_wall) {
134                 char *p;
135
136                 if (!(p = strv_join(arg_wall, " "))) {
137                         log_error("Failed to join strings.");
138                         return;
139                 }
140
141                 if (*p) {
142                         utmp_wall(p);
143                         free(p);
144                         return;
145                 }
146
147                 free(p);
148         }
149
150         if (!table[action])
151                 return;
152
153         utmp_wall(table[action]);
154 }
155
156 static int list_units(DBusConnection *bus, char **args, unsigned n) {
157         DBusMessage *m = NULL, *reply = NULL;
158         DBusError error;
159         int r;
160         DBusMessageIter iter, sub, sub2;
161         unsigned k = 0;
162
163         dbus_error_init(&error);
164
165         assert(bus);
166
167         if (!(m = dbus_message_new_method_call(
168                               "org.freedesktop.systemd1",
169                               "/org/freedesktop/systemd1",
170                               "org.freedesktop.systemd1.Manager",
171                               "ListUnits"))) {
172                 log_error("Could not allocate message.");
173                 return -ENOMEM;
174         }
175
176         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
177                 log_error("Failed to issue method call: %s", error.message);
178                 r = -EIO;
179                 goto finish;
180         }
181
182         if (!dbus_message_iter_init(reply, &iter) ||
183             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
184             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
185                 log_error("Failed to parse reply.");
186                 r = -EIO;
187                 goto finish;
188         }
189
190         dbus_message_iter_recurse(&iter, &sub);
191
192         if (isatty(STDOUT_FILENO))
193                 printf("%-45s %-6s %-12s %-12s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
194
195         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
196                 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path, *job_type, *job_path, *dot;
197                 uint32_t job_id;
198
199                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
200                         log_error("Failed to parse reply.");
201                         r = -EIO;
202                         goto finish;
203                 }
204
205                 dbus_message_iter_recurse(&sub, &sub2);
206
207                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
208                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
209                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
210                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
211                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
212                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
213                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0 ||
214                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &job_id, true) < 0 ||
215                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &job_type, true) < 0 ||
216                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, false) < 0) {
217                         log_error("Failed to parse reply.");
218                         r = -EIO;
219                         goto finish;
220                 }
221
222                 if ((!arg_type || ((dot = strrchr(id, '.')) &&
223                                    streq(dot+1, arg_type))) &&
224                     (arg_all || !(streq(active_state, "inactive") || following[0]) || job_id > 0)) {
225                         char *e;
226                         int a = 0, b = 0;
227
228                         if (streq(active_state, "maintenance"))
229                                 fputs(ANSI_HIGHLIGHT_ON, stdout);
230
231                         e = arg_full ? NULL : ellipsize(id, 45, 33);
232                         printf("%-45s %-6s %-12s %-12s%n", e ? e : id, load_state, active_state, sub_state, &a);
233                         free(e);
234
235                         if (job_id != 0)
236                                 printf(" => %-12s%n", job_type, &b);
237                         else
238                                 b = 1 + 15;
239
240                         if (a + b + 2 < columns()) {
241                                 if (job_id == 0)
242                                         printf("                ");
243
244                                 printf(" %.*s", columns() - a - b - 2, description);
245                         }
246
247                         if (streq(active_state, "maintenance"))
248                                 fputs(ANSI_HIGHLIGHT_OFF, stdout);
249
250                         fputs("\n", stdout);
251                         k++;
252                 }
253
254                 dbus_message_iter_next(&sub);
255         }
256
257         if (isatty(STDOUT_FILENO)) {
258
259                 printf("\nLOAD   = Load State, reflects whether the unit configuration was properly loaded.\n"
260                        "ACTIVE = Active State, the high-level unit activation state, i.e. generalization of the substate.\n"
261                        "SUB    = Substate, the low-level unit activation state, possible values depend on unit type.\n"
262                        "JOB    = Job, shows pending jobs for the unit.\n");
263
264                 if (arg_all)
265                         printf("\n%u units listed.\n", k);
266                 else
267                         printf("\n%u units listed. Pass --all to see inactive units, too.\n", k);
268         }
269
270         r = 0;
271
272 finish:
273         if (m)
274                 dbus_message_unref(m);
275
276         if (reply)
277                 dbus_message_unref(reply);
278
279         dbus_error_free(&error);
280
281         return r;
282 }
283
284 static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
285         static const char * const colors[] = {
286                 "Requires",              "[color=\"black\"]",
287                 "RequiresOverridable",   "[color=\"black\"]",
288                 "Requisite",             "[color=\"darkblue\"]",
289                 "RequisiteOverridable",  "[color=\"darkblue\"]",
290                 "Wants",                 "[color=\"darkgrey\"]",
291                 "Conflicts",             "[color=\"red\"]",
292                 "After",                 "[color=\"green\"]"
293         };
294
295         const char *c = NULL;
296         unsigned i;
297
298         assert(name);
299         assert(prop);
300         assert(iter);
301
302         for (i = 0; i < ELEMENTSOF(colors); i += 2)
303                 if (streq(colors[i], prop)) {
304                         c = colors[i+1];
305                         break;
306                 }
307
308         if (!c)
309                 return 0;
310
311         if (arg_dot != DOT_ALL)
312                 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
313                         return 0;
314
315         switch (dbus_message_iter_get_arg_type(iter)) {
316
317         case DBUS_TYPE_ARRAY:
318
319                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
320                         DBusMessageIter sub;
321
322                         dbus_message_iter_recurse(iter, &sub);
323
324                         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
325                                 const char *s;
326
327                                 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
328                                 dbus_message_iter_get_basic(&sub, &s);
329                                 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
330
331                                 dbus_message_iter_next(&sub);
332                         }
333
334                         return 0;
335                 }
336         }
337
338         return 0;
339 }
340
341 static int dot_one(DBusConnection *bus, const char *name, const char *path) {
342         DBusMessage *m = NULL, *reply = NULL;
343         const char *interface = "org.freedesktop.systemd1.Unit";
344         int r;
345         DBusError error;
346         DBusMessageIter iter, sub, sub2, sub3;
347
348         assert(bus);
349         assert(path);
350
351         dbus_error_init(&error);
352
353         if (!(m = dbus_message_new_method_call(
354                               "org.freedesktop.systemd1",
355                               path,
356                               "org.freedesktop.DBus.Properties",
357                               "GetAll"))) {
358                 log_error("Could not allocate message.");
359                 r = -ENOMEM;
360                 goto finish;
361         }
362
363         if (!dbus_message_append_args(m,
364                                       DBUS_TYPE_STRING, &interface,
365                                       DBUS_TYPE_INVALID)) {
366                 log_error("Could not append arguments to message.");
367                 r = -ENOMEM;
368                 goto finish;
369         }
370
371         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
372                 log_error("Failed to issue method call: %s", error.message);
373                 r = -EIO;
374                 goto finish;
375         }
376
377         if (!dbus_message_iter_init(reply, &iter) ||
378             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
379             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
380                 log_error("Failed to parse reply.");
381                 r = -EIO;
382                 goto finish;
383         }
384
385         dbus_message_iter_recurse(&iter, &sub);
386
387         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
388                 const char *prop;
389
390                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
391                         log_error("Failed to parse reply.");
392                         r = -EIO;
393                         goto finish;
394                 }
395
396                 dbus_message_iter_recurse(&sub, &sub2);
397
398                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
399                         log_error("Failed to parse reply.");
400                         r = -EIO;
401                         goto finish;
402                 }
403
404                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
405                         log_error("Failed to parse reply.");
406                         r = -EIO;
407                         goto finish;
408                 }
409
410                 dbus_message_iter_recurse(&sub2, &sub3);
411
412                 if (dot_one_property(name, prop, &sub3)) {
413                         log_error("Failed to parse reply.");
414                         r = -EIO;
415                         goto finish;
416                 }
417
418                 dbus_message_iter_next(&sub);
419         }
420
421 finish:
422         if (m)
423                 dbus_message_unref(m);
424
425         if (reply)
426                 dbus_message_unref(reply);
427
428         dbus_error_free(&error);
429
430         return r;
431 }
432
433 static int dot(DBusConnection *bus, char **args, unsigned n) {
434         DBusMessage *m = NULL, *reply = NULL;
435         DBusError error;
436         int r;
437         DBusMessageIter iter, sub, sub2;
438
439         dbus_error_init(&error);
440
441         assert(bus);
442
443         if (!(m = dbus_message_new_method_call(
444                               "org.freedesktop.systemd1",
445                               "/org/freedesktop/systemd1",
446                               "org.freedesktop.systemd1.Manager",
447                               "ListUnits"))) {
448                 log_error("Could not allocate message.");
449                 return -ENOMEM;
450         }
451
452         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
453                 log_error("Failed to issue method call: %s", error.message);
454                 r = -EIO;
455                 goto finish;
456         }
457
458         if (!dbus_message_iter_init(reply, &iter) ||
459             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
460             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
461                 log_error("Failed to parse reply.");
462                 r = -EIO;
463                 goto finish;
464         }
465
466         printf("digraph systemd {\n");
467
468         dbus_message_iter_recurse(&iter, &sub);
469         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
470                 const char *id, *description, *load_state, *active_state, *sub_state, *unit_path;
471
472                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
473                         log_error("Failed to parse reply.");
474                         r = -EIO;
475                         goto finish;
476                 }
477
478                 dbus_message_iter_recurse(&sub, &sub2);
479
480                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
481                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
482                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
483                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
484                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
485                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
486                         log_error("Failed to parse reply.");
487                         r = -EIO;
488                         goto finish;
489                 }
490
491                 if ((r = dot_one(bus, id, unit_path)) < 0)
492                         goto finish;
493
494                 /* printf("\t\"%s\";\n", id); */
495                 dbus_message_iter_next(&sub);
496         }
497
498         printf("}\n");
499
500         log_info("   Color legend: black     = Requires\n"
501                  "                 dark blue = Requisite\n"
502                  "                 dark grey = Wants\n"
503                  "                 red       = Conflicts\n"
504                  "                 green     = After\n");
505
506         if (isatty(fileno(stdout)))
507                 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
508                            "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
509
510         r = 0;
511
512 finish:
513         if (m)
514                 dbus_message_unref(m);
515
516         if (reply)
517                 dbus_message_unref(reply);
518
519         dbus_error_free(&error);
520
521         return r;
522 }
523
524 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
525         DBusMessage *m = NULL, *reply = NULL;
526         DBusError error;
527         int r;
528         DBusMessageIter iter, sub, sub2;
529         unsigned k = 0;
530
531         dbus_error_init(&error);
532
533         assert(bus);
534
535         if (!(m = dbus_message_new_method_call(
536                               "org.freedesktop.systemd1",
537                               "/org/freedesktop/systemd1",
538                               "org.freedesktop.systemd1.Manager",
539                               "ListJobs"))) {
540                 log_error("Could not allocate message.");
541                 return -ENOMEM;
542         }
543
544         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
545                 log_error("Failed to issue method call: %s", error.message);
546                 r = -EIO;
547                 goto finish;
548         }
549
550         if (!dbus_message_iter_init(reply, &iter) ||
551             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
552             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
553                 log_error("Failed to parse reply.");
554                 r = -EIO;
555                 goto finish;
556         }
557
558         dbus_message_iter_recurse(&iter, &sub);
559
560         printf("%4s %-45s %-17s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
561
562         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
563                 const char *name, *type, *state, *job_path, *unit_path;
564                 uint32_t id;
565                 char *e;
566
567                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
568                         log_error("Failed to parse reply.");
569                         r = -EIO;
570                         goto finish;
571                 }
572
573                 dbus_message_iter_recurse(&sub, &sub2);
574
575                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
576                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
577                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
578                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
579                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
580                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
581                         log_error("Failed to parse reply.");
582                         r = -EIO;
583                         goto finish;
584                 }
585
586                 e = arg_full ? NULL : ellipsize(name, 45, 33);
587                 printf("%4u %-45s %-17s %-7s\n", id, e ? e : name, type, state);
588                 free(e);
589
590                 k++;
591
592                 dbus_message_iter_next(&sub);
593         }
594
595         printf("\n%u jobs listed.\n", k);
596         r = 0;
597
598 finish:
599         if (m)
600                 dbus_message_unref(m);
601
602         if (reply)
603                 dbus_message_unref(reply);
604
605         dbus_error_free(&error);
606
607         return r;
608 }
609
610 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
611         DBusMessage *m = NULL, *reply = NULL;
612         DBusError error;
613         int r;
614         unsigned i;
615
616         dbus_error_init(&error);
617
618         assert(bus);
619         assert(args);
620
621         for (i = 1; i < n; i++) {
622
623                 if (!(m = dbus_message_new_method_call(
624                                       "org.freedesktop.systemd1",
625                                       "/org/freedesktop/systemd1",
626                                       "org.freedesktop.systemd1.Manager",
627                                       "LoadUnit"))) {
628                         log_error("Could not allocate message.");
629                         r = -ENOMEM;
630                         goto finish;
631                 }
632
633                 if (!dbus_message_append_args(m,
634                                               DBUS_TYPE_STRING, &args[i],
635                                               DBUS_TYPE_INVALID)) {
636                         log_error("Could not append arguments to message.");
637                         r = -ENOMEM;
638                         goto finish;
639                 }
640
641                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
642                         log_error("Failed to issue method call: %s", error.message);
643                         r = -EIO;
644                         goto finish;
645                 }
646
647                 dbus_message_unref(m);
648                 dbus_message_unref(reply);
649
650                 m = reply = NULL;
651         }
652
653         r = 0;
654
655 finish:
656         if (m)
657                 dbus_message_unref(m);
658
659         if (reply)
660                 dbus_message_unref(reply);
661
662         dbus_error_free(&error);
663
664         return r;
665 }
666
667 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
668         DBusMessage *m = NULL, *reply = NULL;
669         DBusError error;
670         int r;
671         unsigned i;
672
673         dbus_error_init(&error);
674
675         assert(bus);
676         assert(args);
677
678         for (i = 1; i < n; i++) {
679                 unsigned id;
680                 const char *path;
681
682                 if (!(m = dbus_message_new_method_call(
683                                       "org.freedesktop.systemd1",
684                                       "/org/freedesktop/systemd1",
685                                       "org.freedesktop.systemd1.Manager",
686                                       "GetJob"))) {
687                         log_error("Could not allocate message.");
688                         r = -ENOMEM;
689                         goto finish;
690                 }
691
692                 if ((r = safe_atou(args[i], &id)) < 0) {
693                         log_error("Failed to parse job id: %s", strerror(-r));
694                         goto finish;
695                 }
696
697                 assert_cc(sizeof(uint32_t) == sizeof(id));
698                 if (!dbus_message_append_args(m,
699                                               DBUS_TYPE_UINT32, &id,
700                                               DBUS_TYPE_INVALID)) {
701                         log_error("Could not append arguments to message.");
702                         r = -ENOMEM;
703                         goto finish;
704                 }
705
706                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
707                         log_error("Failed to issue method call: %s", error.message);
708                         r = -EIO;
709                         goto finish;
710                 }
711
712                 if (!dbus_message_get_args(reply, &error,
713                                            DBUS_TYPE_OBJECT_PATH, &path,
714                                            DBUS_TYPE_INVALID)) {
715                         log_error("Failed to parse reply: %s", error.message);
716                         r = -EIO;
717                         goto finish;
718                 }
719
720                 dbus_message_unref(m);
721                 if (!(m = dbus_message_new_method_call(
722                                       "org.freedesktop.systemd1",
723                                       path,
724                                       "org.freedesktop.systemd1.Job",
725                                       "Cancel"))) {
726                         log_error("Could not allocate message.");
727                         r = -ENOMEM;
728                         goto finish;
729                 }
730
731                 dbus_message_unref(reply);
732                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
733                         log_error("Failed to issue method call: %s", error.message);
734                         r = -EIO;
735                         goto finish;
736                 }
737
738                 dbus_message_unref(m);
739                 dbus_message_unref(reply);
740                 m = reply = NULL;
741         }
742
743         r = 0;
744
745 finish:
746         if (m)
747                 dbus_message_unref(m);
748
749         if (reply)
750                 dbus_message_unref(reply);
751
752         dbus_error_free(&error);
753
754         return r;
755 }
756
757 static bool unit_need_daemon_reload(DBusConnection *bus, const char *unit) {
758         DBusMessage *m, *reply;
759         dbus_bool_t b = FALSE;
760         DBusMessageIter iter, sub;
761         const char
762                 *interface = "org.freedesktop.systemd1.Unit",
763                 *property = "NeedDaemonReload",
764                 *path;
765
766         /* We ignore all errors here, since this is used to show a warning only */
767
768         if (!(m = dbus_message_new_method_call(
769                               "org.freedesktop.systemd1",
770                               "/org/freedesktop/systemd1",
771                               "org.freedesktop.systemd1.Manager",
772                               "GetUnit")))
773                 goto finish;
774
775         if (!dbus_message_append_args(m,
776                                       DBUS_TYPE_STRING, &unit,
777                                       DBUS_TYPE_INVALID))
778                 goto finish;
779
780         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
781                 goto finish;
782
783         if (!dbus_message_get_args(reply, NULL,
784                                    DBUS_TYPE_OBJECT_PATH, &path,
785                                    DBUS_TYPE_INVALID))
786                 goto finish;
787
788         dbus_message_unref(m);
789         if (!(m = dbus_message_new_method_call(
790                               "org.freedesktop.systemd1",
791                               path,
792                               "org.freedesktop.DBus.Properties",
793                               "Get")))
794                 goto finish;
795
796         if (!dbus_message_append_args(m,
797                                       DBUS_TYPE_STRING, &interface,
798                                       DBUS_TYPE_STRING, &property,
799                                       DBUS_TYPE_INVALID)) {
800                 goto finish;
801         }
802
803         dbus_message_unref(reply);
804         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
805                 goto finish;
806
807         if (!dbus_message_iter_init(reply, &iter) ||
808             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
809                 goto finish;
810
811         dbus_message_iter_recurse(&iter, &sub);
812
813         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
814                 goto finish;
815
816         dbus_message_iter_get_basic(&sub, &b);
817
818 finish:
819         if (m)
820                 dbus_message_unref(m);
821
822         if (reply)
823                 dbus_message_unref(reply);
824
825         return b;
826 }
827
828 typedef struct WaitData {
829         Set *set;
830         bool failed;
831 } WaitData;
832
833 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
834         DBusError error;
835         WaitData *d = data;
836
837         assert(connection);
838         assert(message);
839         assert(d);
840
841         dbus_error_init(&error);
842
843         log_debug("Got D-Bus request: %s.%s() on %s",
844                   dbus_message_get_interface(message),
845                   dbus_message_get_member(message),
846                   dbus_message_get_path(message));
847
848         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
849                 log_error("Warning! D-Bus connection terminated.");
850                 dbus_connection_close(connection);
851
852         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
853                 uint32_t id;
854                 const char *path;
855                 dbus_bool_t success = true;
856
857                 if (!dbus_message_get_args(message, &error,
858                                            DBUS_TYPE_UINT32, &id,
859                                            DBUS_TYPE_OBJECT_PATH, &path,
860                                            DBUS_TYPE_BOOLEAN, &success,
861                                            DBUS_TYPE_INVALID))
862                         log_error("Failed to parse message: %s", error.message);
863                 else {
864                         char *p;
865
866                         if ((p = set_remove(d->set, (char*) path)))
867                                 free(p);
868
869                         if (!success)
870                                 d->failed = true;
871                 }
872         }
873
874         dbus_error_free(&error);
875         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
876 }
877
878 static int enable_wait_for_jobs(DBusConnection *bus) {
879         DBusError error;
880
881         assert(bus);
882
883         if (private_bus)
884                 return 0;
885
886         dbus_error_init(&error);
887         dbus_bus_add_match(bus,
888                            "type='signal',"
889                            "sender='org.freedesktop.systemd1',"
890                            "interface='org.freedesktop.systemd1.Manager',"
891                            "member='JobRemoved',"
892                            "path='/org/freedesktop/systemd1'",
893                            &error);
894
895         if (dbus_error_is_set(&error)) {
896                 log_error("Failed to add match: %s", error.message);
897                 dbus_error_free(&error);
898                 return -EIO;
899         }
900
901         /* This is slightly dirty, since we don't undo the match registrations. */
902         return 0;
903 }
904
905 static int wait_for_jobs(DBusConnection *bus, Set *s) {
906         int r;
907         WaitData d;
908
909         assert(bus);
910         assert(s);
911
912         zero(d);
913         d.set = s;
914         d.failed = false;
915
916         if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
917                 log_error("Failed to add filter.");
918                 r = -ENOMEM;
919                 goto finish;
920         }
921
922         while (!set_isempty(s) &&
923                dbus_connection_read_write_dispatch(bus, -1))
924                 ;
925
926         if (!arg_quiet && d.failed)
927                 log_error("Job failed, see logs for details.");
928
929         r = d.failed ? -EIO : 0;
930
931 finish:
932         /* This is slightly dirty, since we don't undo the filter registration. */
933
934         return r;
935 }
936
937 static int start_unit_one(
938                 DBusConnection *bus,
939                 const char *method,
940                 const char *name,
941                 const char *mode,
942                 Set *s) {
943
944         DBusMessage *m = NULL, *reply = NULL;
945         DBusError error;
946         const char *path;
947         int r;
948
949         assert(bus);
950         assert(method);
951         assert(name);
952         assert(mode);
953         assert(arg_no_block || s);
954
955         dbus_error_init(&error);
956
957         if (!(m = dbus_message_new_method_call(
958                               "org.freedesktop.systemd1",
959                               "/org/freedesktop/systemd1",
960                               "org.freedesktop.systemd1.Manager",
961                               method))) {
962                 log_error("Could not allocate message.");
963                 r = -ENOMEM;
964                 goto finish;
965         }
966
967         if (!dbus_message_append_args(m,
968                                       DBUS_TYPE_STRING, &name,
969                                       DBUS_TYPE_STRING, &mode,
970                                       DBUS_TYPE_INVALID)) {
971                 log_error("Could not append arguments to message.");
972                 r = -ENOMEM;
973                 goto finish;
974         }
975
976         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
977
978                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
979                         /* There's always a fallback possible for
980                          * legacy actions. */
981                         r = 0;
982                         goto finish;
983                 }
984
985                 log_error("Failed to issue method call: %s", error.message);
986                 r = -EIO;
987                 goto finish;
988         }
989
990         if (!dbus_message_get_args(reply, &error,
991                                    DBUS_TYPE_OBJECT_PATH, &path,
992                                    DBUS_TYPE_INVALID)) {
993                 log_error("Failed to parse reply: %s", error.message);
994                 r = -EIO;
995                 goto finish;
996         }
997
998         if (unit_need_daemon_reload(bus, name))
999                 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
1000                             arg_session ? "--session" : "--system");
1001
1002         if (!arg_no_block) {
1003                 char *p;
1004
1005                 if (!(p = strdup(path))) {
1006                         log_error("Failed to duplicate path.");
1007                         r = -ENOMEM;
1008                         goto finish;
1009                 }
1010
1011                 if ((r = set_put(s, p)) < 0) {
1012                         free(p);
1013                         log_error("Failed to add path to set.");
1014                         goto finish;
1015                 }
1016         }
1017
1018         r = 1;
1019
1020 finish:
1021         if (m)
1022                 dbus_message_unref(m);
1023
1024         if (reply)
1025                 dbus_message_unref(reply);
1026
1027         dbus_error_free(&error);
1028
1029         return r;
1030 }
1031
1032 static enum action verb_to_action(const char *verb) {
1033         if (streq(verb, "halt"))
1034                 return ACTION_HALT;
1035         else if (streq(verb, "poweroff"))
1036                 return ACTION_POWEROFF;
1037         else if (streq(verb, "reboot"))
1038                 return ACTION_REBOOT;
1039         else if (streq(verb, "rescue"))
1040                 return ACTION_RESCUE;
1041         else if (streq(verb, "emergency"))
1042                 return ACTION_EMERGENCY;
1043         else if (streq(verb, "default"))
1044                 return ACTION_DEFAULT;
1045         else
1046                 return ACTION_INVALID;
1047 }
1048
1049 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1050
1051         static const char * const table[_ACTION_MAX] = {
1052                 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1053                 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1054                 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
1055                 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1056                 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1057                 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1058                 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1059                 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
1060                 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
1061                 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
1062         };
1063
1064         int r;
1065         unsigned i;
1066         const char *method, *mode, *one_name;
1067         Set *s = NULL;
1068
1069         assert(bus);
1070
1071         if (arg_action == ACTION_SYSTEMCTL) {
1072                 method =
1073                         streq(args[0], "stop")                  ? "StopUnit" :
1074                         streq(args[0], "reload")                ? "ReloadUnit" :
1075                         streq(args[0], "restart")               ? "RestartUnit" :
1076                         streq(args[0], "try-restart")           ? "TryRestartUnit" :
1077                         streq(args[0], "reload-or-restart")     ? "ReloadOrRestartUnit" :
1078                         streq(args[0], "reload-or-try-restart") ? "ReloadOrTryRestartUnit" :
1079                                                                   "StartUnit";
1080
1081                 mode =
1082                         (streq(args[0], "isolate") ||
1083                          streq(args[0], "rescue")  ||
1084                          streq(args[0], "emergency")) ? "isolate" :
1085                                              arg_fail ? "fail" :
1086                                                         "replace";
1087
1088                 one_name = table[verb_to_action(args[0])];
1089
1090         } else {
1091                 assert(arg_action < ELEMENTSOF(table));
1092                 assert(table[arg_action]);
1093
1094                 method = "StartUnit";
1095
1096                 mode = (arg_action == ACTION_EMERGENCY ||
1097                         arg_action == ACTION_RESCUE) ? "isolate" : "replace";
1098
1099                 one_name = table[arg_action];
1100         }
1101
1102         if (!arg_no_block) {
1103                 if ((r = enable_wait_for_jobs(bus)) < 0) {
1104                         log_error("Could not watch jobs: %s", strerror(-r));
1105                         goto finish;
1106                 }
1107
1108                 if (!(s = set_new(string_hash_func, string_compare_func))) {
1109                         log_error("Failed to allocate set.");
1110                         r = -ENOMEM;
1111                         goto finish;
1112                 }
1113         }
1114
1115         r = 0;
1116
1117         if (one_name) {
1118                 if ((r = start_unit_one(bus, method, one_name, mode, s)) <= 0)
1119                         goto finish;
1120         } else {
1121                 for (i = 1; i < n; i++)
1122                         if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
1123                                 goto finish;
1124         }
1125
1126         if (!arg_no_block)
1127                 r = wait_for_jobs(bus, s);
1128
1129 finish:
1130         if (s)
1131                 set_free_free(s);
1132
1133         return r;
1134 }
1135
1136 static int start_special(DBusConnection *bus, char **args, unsigned n) {
1137         int r;
1138
1139         assert(bus);
1140         assert(args);
1141
1142         r = start_unit(bus, args, n);
1143
1144         if (r >= 0)
1145                 warn_wall(verb_to_action(args[0]));
1146
1147         return r;
1148 }
1149
1150 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1151         DBusMessage *m = NULL, *reply = NULL;
1152         const char
1153                 *interface = "org.freedesktop.systemd1.Unit",
1154                 *property = "ActiveState";
1155         int r = -EADDRNOTAVAIL;
1156         DBusError error;
1157         unsigned i;
1158
1159         assert(bus);
1160         assert(args);
1161
1162         dbus_error_init(&error);
1163
1164         for (i = 1; i < n; i++) {
1165                 const char *path = NULL;
1166                 const char *state;
1167                 DBusMessageIter iter, sub;
1168
1169                 if (!(m = dbus_message_new_method_call(
1170                                       "org.freedesktop.systemd1",
1171                                       "/org/freedesktop/systemd1",
1172                                       "org.freedesktop.systemd1.Manager",
1173                                       "GetUnit"))) {
1174                         log_error("Could not allocate message.");
1175                         r = -ENOMEM;
1176                         goto finish;
1177                 }
1178
1179                 if (!dbus_message_append_args(m,
1180                                               DBUS_TYPE_STRING, &args[i],
1181                                               DBUS_TYPE_INVALID)) {
1182                         log_error("Could not append arguments to message.");
1183                         r = -ENOMEM;
1184                         goto finish;
1185                 }
1186
1187                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1188
1189                         /* Hmm, cannot figure out anything about this unit... */
1190                         if (!arg_quiet)
1191                                 puts("unknown");
1192
1193                         dbus_error_free(&error);
1194                         continue;
1195                 }
1196
1197                 if (!dbus_message_get_args(reply, &error,
1198                                            DBUS_TYPE_OBJECT_PATH, &path,
1199                                            DBUS_TYPE_INVALID)) {
1200                         log_error("Failed to parse reply: %s", error.message);
1201                         r = -EIO;
1202                         goto finish;
1203                 }
1204
1205                 dbus_message_unref(m);
1206                 if (!(m = dbus_message_new_method_call(
1207                                       "org.freedesktop.systemd1",
1208                                       path,
1209                                       "org.freedesktop.DBus.Properties",
1210                                       "Get"))) {
1211                         log_error("Could not allocate message.");
1212                         r = -ENOMEM;
1213                         goto finish;
1214                 }
1215
1216                 if (!dbus_message_append_args(m,
1217                                               DBUS_TYPE_STRING, &interface,
1218                                               DBUS_TYPE_STRING, &property,
1219                                               DBUS_TYPE_INVALID)) {
1220                         log_error("Could not append arguments to message.");
1221                         r = -ENOMEM;
1222                         goto finish;
1223                 }
1224
1225                 dbus_message_unref(reply);
1226                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1227                         log_error("Failed to issue method call: %s", error.message);
1228                         r = -EIO;
1229                         goto finish;
1230                 }
1231
1232                 if (!dbus_message_iter_init(reply, &iter) ||
1233                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1234                         log_error("Failed to parse reply.");
1235                         r = -EIO;
1236                         goto finish;
1237                 }
1238
1239                 dbus_message_iter_recurse(&iter, &sub);
1240
1241                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1242                         log_error("Failed to parse reply.");
1243                         r = -EIO;
1244                         goto finish;
1245                 }
1246
1247                 dbus_message_iter_get_basic(&sub, &state);
1248
1249                 if (!arg_quiet)
1250                         puts(state);
1251
1252                 if (streq(state, "active") || startswith(state, "reloading"))
1253                         r = 0;
1254
1255                 dbus_message_unref(m);
1256                 dbus_message_unref(reply);
1257                 m = reply = NULL;
1258         }
1259
1260 finish:
1261         if (m)
1262                 dbus_message_unref(m);
1263
1264         if (reply)
1265                 dbus_message_unref(reply);
1266
1267         dbus_error_free(&error);
1268
1269         return r;
1270 }
1271
1272 typedef struct ExecStatusInfo {
1273         char *path;
1274         char **argv;
1275
1276         bool ignore;
1277
1278         usec_t start_timestamp;
1279         usec_t exit_timestamp;
1280         pid_t pid;
1281         int code;
1282         int status;
1283
1284         LIST_FIELDS(struct ExecStatusInfo, exec);
1285 } ExecStatusInfo;
1286
1287 static void exec_status_info_free(ExecStatusInfo *i) {
1288         assert(i);
1289
1290         free(i->path);
1291         strv_free(i->argv);
1292         free(i);
1293 }
1294
1295 static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
1296         uint64_t start_timestamp, exit_timestamp;
1297         DBusMessageIter sub2, sub3;
1298         const char*path;
1299         unsigned n;
1300         uint32_t pid;
1301         int32_t code, status;
1302         dbus_bool_t ignore;
1303
1304         assert(i);
1305         assert(i);
1306
1307         if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1308                 return -EIO;
1309
1310         dbus_message_iter_recurse(sub, &sub2);
1311
1312         if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1313                 return -EIO;
1314
1315         if (!(i->path = strdup(path)))
1316                 return -ENOMEM;
1317
1318         if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1319             dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1320                 return -EIO;
1321
1322         n = 0;
1323         dbus_message_iter_recurse(&sub2, &sub3);
1324         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1325                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1326                 dbus_message_iter_next(&sub3);
1327                 n++;
1328         }
1329
1330
1331         if (!(i->argv = new0(char*, n+1)))
1332                 return -ENOMEM;
1333
1334         n = 0;
1335         dbus_message_iter_recurse(&sub2, &sub3);
1336         while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1337                 const char *s;
1338
1339                 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1340                 dbus_message_iter_get_basic(&sub3, &s);
1341                 dbus_message_iter_next(&sub3);
1342
1343                 if (!(i->argv[n++] = strdup(s)))
1344                         return -ENOMEM;
1345         }
1346
1347         if (!dbus_message_iter_next(&sub2) ||
1348             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
1349             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
1350             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
1351             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1352             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1353             bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1354                 return -EIO;
1355
1356         i->ignore = ignore;
1357         i->start_timestamp = (usec_t) start_timestamp;
1358         i->exit_timestamp = (usec_t) exit_timestamp;
1359         i->pid = (pid_t) pid;
1360         i->code = code;
1361         i->status = status;
1362
1363         return 0;
1364 }
1365
1366 typedef struct UnitStatusInfo {
1367         const char *id;
1368         const char *load_state;
1369         const char *active_state;
1370         const char *sub_state;
1371
1372         const char *description;
1373
1374         const char *fragment_path;
1375         const char *default_control_group;
1376
1377         bool need_daemon_reload;
1378
1379         /* Service */
1380         pid_t main_pid;
1381         pid_t control_pid;
1382         const char *status_text;
1383         bool running;
1384
1385         usec_t start_timestamp;
1386         usec_t exit_timestamp;
1387
1388         int exit_code, exit_status;
1389
1390         /* Socket */
1391         unsigned n_accepted;
1392         unsigned n_connections;
1393         bool accept;
1394
1395         /* Device */
1396         const char *sysfs_path;
1397
1398         /* Mount, Automount */
1399         const char *where;
1400
1401         /* Swap */
1402         const char *what;
1403
1404         LIST_HEAD(ExecStatusInfo, exec);
1405 } UnitStatusInfo;
1406
1407 static void print_status_info(UnitStatusInfo *i) {
1408         ExecStatusInfo *p;
1409
1410         assert(i);
1411
1412         /* This shows pretty information about a unit. See
1413          * print_property() for a low-level property printer */
1414
1415         printf("%s", strna(i->id));
1416
1417         if (i->description && !streq_ptr(i->id, i->description))
1418                 printf(" - %s", i->description);
1419
1420         printf("\n");
1421
1422         if (i->fragment_path)
1423                 printf("\t  Loaded: %s (%s)\n", strna(i->load_state), i->fragment_path);
1424         else if (streq_ptr(i->load_state, "failed"))
1425                 printf("\t  Loaded: " ANSI_HIGHLIGHT_ON "%s" ANSI_HIGHLIGHT_OFF "\n", strna(i->load_state));
1426         else
1427                 printf("\t  Loaded: %s\n", strna(i->load_state));
1428
1429         if (streq_ptr(i->active_state, "maintenance")) {
1430                         if (streq_ptr(i->active_state, i->sub_state))
1431                                 printf("\t  Active: " ANSI_HIGHLIGHT_ON "%s" ANSI_HIGHLIGHT_OFF "\n",
1432                                        strna(i->active_state));
1433                         else
1434                                 printf("\t  Active: " ANSI_HIGHLIGHT_ON "%s (%s)" ANSI_HIGHLIGHT_OFF "\n",
1435                                        strna(i->active_state),
1436                                        strna(i->sub_state));
1437         } else {
1438                 if (streq_ptr(i->active_state, i->sub_state))
1439                         printf("\t  Active: %s\n",
1440                                strna(i->active_state));
1441                 else
1442                         printf("\t  Active: %s (%s)\n",
1443                                strna(i->active_state),
1444                                strna(i->sub_state));
1445         }
1446
1447         if (i->sysfs_path)
1448                 printf("\t  Device: %s\n", i->sysfs_path);
1449         else if (i->where)
1450                 printf("\t   Where: %s\n", i->where);
1451         else if (i->what)
1452                 printf("\t    What: %s\n", i->what);
1453
1454         if (i->accept)
1455                 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1456
1457         LIST_FOREACH(exec, p, i->exec) {
1458                 char *t;
1459
1460                 /* Only show exited processes here */
1461                 if (p->code == 0)
1462                         continue;
1463
1464                 t = strv_join(p->argv, " ");
1465                 printf("\t  Exited: %u (%s, code=%s, ", p->pid, strna(t), sigchld_code_to_string(p->code));
1466                 free(t);
1467
1468                 if (p->code == CLD_EXITED)
1469                         printf("status=%i", p->status);
1470                 else
1471                         printf("signal=%s", signal_to_string(p->status));
1472                 printf(")\n");
1473
1474                 if (i->main_pid == p->pid &&
1475                     i->start_timestamp == p->start_timestamp &&
1476                     i->exit_timestamp == p->start_timestamp)
1477                         /* Let's not show this twice */
1478                         i->main_pid = 0;
1479
1480                 if (p->pid == i->control_pid)
1481                         i->control_pid = 0;
1482         }
1483
1484         if (i->main_pid > 0 || i->control_pid > 0) {
1485                 printf("\t");
1486
1487                 if (i->main_pid > 0) {
1488                         printf("    Main: %u", (unsigned) i->main_pid);
1489
1490                         if (i->running) {
1491                                 char *t = NULL;
1492                                 get_process_name(i->main_pid, &t);
1493                                 if (t) {
1494                                         printf(" (%s)", t);
1495                                         free(t);
1496                                 }
1497                         } else {
1498                                 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
1499
1500                                 if (i->exit_code == CLD_EXITED)
1501                                         printf("status=%i", i->exit_status);
1502                                 else
1503                                         printf("signal=%s", signal_to_string(i->exit_status));
1504                                 printf(")");
1505                         }
1506                 }
1507
1508                 if (i->main_pid > 0 && i->control_pid > 0)
1509                         printf(";");
1510
1511                 if (i->control_pid > 0) {
1512                         char *t = NULL;
1513
1514                         printf(" Control: %u", (unsigned) i->control_pid);
1515
1516                         get_process_name(i->control_pid, &t);
1517                         if (t) {
1518                                 printf(" (%s)", t);
1519                                 free(t);
1520                         }
1521                 }
1522
1523                 printf("\n");
1524         }
1525
1526         if (i->status_text)
1527                 printf("\t  Status: \"%s\"\n", i->status_text);
1528
1529         if (i->default_control_group) {
1530                 unsigned c;
1531
1532                 printf("\t  CGroup: %s\n", i->default_control_group);
1533
1534                 if ((c = columns()) > 18)
1535                         c -= 18;
1536                 else
1537                         c = 0;
1538
1539                 show_cgroup_by_path(i->default_control_group, "\t\t  ", c);
1540         }
1541
1542         if (i->need_daemon_reload)
1543                 printf("\n" ANSI_HIGHLIGHT_ON "Warning:" ANSI_HIGHLIGHT_OFF " Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
1544                        arg_session ? "--session" : "--system");
1545 }
1546
1547 static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
1548
1549         switch (dbus_message_iter_get_arg_type(iter)) {
1550
1551         case DBUS_TYPE_STRING: {
1552                 const char *s;
1553
1554                 dbus_message_iter_get_basic(iter, &s);
1555
1556                 if (s[0]) {
1557                         if (streq(name, "Id"))
1558                                 i->id = s;
1559                         else if (streq(name, "LoadState"))
1560                                 i->load_state = s;
1561                         else if (streq(name, "ActiveState"))
1562                                 i->active_state = s;
1563                         else if (streq(name, "SubState"))
1564                                 i->sub_state = s;
1565                         else if (streq(name, "Description"))
1566                                 i->description = s;
1567                         else if (streq(name, "FragmentPath"))
1568                                 i->fragment_path = s;
1569                         else if (streq(name, "DefaultControlGroup"))
1570                                 i->default_control_group = s;
1571                         else if (streq(name, "StatusText"))
1572                                 i->status_text = s;
1573                         else if (streq(name, "SysFSPath"))
1574                                 i->sysfs_path = s;
1575                         else if (streq(name, "Where"))
1576                                 i->where = s;
1577                         else if (streq(name, "What"))
1578                                 i->what = s;
1579                 }
1580
1581                 break;
1582         }
1583
1584         case DBUS_TYPE_BOOLEAN: {
1585                 dbus_bool_t b;
1586
1587                 dbus_message_iter_get_basic(iter, &b);
1588
1589                 if (streq(name, "Accept"))
1590                         i->accept = b;
1591                 else if (streq(name, "NeedDaemonReload"))
1592                         i->need_daemon_reload = b;
1593
1594                 break;
1595         }
1596
1597         case DBUS_TYPE_UINT32: {
1598                 uint32_t u;
1599
1600                 dbus_message_iter_get_basic(iter, &u);
1601
1602                 if (streq(name, "MainPID")) {
1603                         if (u > 0) {
1604                                 i->main_pid = (pid_t) u;
1605                                 i->running = true;
1606                         }
1607                 } else if (streq(name, "ControlPID"))
1608                         i->control_pid = (pid_t) u;
1609                 else if (streq(name, "ExecMainPID")) {
1610                         if (u > 0)
1611                                 i->main_pid = (pid_t) u;
1612                 } else if (streq(name, "NAccepted"))
1613                         i->n_accepted = u;
1614                 else if (streq(name, "NConnections"))
1615                         i->n_connections = u;
1616
1617                 break;
1618         }
1619
1620         case DBUS_TYPE_INT32: {
1621                 int32_t j;
1622
1623                 dbus_message_iter_get_basic(iter, &j);
1624
1625                 if (streq(name, "ExecMainCode"))
1626                         i->exit_code = (int) j;
1627                 else if (streq(name, "ExecMainStatus"))
1628                         i->exit_status = (int) j;
1629
1630                 break;
1631         }
1632
1633         case DBUS_TYPE_UINT64: {
1634                 uint64_t u;
1635
1636                 dbus_message_iter_get_basic(iter, &u);
1637
1638                 if (streq(name, "ExecMainStartTimestamp"))
1639                         i->start_timestamp = (usec_t) u;
1640                 else if (streq(name, "ExecMainExitTimestamp"))
1641                         i->exit_timestamp = (usec_t) u;
1642
1643                 break;
1644         }
1645
1646         case DBUS_TYPE_ARRAY: {
1647
1648                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
1649                     startswith(name, "Exec")) {
1650                         DBusMessageIter sub;
1651
1652                         dbus_message_iter_recurse(iter, &sub);
1653                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1654                                 ExecStatusInfo *info;
1655                                 int r;
1656
1657                                 if (!(info = new0(ExecStatusInfo, 1)))
1658                                         return -ENOMEM;
1659
1660                                 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
1661                                         free(info);
1662                                         return r;
1663                                 }
1664
1665                                 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
1666
1667                                 dbus_message_iter_next(&sub);
1668                         }
1669                 }
1670
1671                 break;
1672         }
1673         }
1674
1675         return 0;
1676 }
1677
1678 static int print_property(const char *name, DBusMessageIter *iter) {
1679         assert(name);
1680         assert(iter);
1681
1682         /* This is a low-level property printer, see
1683          * print_status_info() for the nicer output */
1684
1685         if (arg_property && !streq(name, arg_property))
1686                 return 0;
1687
1688         switch (dbus_message_iter_get_arg_type(iter)) {
1689
1690         case DBUS_TYPE_STRING: {
1691                 const char *s;
1692                 dbus_message_iter_get_basic(iter, &s);
1693
1694                 if (arg_all || s[0])
1695                         printf("%s=%s\n", name, s);
1696
1697                 return 0;
1698         }
1699
1700         case DBUS_TYPE_BOOLEAN: {
1701                 dbus_bool_t b;
1702                 dbus_message_iter_get_basic(iter, &b);
1703                 printf("%s=%s\n", name, yes_no(b));
1704
1705                 return 0;
1706         }
1707
1708         case DBUS_TYPE_UINT64: {
1709                 uint64_t u;
1710                 dbus_message_iter_get_basic(iter, &u);
1711
1712                 /* Yes, heuristics! But we can change this check
1713                  * should it turn out to not be sufficient */
1714
1715                 if (strstr(name, "Timestamp")) {
1716                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1717
1718                         if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1719                                 printf("%s=%s\n", name, strempty(t));
1720                 } else if (strstr(name, "USec")) {
1721                         char timespan[FORMAT_TIMESPAN_MAX];
1722
1723                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
1724                 } else
1725                         printf("%s=%llu\n", name, (unsigned long long) u);
1726
1727                 return 0;
1728         }
1729
1730         case DBUS_TYPE_UINT32: {
1731                 uint32_t u;
1732                 dbus_message_iter_get_basic(iter, &u);
1733
1734                 if (strstr(name, "UMask") || strstr(name, "Mode"))
1735                         printf("%s=%04o\n", name, u);
1736                 else
1737                         printf("%s=%u\n", name, (unsigned) u);
1738
1739                 return 0;
1740         }
1741
1742         case DBUS_TYPE_INT32: {
1743                 int32_t i;
1744                 dbus_message_iter_get_basic(iter, &i);
1745
1746                 printf("%s=%i\n", name, (int) i);
1747                 return 0;
1748         }
1749
1750         case DBUS_TYPE_STRUCT: {
1751                 DBusMessageIter sub;
1752                 dbus_message_iter_recurse(iter, &sub);
1753
1754                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1755                         uint32_t u;
1756
1757                         dbus_message_iter_get_basic(&sub, &u);
1758
1759                         if (u)
1760                                 printf("%s=%u\n", name, (unsigned) u);
1761                         else if (arg_all)
1762                                 printf("%s=\n", name);
1763
1764                         return 0;
1765                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1766                         const char *s;
1767
1768                         dbus_message_iter_get_basic(&sub, &s);
1769
1770                         if (arg_all || s[0])
1771                                 printf("%s=%s\n", name, s);
1772
1773                         return 0;
1774                 }
1775
1776                 break;
1777         }
1778
1779         case DBUS_TYPE_ARRAY:
1780
1781                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1782                         DBusMessageIter sub;
1783                         bool space = false;
1784
1785                         dbus_message_iter_recurse(iter, &sub);
1786                         if (arg_all ||
1787                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1788                                 printf("%s=", name);
1789
1790                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1791                                         const char *s;
1792
1793                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1794                                         dbus_message_iter_get_basic(&sub, &s);
1795                                         printf("%s%s", space ? " " : "", s);
1796
1797                                         space = true;
1798                                         dbus_message_iter_next(&sub);
1799                                 }
1800
1801                                 puts("");
1802                         }
1803
1804                         return 0;
1805
1806                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1807                         DBusMessageIter sub;
1808
1809                         dbus_message_iter_recurse(iter, &sub);
1810                         if (arg_all ||
1811                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1812                                 printf("%s=", name);
1813
1814                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1815                                         uint8_t u;
1816
1817                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1818                                         dbus_message_iter_get_basic(&sub, &u);
1819                                         printf("%02x", u);
1820
1821                                         dbus_message_iter_next(&sub);
1822                                 }
1823
1824                                 puts("");
1825                         }
1826
1827                         return 0;
1828
1829                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1830                         DBusMessageIter sub, sub2;
1831
1832                         dbus_message_iter_recurse(iter, &sub);
1833                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1834                                 const char *type, *path;
1835
1836                                 dbus_message_iter_recurse(&sub, &sub2);
1837
1838                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1839                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1840                                         printf("%s=%s\n", type, path);
1841
1842                                 dbus_message_iter_next(&sub);
1843                         }
1844
1845                         return 0;
1846
1847                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1848                         DBusMessageIter sub, sub2;
1849
1850                         dbus_message_iter_recurse(iter, &sub);
1851                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1852                                 const char *base;
1853                                 uint64_t value, next_elapse;
1854
1855                                 dbus_message_iter_recurse(&sub, &sub2);
1856
1857                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
1858                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
1859                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
1860                                         char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
1861
1862                                         printf("%s={ value=%s ; next_elapse=%s }\n",
1863                                                base,
1864                                                format_timespan(timespan1, sizeof(timespan1), value),
1865                                                format_timespan(timespan2, sizeof(timespan2), next_elapse));
1866                                 }
1867
1868                                 dbus_message_iter_next(&sub);
1869                         }
1870
1871                         return 0;
1872
1873                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
1874                         DBusMessageIter sub;
1875
1876                         dbus_message_iter_recurse(iter, &sub);
1877                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1878                                 ExecStatusInfo info;
1879
1880                                 zero(info);
1881                                 if (exec_status_info_deserialize(&sub, &info) >= 0) {
1882                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
1883                                         char *t;
1884
1885                                         t = strv_join(info.argv, " ");
1886
1887                                         printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
1888                                                name,
1889                                                strna(info.path),
1890                                                strna(t),
1891                                                yes_no(info.ignore),
1892                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
1893                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
1894                                                (unsigned) info. pid,
1895                                                sigchld_code_to_string(info.code),
1896                                                info.status,
1897                                                info.code == CLD_EXITED ? "" : "/",
1898                                                strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
1899
1900                                         free(t);
1901                                 }
1902
1903                                 free(info.path);
1904                                 strv_free(info.argv);
1905
1906                                 dbus_message_iter_next(&sub);
1907                         }
1908
1909                         return 0;
1910                 }
1911
1912                 break;
1913         }
1914
1915         if (arg_all)
1916                 printf("%s=[unprintable]\n", name);
1917
1918         return 0;
1919 }
1920
1921 static int show_one(DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
1922         DBusMessage *m = NULL, *reply = NULL;
1923         const char *interface = "";
1924         int r;
1925         DBusError error;
1926         DBusMessageIter iter, sub, sub2, sub3;
1927         UnitStatusInfo info;
1928         ExecStatusInfo *p;
1929
1930         assert(bus);
1931         assert(path);
1932         assert(new_line);
1933
1934         zero(info);
1935         dbus_error_init(&error);
1936
1937         if (!(m = dbus_message_new_method_call(
1938                               "org.freedesktop.systemd1",
1939                               path,
1940                               "org.freedesktop.DBus.Properties",
1941                               "GetAll"))) {
1942                 log_error("Could not allocate message.");
1943                 r = -ENOMEM;
1944                 goto finish;
1945         }
1946
1947         if (!dbus_message_append_args(m,
1948                                       DBUS_TYPE_STRING, &interface,
1949                                       DBUS_TYPE_INVALID)) {
1950                 log_error("Could not append arguments to message.");
1951                 r = -ENOMEM;
1952                 goto finish;
1953         }
1954
1955         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1956                 log_error("Failed to issue method call: %s", error.message);
1957                 r = -EIO;
1958                 goto finish;
1959         }
1960
1961         if (!dbus_message_iter_init(reply, &iter) ||
1962             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1963             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
1964                 log_error("Failed to parse reply.");
1965                 r = -EIO;
1966                 goto finish;
1967         }
1968
1969         dbus_message_iter_recurse(&iter, &sub);
1970
1971         if (*new_line)
1972                 printf("\n");
1973
1974         *new_line = true;
1975
1976         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1977                 const char *name;
1978
1979                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
1980                         log_error("Failed to parse reply.");
1981                         r = -EIO;
1982                         goto finish;
1983                 }
1984
1985                 dbus_message_iter_recurse(&sub, &sub2);
1986
1987                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
1988                         log_error("Failed to parse reply.");
1989                         r = -EIO;
1990                         goto finish;
1991                 }
1992
1993                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
1994                         log_error("Failed to parse reply.");
1995                         r = -EIO;
1996                         goto finish;
1997                 }
1998
1999                 dbus_message_iter_recurse(&sub2, &sub3);
2000
2001                 if (show_properties)
2002                         r = print_property(name, &sub3);
2003                 else
2004                         r = status_property(name, &sub3, &info);
2005
2006                 if (r < 0) {
2007                         log_error("Failed to parse reply.");
2008                         r = -EIO;
2009                         goto finish;
2010                 }
2011
2012                 dbus_message_iter_next(&sub);
2013         }
2014
2015         if (!show_properties)
2016                 print_status_info(&info);
2017
2018         while ((p = info.exec)) {
2019                 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2020                 exec_status_info_free(p);
2021         }
2022
2023         r = 0;
2024
2025 finish:
2026         if (m)
2027                 dbus_message_unref(m);
2028
2029         if (reply)
2030                 dbus_message_unref(reply);
2031
2032         dbus_error_free(&error);
2033
2034         return r;
2035 }
2036
2037 static int show(DBusConnection *bus, char **args, unsigned n) {
2038         DBusMessage *m = NULL, *reply = NULL;
2039         int r;
2040         DBusError error;
2041         unsigned i;
2042         bool show_properties, new_line = false;
2043
2044         assert(bus);
2045         assert(args);
2046
2047         dbus_error_init(&error);
2048
2049         show_properties = !streq(args[0], "status");
2050
2051         if (show_properties && n <= 1) {
2052                 /* If not argument is specified inspect the manager
2053                  * itself */
2054
2055                 r = show_one(bus, "/org/freedesktop/systemd1", show_properties, &new_line);
2056                 goto finish;
2057         }
2058
2059         for (i = 1; i < n; i++) {
2060                 const char *path = NULL;
2061                 uint32_t id;
2062
2063                 if (!show_properties || safe_atou32(args[i], &id) < 0) {
2064
2065                         if (!(m = dbus_message_new_method_call(
2066                                               "org.freedesktop.systemd1",
2067                                               "/org/freedesktop/systemd1",
2068                                               "org.freedesktop.systemd1.Manager",
2069                                               "LoadUnit"))) {
2070                                 log_error("Could not allocate message.");
2071                                 r = -ENOMEM;
2072                                 goto finish;
2073                         }
2074
2075                         if (!dbus_message_append_args(m,
2076                                                       DBUS_TYPE_STRING, &args[i],
2077                                                       DBUS_TYPE_INVALID)) {
2078                                 log_error("Could not append arguments to message.");
2079                                 r = -ENOMEM;
2080                                 goto finish;
2081                         }
2082
2083                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2084
2085                                 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
2086                                         log_error("Failed to issue method call: %s", error.message);
2087                                         r = -EIO;
2088                                         goto finish;
2089                                 }
2090
2091                                 dbus_error_free(&error);
2092
2093                                 dbus_message_unref(m);
2094                                 if (!(m = dbus_message_new_method_call(
2095                                                       "org.freedesktop.systemd1",
2096                                                       "/org/freedesktop/systemd1",
2097                                                       "org.freedesktop.systemd1.Manager",
2098                                                       "GetUnit"))) {
2099                                         log_error("Could not allocate message.");
2100                                         r = -ENOMEM;
2101                                         goto finish;
2102                                 }
2103
2104                                 if (!dbus_message_append_args(m,
2105                                                               DBUS_TYPE_STRING, &args[i],
2106                                                               DBUS_TYPE_INVALID)) {
2107                                         log_error("Could not append arguments to message.");
2108                                         r = -ENOMEM;
2109                                         goto finish;
2110                                 }
2111
2112                                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2113                                         log_error("Failed to issue method call: %s", error.message);
2114                                         r = -EIO;
2115                                         goto finish;
2116                                 }
2117                         }
2118
2119                 } else {
2120
2121                         if (!(m = dbus_message_new_method_call(
2122                                               "org.freedesktop.systemd1",
2123                                               "/org/freedesktop/systemd1",
2124                                               "org.freedesktop.systemd1.Manager",
2125                                               "GetJob"))) {
2126                                 log_error("Could not allocate message.");
2127                                 r = -ENOMEM;
2128                                 goto finish;
2129                         }
2130
2131                         if (!dbus_message_append_args(m,
2132                                                       DBUS_TYPE_UINT32, &id,
2133                                                       DBUS_TYPE_INVALID)) {
2134                                 log_error("Could not append arguments to message.");
2135                                 r = -ENOMEM;
2136                                 goto finish;
2137                         }
2138
2139                         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2140                                 log_error("Failed to issue method call: %s", error.message);
2141                                 r = -EIO;
2142                                 goto finish;
2143                         }
2144                 }
2145
2146                 if (!dbus_message_get_args(reply, &error,
2147                                            DBUS_TYPE_OBJECT_PATH, &path,
2148                                            DBUS_TYPE_INVALID)) {
2149                         log_error("Failed to parse reply: %s", error.message);
2150                         r = -EIO;
2151                         goto finish;
2152                 }
2153
2154                 if ((r = show_one(bus, path, show_properties, &new_line)) < 0)
2155                         goto finish;
2156
2157                 dbus_message_unref(m);
2158                 dbus_message_unref(reply);
2159                 m = reply = NULL;
2160         }
2161
2162         r = 0;
2163
2164 finish:
2165         if (m)
2166                 dbus_message_unref(m);
2167
2168         if (reply)
2169                 dbus_message_unref(reply);
2170
2171         dbus_error_free(&error);
2172
2173         return r;
2174 }
2175
2176 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2177         DBusError error;
2178         DBusMessage *m = NULL, *reply = NULL;
2179
2180         assert(connection);
2181         assert(message);
2182
2183         dbus_error_init(&error);
2184
2185         log_debug("Got D-Bus request: %s.%s() on %s",
2186                   dbus_message_get_interface(message),
2187                   dbus_message_get_member(message),
2188                   dbus_message_get_path(message));
2189
2190         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2191                 log_error("Warning! D-Bus connection terminated.");
2192                 dbus_connection_close(connection);
2193
2194         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2195                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2196                 const char *id, *path;
2197
2198                 if (!dbus_message_get_args(message, &error,
2199                                            DBUS_TYPE_STRING, &id,
2200                                            DBUS_TYPE_OBJECT_PATH, &path,
2201                                            DBUS_TYPE_INVALID))
2202                         log_error("Failed to parse message: %s", error.message);
2203                 else if (streq(dbus_message_get_member(message), "UnitNew"))
2204                         printf("Unit %s added.\n", id);
2205                 else
2206                         printf("Unit %s removed.\n", id);
2207
2208         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
2209                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
2210                 uint32_t id;
2211                 const char *path;
2212
2213                 if (!dbus_message_get_args(message, &error,
2214                                            DBUS_TYPE_UINT32, &id,
2215                                            DBUS_TYPE_OBJECT_PATH, &path,
2216                                            DBUS_TYPE_INVALID))
2217                         log_error("Failed to parse message: %s", error.message);
2218                 else if (streq(dbus_message_get_member(message), "JobNew"))
2219                         printf("Job %u added.\n", id);
2220                 else
2221                         printf("Job %u removed.\n", id);
2222
2223
2224         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Unit", "Changed") ||
2225                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Job", "Changed")) {
2226
2227                 const char *path, *interface, *property = "Id";
2228                 DBusMessageIter iter, sub;
2229
2230                 path = dbus_message_get_path(message);
2231                 interface = dbus_message_get_interface(message);
2232
2233                 if (!(m = dbus_message_new_method_call(
2234                               "org.freedesktop.systemd1",
2235                               path,
2236                               "org.freedesktop.DBus.Properties",
2237                               "Get"))) {
2238                         log_error("Could not allocate message.");
2239                         goto oom;
2240                 }
2241
2242                 if (!dbus_message_append_args(m,
2243                                               DBUS_TYPE_STRING, &interface,
2244                                               DBUS_TYPE_STRING, &property,
2245                                               DBUS_TYPE_INVALID)) {
2246                         log_error("Could not append arguments to message.");
2247                         goto finish;
2248                 }
2249
2250                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
2251                         log_error("Failed to issue method call: %s", error.message);
2252                         goto finish;
2253                 }
2254
2255                 if (!dbus_message_iter_init(reply, &iter) ||
2256                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2257                         log_error("Failed to parse reply.");
2258                         goto finish;
2259                 }
2260
2261                 dbus_message_iter_recurse(&iter, &sub);
2262
2263                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2264                         const char *id;
2265
2266                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2267                                 log_error("Failed to parse reply.");
2268                                 goto finish;
2269                         }
2270
2271                         dbus_message_iter_get_basic(&sub, &id);
2272                         printf("Unit %s changed.\n", id);
2273                 } else {
2274                         uint32_t id;
2275
2276                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
2277                                 log_error("Failed to parse reply.");
2278                                 goto finish;
2279                         }
2280
2281                         dbus_message_iter_get_basic(&sub, &id);
2282                         printf("Job %u changed.\n", id);
2283                 }
2284         }
2285
2286 finish:
2287         if (m)
2288                 dbus_message_unref(m);
2289
2290         if (reply)
2291                 dbus_message_unref(reply);
2292
2293         dbus_error_free(&error);
2294         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2295
2296 oom:
2297         if (m)
2298                 dbus_message_unref(m);
2299
2300         if (reply)
2301                 dbus_message_unref(reply);
2302
2303         dbus_error_free(&error);
2304         return DBUS_HANDLER_RESULT_NEED_MEMORY;
2305 }
2306
2307 static int monitor(DBusConnection *bus, char **args, unsigned n) {
2308         DBusMessage *m = NULL, *reply = NULL;
2309         DBusError error;
2310         int r;
2311
2312         dbus_error_init(&error);
2313
2314         if (!private_bus) {
2315                 dbus_bus_add_match(bus,
2316                                    "type='signal',"
2317                                    "sender='org.freedesktop.systemd1',"
2318                                    "interface='org.freedesktop.systemd1.Manager',"
2319                                    "path='/org/freedesktop/systemd1'",
2320                                    &error);
2321
2322                 if (dbus_error_is_set(&error)) {
2323                         log_error("Failed to add match: %s", error.message);
2324                         r = -EIO;
2325                         goto finish;
2326                 }
2327
2328                 dbus_bus_add_match(bus,
2329                                    "type='signal',"
2330                                    "sender='org.freedesktop.systemd1',"
2331                                    "interface='org.freedesktop.systemd1.Unit',"
2332                                    "member='Changed'",
2333                                    &error);
2334
2335                 if (dbus_error_is_set(&error)) {
2336                         log_error("Failed to add match: %s", error.message);
2337                         r = -EIO;
2338                         goto finish;
2339                 }
2340
2341                 dbus_bus_add_match(bus,
2342                                    "type='signal',"
2343                                    "sender='org.freedesktop.systemd1',"
2344                                    "interface='org.freedesktop.systemd1.Job',"
2345                                    "member='Changed'",
2346                                    &error);
2347
2348                 if (dbus_error_is_set(&error)) {
2349                         log_error("Failed to add match: %s", error.message);
2350                         r = -EIO;
2351                         goto finish;
2352                 }
2353         }
2354
2355         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
2356                 log_error("Failed to add filter.");
2357                 r = -ENOMEM;
2358                 goto finish;
2359         }
2360
2361         if (!(m = dbus_message_new_method_call(
2362                               "org.freedesktop.systemd1",
2363                               "/org/freedesktop/systemd1",
2364                               "org.freedesktop.systemd1.Manager",
2365                               "Subscribe"))) {
2366                 log_error("Could not allocate message.");
2367                 r = -ENOMEM;
2368                 goto finish;
2369         }
2370
2371         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2372                 log_error("Failed to issue method call: %s", error.message);
2373                 r = -EIO;
2374                 goto finish;
2375         }
2376
2377         while (dbus_connection_read_write_dispatch(bus, -1))
2378                 ;
2379
2380         r = 0;
2381
2382 finish:
2383
2384         /* This is slightly dirty, since we don't undo the filter or the matches. */
2385
2386         if (m)
2387                 dbus_message_unref(m);
2388
2389         if (reply)
2390                 dbus_message_unref(reply);
2391
2392         dbus_error_free(&error);
2393
2394         return r;
2395 }
2396
2397 static int dump(DBusConnection *bus, char **args, unsigned n) {
2398         DBusMessage *m = NULL, *reply = NULL;
2399         DBusError error;
2400         int r;
2401         const char *text;
2402
2403         dbus_error_init(&error);
2404
2405         if (!(m = dbus_message_new_method_call(
2406                               "org.freedesktop.systemd1",
2407                               "/org/freedesktop/systemd1",
2408                               "org.freedesktop.systemd1.Manager",
2409                               "Dump"))) {
2410                 log_error("Could not allocate message.");
2411                 return -ENOMEM;
2412         }
2413
2414         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2415                 log_error("Failed to issue method call: %s", error.message);
2416                 r = -EIO;
2417                 goto finish;
2418         }
2419
2420         if (!dbus_message_get_args(reply, &error,
2421                                    DBUS_TYPE_STRING, &text,
2422                                    DBUS_TYPE_INVALID)) {
2423                 log_error("Failed to parse reply: %s", error.message);
2424                 r = -EIO;
2425                 goto finish;
2426         }
2427
2428         fputs(text, stdout);
2429
2430         r = 0;
2431
2432 finish:
2433         if (m)
2434                 dbus_message_unref(m);
2435
2436         if (reply)
2437                 dbus_message_unref(reply);
2438
2439         dbus_error_free(&error);
2440
2441         return r;
2442 }
2443
2444 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
2445         DBusMessage *m = NULL, *reply = NULL;
2446         DBusError error;
2447         int r;
2448         const char *name = "", *path, *id;
2449         dbus_bool_t cleanup = FALSE;
2450         DBusMessageIter iter, sub;
2451         const char
2452                 *interface = "org.freedesktop.systemd1.Unit",
2453                 *property = "Id";
2454
2455         dbus_error_init(&error);
2456
2457         if (!(m = dbus_message_new_method_call(
2458                               "org.freedesktop.systemd1",
2459                               "/org/freedesktop/systemd1",
2460                               "org.freedesktop.systemd1.Manager",
2461                               "CreateSnapshot"))) {
2462                 log_error("Could not allocate message.");
2463                 return -ENOMEM;
2464         }
2465
2466         if (n > 1)
2467                 name = args[1];
2468
2469         if (!dbus_message_append_args(m,
2470                                       DBUS_TYPE_STRING, &name,
2471                                       DBUS_TYPE_BOOLEAN, &cleanup,
2472                                       DBUS_TYPE_INVALID)) {
2473                 log_error("Could not append arguments to message.");
2474                 r = -ENOMEM;
2475                 goto finish;
2476         }
2477
2478         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2479                 log_error("Failed to issue method call: %s", error.message);
2480                 r = -EIO;
2481                 goto finish;
2482         }
2483
2484         if (!dbus_message_get_args(reply, &error,
2485                                    DBUS_TYPE_OBJECT_PATH, &path,
2486                                    DBUS_TYPE_INVALID)) {
2487                 log_error("Failed to parse reply: %s", error.message);
2488                 r = -EIO;
2489                 goto finish;
2490         }
2491
2492         dbus_message_unref(m);
2493         if (!(m = dbus_message_new_method_call(
2494                               "org.freedesktop.systemd1",
2495                               path,
2496                               "org.freedesktop.DBus.Properties",
2497                               "Get"))) {
2498                 log_error("Could not allocate message.");
2499                 return -ENOMEM;
2500         }
2501
2502         if (!dbus_message_append_args(m,
2503                                       DBUS_TYPE_STRING, &interface,
2504                                       DBUS_TYPE_STRING, &property,
2505                                       DBUS_TYPE_INVALID)) {
2506                 log_error("Could not append arguments to message.");
2507                 r = -ENOMEM;
2508                 goto finish;
2509         }
2510
2511         dbus_message_unref(reply);
2512         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2513                 log_error("Failed to issue method call: %s", error.message);
2514                 r = -EIO;
2515                 goto finish;
2516         }
2517
2518         if (!dbus_message_iter_init(reply, &iter) ||
2519             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
2520                 log_error("Failed to parse reply.");
2521                 r = -EIO;
2522                 goto finish;
2523         }
2524
2525         dbus_message_iter_recurse(&iter, &sub);
2526
2527         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
2528                 log_error("Failed to parse reply.");
2529                 r = -EIO;
2530                 goto finish;
2531         }
2532
2533         dbus_message_iter_get_basic(&sub, &id);
2534
2535         if (!arg_quiet)
2536                 puts(id);
2537         r = 0;
2538
2539 finish:
2540         if (m)
2541                 dbus_message_unref(m);
2542
2543         if (reply)
2544                 dbus_message_unref(reply);
2545
2546         dbus_error_free(&error);
2547
2548         return r;
2549 }
2550
2551 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
2552         DBusMessage *m = NULL, *reply = NULL;
2553         int r;
2554         DBusError error;
2555         unsigned i;
2556
2557         assert(bus);
2558         assert(args);
2559
2560         dbus_error_init(&error);
2561
2562         for (i = 1; i < n; i++) {
2563                 const char *path = NULL;
2564
2565                 if (!(m = dbus_message_new_method_call(
2566                                       "org.freedesktop.systemd1",
2567                                       "/org/freedesktop/systemd1",
2568                                       "org.freedesktop.systemd1.Manager",
2569                                       "GetUnit"))) {
2570                         log_error("Could not allocate message.");
2571                         r = -ENOMEM;
2572                         goto finish;
2573                 }
2574
2575                 if (!dbus_message_append_args(m,
2576                                               DBUS_TYPE_STRING, &args[i],
2577                                               DBUS_TYPE_INVALID)) {
2578                         log_error("Could not append arguments to message.");
2579                         r = -ENOMEM;
2580                         goto finish;
2581                 }
2582
2583                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2584                         log_error("Failed to issue method call: %s", error.message);
2585                         r = -EIO;
2586                         goto finish;
2587                 }
2588
2589                 if (!dbus_message_get_args(reply, &error,
2590                                            DBUS_TYPE_OBJECT_PATH, &path,
2591                                            DBUS_TYPE_INVALID)) {
2592                         log_error("Failed to parse reply: %s", error.message);
2593                         r = -EIO;
2594                         goto finish;
2595                 }
2596
2597                 dbus_message_unref(m);
2598                 if (!(m = dbus_message_new_method_call(
2599                                       "org.freedesktop.systemd1",
2600                                       path,
2601                                       "org.freedesktop.systemd1.Snapshot",
2602                                       "Remove"))) {
2603                         log_error("Could not allocate message.");
2604                         r = -ENOMEM;
2605                         goto finish;
2606                 }
2607
2608                 dbus_message_unref(reply);
2609                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2610                         log_error("Failed to issue method call: %s", error.message);
2611                         r = -EIO;
2612                         goto finish;
2613                 }
2614
2615                 dbus_message_unref(m);
2616                 dbus_message_unref(reply);
2617                 m = reply = NULL;
2618         }
2619
2620         r = 0;
2621
2622 finish:
2623         if (m)
2624                 dbus_message_unref(m);
2625
2626         if (reply)
2627                 dbus_message_unref(reply);
2628
2629         dbus_error_free(&error);
2630
2631         return r;
2632 }
2633
2634 static int clear_jobs(DBusConnection *bus, char **args, unsigned n) {
2635         DBusMessage *m = NULL, *reply = NULL;
2636         DBusError error;
2637         int r;
2638         const char *method;
2639
2640         dbus_error_init(&error);
2641
2642         if (arg_action == ACTION_RELOAD)
2643                 method = "Reload";
2644         else if (arg_action == ACTION_REEXEC)
2645                 method = "Reexecute";
2646         else {
2647                 assert(arg_action == ACTION_SYSTEMCTL);
2648
2649                 method =
2650                         streq(args[0], "clear-jobs")        ? "ClearJobs" :
2651                         streq(args[0], "daemon-reload")     ? "Reload" :
2652                         streq(args[0], "daemon-reexec")     ? "Reexecute" :
2653                         streq(args[0], "reset-maintenance") ? "ResetMaintenance" :
2654                                                               "Exit";
2655         }
2656
2657         if (!(m = dbus_message_new_method_call(
2658                               "org.freedesktop.systemd1",
2659                               "/org/freedesktop/systemd1",
2660                               "org.freedesktop.systemd1.Manager",
2661                               method))) {
2662                 log_error("Could not allocate message.");
2663                 return -ENOMEM;
2664         }
2665
2666         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2667
2668                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
2669                         /* There's always a fallback possible for
2670                          * legacy actions. */
2671                         r = 0;
2672                         goto finish;
2673                 }
2674
2675                 log_error("Failed to issue method call: %s", error.message);
2676                 r = -EIO;
2677                 goto finish;
2678         }
2679
2680         r = 1;
2681
2682 finish:
2683         if (m)
2684                 dbus_message_unref(m);
2685
2686         if (reply)
2687                 dbus_message_unref(reply);
2688
2689         dbus_error_free(&error);
2690
2691         return r;
2692 }
2693
2694 static int reset_maintenance(DBusConnection *bus, char **args, unsigned n) {
2695         DBusMessage *m = NULL, *reply = NULL;
2696         unsigned i;
2697         int r;
2698         DBusError error;
2699
2700         assert(bus);
2701         dbus_error_init(&error);
2702
2703         if (n <= 1)
2704                 return clear_jobs(bus, args, n);
2705
2706         for (i = 1; i < n; i++) {
2707
2708                 if (!(m = dbus_message_new_method_call(
2709                                       "org.freedesktop.systemd1",
2710                                       "/org/freedesktop/systemd1",
2711                                       "org.freedesktop.systemd1.Manager",
2712                                       "ResetMaintenanceUnit"))) {
2713                         log_error("Could not allocate message.");
2714                         r = -ENOMEM;
2715                         goto finish;
2716                 }
2717
2718                 if (!dbus_message_append_args(m,
2719                                               DBUS_TYPE_STRING, args + i,
2720                                               DBUS_TYPE_INVALID)) {
2721                         log_error("Could not append arguments to message.");
2722                         r = -ENOMEM;
2723                         goto finish;
2724                 }
2725
2726                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2727                         log_error("Failed to issue method call: %s", error.message);
2728                         r = -EIO;
2729                         goto finish;
2730                 }
2731
2732                 dbus_message_unref(m);
2733                 dbus_message_unref(reply);
2734                 m = reply = NULL;
2735         }
2736
2737         r = 0;
2738
2739 finish:
2740         if (m)
2741                 dbus_message_unref(m);
2742
2743         if (reply)
2744                 dbus_message_unref(reply);
2745
2746         dbus_error_free(&error);
2747
2748         return r;
2749 }
2750
2751 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
2752         DBusMessage *m = NULL, *reply = NULL;
2753         DBusError error;
2754         DBusMessageIter iter, sub, sub2;
2755         int r;
2756         const char
2757                 *interface = "org.freedesktop.systemd1.Manager",
2758                 *property = "Environment";
2759
2760         dbus_error_init(&error);
2761
2762         if (!(m = dbus_message_new_method_call(
2763                               "org.freedesktop.systemd1",
2764                               "/org/freedesktop/systemd1",
2765                               "org.freedesktop.DBus.Properties",
2766                               "Get"))) {
2767                 log_error("Could not allocate message.");
2768                 return -ENOMEM;
2769         }
2770
2771         if (!dbus_message_append_args(m,
2772                                       DBUS_TYPE_STRING, &interface,
2773                                       DBUS_TYPE_STRING, &property,
2774                                       DBUS_TYPE_INVALID)) {
2775                 log_error("Could not append arguments to message.");
2776                 r = -ENOMEM;
2777                 goto finish;
2778         }
2779
2780         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2781                 log_error("Failed to issue method call: %s", error.message);
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_ARRAY ||
2796             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
2797                 log_error("Failed to parse reply.");
2798                 r = -EIO;
2799                 goto finish;
2800         }
2801
2802         dbus_message_iter_recurse(&sub, &sub2);
2803
2804         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2805                 const char *text;
2806
2807                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2808                         log_error("Failed to parse reply.");
2809                         r = -EIO;
2810                         goto finish;
2811                 }
2812
2813                 dbus_message_iter_get_basic(&sub2, &text);
2814                 printf("%s\n", text);
2815
2816                 dbus_message_iter_next(&sub2);
2817         }
2818
2819         r = 0;
2820
2821 finish:
2822         if (m)
2823                 dbus_message_unref(m);
2824
2825         if (reply)
2826                 dbus_message_unref(reply);
2827
2828         dbus_error_free(&error);
2829
2830         return r;
2831 }
2832
2833 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
2834         DBusMessage *m = NULL, *reply = NULL;
2835         DBusError error;
2836         int r;
2837         const char *method;
2838         DBusMessageIter iter, sub;
2839         unsigned i;
2840
2841         dbus_error_init(&error);
2842
2843         method = streq(args[0], "set-environment")
2844                 ? "SetEnvironment"
2845                 : "UnsetEnvironment";
2846
2847         if (!(m = dbus_message_new_method_call(
2848                               "org.freedesktop.systemd1",
2849                               "/org/freedesktop/systemd1",
2850                               "org.freedesktop.systemd1.Manager",
2851                               method))) {
2852
2853                 log_error("Could not allocate message.");
2854                 return -ENOMEM;
2855         }
2856
2857         dbus_message_iter_init_append(m, &iter);
2858
2859         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
2860                 log_error("Could not append arguments to message.");
2861                 r = -ENOMEM;
2862                 goto finish;
2863         }
2864
2865         for (i = 1; i < n; i++)
2866                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
2867                         log_error("Could not append arguments to message.");
2868                         r = -ENOMEM;
2869                         goto finish;
2870                 }
2871
2872         if (!dbus_message_iter_close_container(&iter, &sub)) {
2873                 log_error("Could not append arguments to message.");
2874                 r = -ENOMEM;
2875                 goto finish;
2876         }
2877
2878         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2879                 log_error("Failed to issue method call: %s", error.message);
2880                 r = -EIO;
2881                 goto finish;
2882         }
2883
2884         r = 0;
2885
2886 finish:
2887         if (m)
2888                 dbus_message_unref(m);
2889
2890         if (reply)
2891                 dbus_message_unref(reply);
2892
2893         dbus_error_free(&error);
2894
2895         return r;
2896 }
2897
2898 static int systemctl_help(void) {
2899
2900         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
2901                "Send control commands to or query the systemd manager.\n\n"
2902                "  -h --help          Show this help\n"
2903                "  -t --type=TYPE     List only units of a particular type\n"
2904                "  -p --property=NAME Show only properties by this name\n"
2905                "  -a --all           Show all units/properties, including dead/empty ones\n"
2906                "     --full          Don't ellipsize unit names.\n"
2907                "     --fail          When installing a new job, fail if conflicting jobs are\n"
2908                "                     pending\n"
2909                "     --system        Connect to system bus\n"
2910                "     --session       Connect to session bus\n"
2911                "     --order         When generating graph for dot, show only order\n"
2912                "     --require        When generating graph for dot, show only requirement\n"
2913                "  -q --quiet         Suppress output\n"
2914                "     --no-block      Do not wait until operation finished\n"
2915                "     --no-wall       Don't send wall message before halt/power-off/reboot\n\n"
2916                "Commands:\n"
2917                "  list-units                      List units\n"
2918                "  start [NAME...]                 Start one or more units\n"
2919                "  stop [NAME...]                  Stop one or more units\n"
2920                "  reload [NAME...]                Reload one or more units\n"
2921                "  restart [NAME...]               Start or restart one or more units\n"
2922                "  try-restart [NAME...]           Restart one or more units if active\n"
2923                "  reload-or-restart [NAME...]     Reload one or more units is possible,\n"
2924                "                                  otherwise start or restart\n"
2925                "  reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
2926                "                                  otherwise restart if active\n"
2927                "  isolate [NAME]                  Start one unit and stop all others\n"
2928                "  check [NAME...]                 Check whether units are active\n"
2929                "  status [NAME...]                Show status of one or more units\n"
2930                "  show [NAME...|JOB...]           Show properties of one or more\n"
2931                "                                  units/jobs/manager\n"
2932                "  reset-maintenance [NAME...]     Reset maintenance state for all, one\n"
2933                "                                  or more units\n"
2934                "  load [NAME...]                  Load one or more units\n"
2935                "  list-jobs                       List jobs\n"
2936                "  cancel [JOB...]                 Cancel one or more jobs\n"
2937                "  clear-jobs                      Cancel all jobs\n"
2938                "  monitor                         Monitor unit/job changes\n"
2939                "  dump                            Dump server status\n"
2940                "  dot                             Dump dependency graph for dot(1)\n"
2941                "  snapshot [NAME]                 Create a snapshot\n"
2942                "  delete [NAME...]                Remove one or more snapshots\n"
2943                "  daemon-reload                   Reload systemd manager configuration\n"
2944                "  daemon-reexec                   Reexecute systemd manager\n"
2945                "  daemon-exit                     Ask the systemd manager to quit\n"
2946                "  show-environment                Dump environment\n"
2947                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
2948                "  unset-environment [NAME...]     Unset one or more environment variables\n"
2949                "  halt                            Shut down and halt the system\n"
2950                "  poweroff                        Shut down and power-off the system\n"
2951                "  reboot                          Shut down and reboot the system\n"
2952                "  rescue                          Enter system rescue mode\n"
2953                "  emergency                       Enter system emergency mode\n"
2954                "  default                         Enter system default mode\n",
2955                program_invocation_short_name);
2956
2957         return 0;
2958 }
2959
2960 static int halt_help(void) {
2961
2962         printf("%s [OPTIONS...]\n\n"
2963                "%s the system.\n\n"
2964                "     --help      Show this help\n"
2965                "     --halt      Halt the machine\n"
2966                "  -p --poweroff  Switch off the machine\n"
2967                "     --reboot    Reboot the machine\n"
2968                "  -f --force     Force immediate halt/power-off/reboot\n"
2969                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
2970                "  -d --no-wtmp   Don't write wtmp record\n"
2971                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
2972                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
2973                program_invocation_short_name,
2974                arg_action == ACTION_REBOOT   ? "Reboot" :
2975                arg_action == ACTION_POWEROFF ? "Power off" :
2976                                                "Halt");
2977
2978         return 0;
2979 }
2980
2981 static int shutdown_help(void) {
2982
2983         printf("%s [OPTIONS...] [now] [WALL...]\n\n"
2984                "Shut down the system.\n\n"
2985                "     --help      Show this help\n"
2986                "  -H --halt      Halt the machine\n"
2987                "  -P --poweroff  Power-off the machine\n"
2988                "  -r --reboot    Reboot the machine\n"
2989                "  -h             Equivalent to --poweroff, overriden by --halt\n"
2990                "  -k             Don't halt/power-off/reboot, just send warnings\n"
2991                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
2992                program_invocation_short_name);
2993
2994         return 0;
2995 }
2996
2997 static int telinit_help(void) {
2998
2999         printf("%s [OPTIONS...] {COMMAND}\n\n"
3000                "Send control commands to the init daemon.\n\n"
3001                "     --help      Show this help\n"
3002                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
3003                "Commands:\n"
3004                "  0              Power-off the machine\n"
3005                "  6              Reboot the machine\n"
3006                "  2, 3, 4, 5     Start runlevelX.target unit\n"
3007                "  1, s, S        Enter rescue mode\n"
3008                "  q, Q           Reload init daemon configuration\n"
3009                "  u, U           Reexecute init daemon\n",
3010                program_invocation_short_name);
3011
3012         return 0;
3013 }
3014
3015 static int runlevel_help(void) {
3016
3017         printf("%s [OPTIONS...]\n\n"
3018                "Prints the previous and current runlevel of the init system.\n\n"
3019                "     --help      Show this help\n",
3020                program_invocation_short_name);
3021
3022         return 0;
3023 }
3024
3025 static int systemctl_parse_argv(int argc, char *argv[]) {
3026
3027         enum {
3028                 ARG_FAIL = 0x100,
3029                 ARG_SESSION,
3030                 ARG_SYSTEM,
3031                 ARG_NO_BLOCK,
3032                 ARG_NO_WALL,
3033                 ARG_ORDER,
3034                 ARG_REQUIRE,
3035                 ARG_FULL
3036         };
3037
3038         static const struct option options[] = {
3039                 { "help",      no_argument,       NULL, 'h'          },
3040                 { "type",      required_argument, NULL, 't'          },
3041                 { "property",  required_argument, NULL, 'p'          },
3042                 { "all",       no_argument,       NULL, 'a'          },
3043                 { "full",      no_argument,       NULL, ARG_FULL     },
3044                 { "fail",      no_argument,       NULL, ARG_FAIL     },
3045                 { "session",   no_argument,       NULL, ARG_SESSION  },
3046                 { "system",    no_argument,       NULL, ARG_SYSTEM   },
3047                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK },
3048                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL  },
3049                 { "quiet",     no_argument,       NULL, 'q'          },
3050                 { "order",     no_argument,       NULL, ARG_ORDER    },
3051                 { "require",   no_argument,       NULL, ARG_REQUIRE  },
3052                 { NULL,        0,                 NULL, 0            }
3053         };
3054
3055         int c;
3056
3057         assert(argc >= 0);
3058         assert(argv);
3059
3060         while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
3061
3062                 switch (c) {
3063
3064                 case 'h':
3065                         systemctl_help();
3066                         return 0;
3067
3068                 case 't':
3069                         arg_type = optarg;
3070                         break;
3071
3072                 case 'p':
3073                         arg_property = optarg;
3074
3075                         /* If the user asked for a particular
3076                          * property, show it to him, even if it is
3077                          * empty. */
3078                         arg_all = true;
3079                         break;
3080
3081                 case 'a':
3082                         arg_all = true;
3083                         break;
3084
3085                 case ARG_FAIL:
3086                         arg_fail = true;
3087                         break;
3088
3089                 case ARG_SESSION:
3090                         arg_session = true;
3091                         break;
3092
3093                 case ARG_SYSTEM:
3094                         arg_session = false;
3095                         break;
3096
3097                 case ARG_NO_BLOCK:
3098                         arg_no_block = true;
3099                         break;
3100
3101                 case ARG_NO_WALL:
3102                         arg_no_wall = true;
3103                         break;
3104
3105                 case ARG_ORDER:
3106                         arg_dot = DOT_ORDER;
3107                         break;
3108
3109                 case ARG_REQUIRE:
3110                         arg_dot = DOT_REQUIRE;
3111                         break;
3112
3113                 case ARG_FULL:
3114                         arg_full = true;
3115                         break;
3116
3117                 case 'q':
3118                         arg_quiet = true;
3119                         break;
3120
3121                 case '?':
3122                         return -EINVAL;
3123
3124                 default:
3125                         log_error("Unknown option code %c", c);
3126                         return -EINVAL;
3127                 }
3128         }
3129
3130         return 1;
3131 }
3132
3133 static int halt_parse_argv(int argc, char *argv[]) {
3134
3135         enum {
3136                 ARG_HELP = 0x100,
3137                 ARG_HALT,
3138                 ARG_REBOOT,
3139                 ARG_NO_WALL
3140         };
3141
3142         static const struct option options[] = {
3143                 { "help",      no_argument,       NULL, ARG_HELP    },
3144                 { "halt",      no_argument,       NULL, ARG_HALT    },
3145                 { "poweroff",  no_argument,       NULL, 'p'         },
3146                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
3147                 { "force",     no_argument,       NULL, 'f'         },
3148                 { "wtmp-only", no_argument,       NULL, 'w'         },
3149                 { "no-wtmp",   no_argument,       NULL, 'd'         },
3150                 { "no-sync",   no_argument,       NULL, 'n'         },
3151                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
3152                 { NULL,        0,                 NULL, 0           }
3153         };
3154
3155         int c, runlevel;
3156
3157         assert(argc >= 0);
3158         assert(argv);
3159
3160         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
3161                 if (runlevel == '0' || runlevel == '6')
3162                         arg_immediate = true;
3163
3164         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
3165                 switch (c) {
3166
3167                 case ARG_HELP:
3168                         halt_help();
3169                         return 0;
3170
3171                 case ARG_HALT:
3172                         arg_action = ACTION_HALT;
3173                         break;
3174
3175                 case 'p':
3176                         arg_action = ACTION_POWEROFF;
3177                         break;
3178
3179                 case ARG_REBOOT:
3180                         arg_action = ACTION_REBOOT;
3181                         break;
3182
3183                 case 'f':
3184                         arg_immediate = true;
3185                         break;
3186
3187                 case 'w':
3188                         arg_dry = true;
3189                         break;
3190
3191                 case 'd':
3192                         arg_no_wtmp = true;
3193                         break;
3194
3195                 case 'n':
3196                         arg_no_sync = true;
3197                         break;
3198
3199                 case ARG_NO_WALL:
3200                         arg_no_wall = true;
3201                         break;
3202
3203                 case 'i':
3204                 case 'h':
3205                         /* Compatibility nops */
3206                         break;
3207
3208                 case '?':
3209                         return -EINVAL;
3210
3211                 default:
3212                         log_error("Unknown option code %c", c);
3213                         return -EINVAL;
3214                 }
3215         }
3216
3217         if (optind < argc) {
3218                 log_error("Too many arguments.");
3219                 return -EINVAL;
3220         }
3221
3222         return 1;
3223 }
3224
3225 static int shutdown_parse_argv(int argc, char *argv[]) {
3226
3227         enum {
3228                 ARG_HELP = 0x100,
3229                 ARG_NO_WALL
3230         };
3231
3232         static const struct option options[] = {
3233                 { "help",      no_argument,       NULL, ARG_HELP    },
3234                 { "halt",      no_argument,       NULL, 'H'         },
3235                 { "poweroff",  no_argument,       NULL, 'P'         },
3236                 { "reboot",    no_argument,       NULL, 'r'         },
3237                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
3238                 { NULL,        0,                 NULL, 0           }
3239         };
3240
3241         int c;
3242
3243         assert(argc >= 0);
3244         assert(argv);
3245
3246         while ((c = getopt_long(argc, argv, "HPrhkt:a", options, NULL)) >= 0) {
3247                 switch (c) {
3248
3249                 case ARG_HELP:
3250                         shutdown_help();
3251                         return 0;
3252
3253                 case 'H':
3254                         arg_action = ACTION_HALT;
3255                         break;
3256
3257                 case 'P':
3258                         arg_action = ACTION_POWEROFF;
3259                         break;
3260
3261                 case 'r':
3262                         arg_action = ACTION_REBOOT;
3263                         break;
3264
3265                 case 'h':
3266                         if (arg_action != ACTION_HALT)
3267                                 arg_action = ACTION_POWEROFF;
3268                         break;
3269
3270                 case 'k':
3271                         arg_dry = true;
3272                         break;
3273
3274                 case ARG_NO_WALL:
3275                         arg_no_wall = true;
3276                         break;
3277
3278                 case 't':
3279                 case 'a':
3280                         /* Compatibility nops */
3281                         break;
3282
3283                 case '?':
3284                         return -EINVAL;
3285
3286                 default:
3287                         log_error("Unknown option code %c", c);
3288                         return -EINVAL;
3289                 }
3290         }
3291
3292         if (argc > optind && !streq(argv[optind], "now"))
3293                 log_warning("First argument '%s' isn't 'now'. Ignoring.", argv[optind]);
3294
3295         /* We ignore the time argument */
3296         if (argc > optind + 1)
3297                 arg_wall = argv + optind + 1;
3298
3299         optind = argc;
3300
3301         return 1;
3302 }
3303
3304 static int telinit_parse_argv(int argc, char *argv[]) {
3305
3306         enum {
3307                 ARG_HELP = 0x100,
3308                 ARG_NO_WALL
3309         };
3310
3311         static const struct option options[] = {
3312                 { "help",      no_argument,       NULL, ARG_HELP    },
3313                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
3314                 { NULL,        0,                 NULL, 0           }
3315         };
3316
3317         static const struct {
3318                 char from;
3319                 enum action to;
3320         } table[] = {
3321                 { '0', ACTION_POWEROFF },
3322                 { '6', ACTION_REBOOT },
3323                 { '1', ACTION_RESCUE },
3324                 { '2', ACTION_RUNLEVEL2 },
3325                 { '3', ACTION_RUNLEVEL3 },
3326                 { '4', ACTION_RUNLEVEL4 },
3327                 { '5', ACTION_RUNLEVEL5 },
3328                 { 's', ACTION_RESCUE },
3329                 { 'S', ACTION_RESCUE },
3330                 { 'q', ACTION_RELOAD },
3331                 { 'Q', ACTION_RELOAD },
3332                 { 'u', ACTION_REEXEC },
3333                 { 'U', ACTION_REEXEC }
3334         };
3335
3336         unsigned i;
3337         int c;
3338
3339         assert(argc >= 0);
3340         assert(argv);
3341
3342         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
3343                 switch (c) {
3344
3345                 case ARG_HELP:
3346                         telinit_help();
3347                         return 0;
3348
3349                 case ARG_NO_WALL:
3350                         arg_no_wall = true;
3351                         break;
3352
3353                 case '?':
3354                         return -EINVAL;
3355
3356                 default:
3357                         log_error("Unknown option code %c", c);
3358                         return -EINVAL;
3359                 }
3360         }
3361
3362         if (optind >= argc) {
3363                 telinit_help();
3364                 return -EINVAL;
3365         }
3366
3367         if (optind + 1 < argc) {
3368                 log_error("Too many arguments.");
3369                 return -EINVAL;
3370         }
3371
3372         if (strlen(argv[optind]) != 1) {
3373                 log_error("Expected single character argument.");
3374                 return -EINVAL;
3375         }
3376
3377         for (i = 0; i < ELEMENTSOF(table); i++)
3378                 if (table[i].from == argv[optind][0])
3379                         break;
3380
3381         if (i >= ELEMENTSOF(table)) {
3382                 log_error("Unknown command %s.", argv[optind]);
3383                 return -EINVAL;
3384         }
3385
3386         arg_action = table[i].to;
3387
3388         optind ++;
3389
3390         return 1;
3391 }
3392
3393 static int runlevel_parse_argv(int argc, char *argv[]) {
3394
3395         enum {
3396                 ARG_HELP = 0x100,
3397         };
3398
3399         static const struct option options[] = {
3400                 { "help",      no_argument,       NULL, ARG_HELP    },
3401                 { NULL,        0,                 NULL, 0           }
3402         };
3403
3404         int c;
3405
3406         assert(argc >= 0);
3407         assert(argv);
3408
3409         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
3410                 switch (c) {
3411
3412                 case ARG_HELP:
3413                         runlevel_help();
3414                         return 0;
3415
3416                 case '?':
3417                         return -EINVAL;
3418
3419                 default:
3420                         log_error("Unknown option code %c", c);
3421                         return -EINVAL;
3422                 }
3423         }
3424
3425         if (optind < argc) {
3426                 log_error("Too many arguments.");
3427                 return -EINVAL;
3428         }
3429
3430         return 1;
3431 }
3432
3433 static int parse_argv(int argc, char *argv[]) {
3434         assert(argc >= 0);
3435         assert(argv);
3436
3437         if (program_invocation_short_name) {
3438
3439                 if (strstr(program_invocation_short_name, "halt")) {
3440                         arg_action = ACTION_HALT;
3441                         return halt_parse_argv(argc, argv);
3442                 } else if (strstr(program_invocation_short_name, "poweroff")) {
3443                         arg_action = ACTION_POWEROFF;
3444                         return halt_parse_argv(argc, argv);
3445                 } else if (strstr(program_invocation_short_name, "reboot")) {
3446                         arg_action = ACTION_REBOOT;
3447                         return halt_parse_argv(argc, argv);
3448                 } else if (strstr(program_invocation_short_name, "shutdown")) {
3449                         arg_action = ACTION_POWEROFF;
3450                         return shutdown_parse_argv(argc, argv);
3451                 } else if (strstr(program_invocation_short_name, "init")) {
3452                         arg_action = ACTION_INVALID;
3453                         return telinit_parse_argv(argc, argv);
3454                 } else if (strstr(program_invocation_short_name, "runlevel")) {
3455                         arg_action = ACTION_RUNLEVEL;
3456                         return runlevel_parse_argv(argc, argv);
3457                 }
3458         }
3459
3460         arg_action = ACTION_SYSTEMCTL;
3461         return systemctl_parse_argv(argc, argv);
3462 }
3463
3464 static int action_to_runlevel(void) {
3465
3466         static const char table[_ACTION_MAX] = {
3467                 [ACTION_HALT] =      '0',
3468                 [ACTION_POWEROFF] =  '0',
3469                 [ACTION_REBOOT] =    '6',
3470                 [ACTION_RUNLEVEL2] = '2',
3471                 [ACTION_RUNLEVEL3] = '3',
3472                 [ACTION_RUNLEVEL4] = '4',
3473                 [ACTION_RUNLEVEL5] = '5',
3474                 [ACTION_RESCUE] =    '1'
3475         };
3476
3477         assert(arg_action < _ACTION_MAX);
3478
3479         return table[arg_action];
3480 }
3481
3482 static int talk_upstart(void) {
3483         DBusMessage *m = NULL, *reply = NULL;
3484         DBusError error;
3485         int previous, rl, r;
3486         char
3487                 env1_buf[] = "RUNLEVEL=X",
3488                 env2_buf[] = "PREVLEVEL=X";
3489         char *env1 = env1_buf, *env2 = env2_buf;
3490         const char *emit = "runlevel";
3491         dbus_bool_t b_false = FALSE;
3492         DBusMessageIter iter, sub;
3493         DBusConnection *bus;
3494
3495         dbus_error_init(&error);
3496
3497         if (!(rl = action_to_runlevel()))
3498                 return 0;
3499
3500         if (utmp_get_runlevel(&previous, NULL) < 0)
3501                 previous = 'N';
3502
3503         if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
3504                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
3505                         r = 0;
3506                         goto finish;
3507                 }
3508
3509                 log_error("Failed to connect to Upstart bus: %s", error.message);
3510                 r = -EIO;
3511                 goto finish;
3512         }
3513
3514         if ((r = bus_check_peercred(bus)) < 0) {
3515                 log_error("Failed to verify owner of bus.");
3516                 goto finish;
3517         }
3518
3519         if (!(m = dbus_message_new_method_call(
3520                               "com.ubuntu.Upstart",
3521                               "/com/ubuntu/Upstart",
3522                               "com.ubuntu.Upstart0_6",
3523                               "EmitEvent"))) {
3524
3525                 log_error("Could not allocate message.");
3526                 r = -ENOMEM;
3527                 goto finish;
3528         }
3529
3530         dbus_message_iter_init_append(m, &iter);
3531
3532         env1_buf[sizeof(env1_buf)-2] = rl;
3533         env2_buf[sizeof(env2_buf)-2] = previous;
3534
3535         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
3536             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
3537             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
3538             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
3539             !dbus_message_iter_close_container(&iter, &sub) ||
3540             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
3541                 log_error("Could not append arguments to message.");
3542                 r = -ENOMEM;
3543                 goto finish;
3544         }
3545
3546         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
3547
3548                 if (error_is_no_service(&error)) {
3549                         r = 0;
3550                         goto finish;
3551                 }
3552
3553                 log_error("Failed to issue method call: %s", error.message);
3554                 r = -EIO;
3555                 goto finish;
3556         }
3557
3558         r = 1;
3559
3560 finish:
3561         if (m)
3562                 dbus_message_unref(m);
3563
3564         if (reply)
3565                 dbus_message_unref(reply);
3566
3567         if (bus) {
3568                 dbus_connection_close(bus);
3569                 dbus_connection_unref(bus);
3570         }
3571
3572         dbus_error_free(&error);
3573
3574         return r;
3575 }
3576
3577 static int talk_initctl(void) {
3578         struct init_request request;
3579         int r, fd;
3580         char rl;
3581
3582         if (!(rl = action_to_runlevel()))
3583                 return 0;
3584
3585         zero(request);
3586         request.magic = INIT_MAGIC;
3587         request.sleeptime = 0;
3588         request.cmd = INIT_CMD_RUNLVL;
3589         request.runlevel = rl;
3590
3591         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
3592
3593                 if (errno == ENOENT)
3594                         return 0;
3595
3596                 log_error("Failed to open "INIT_FIFO": %m");
3597                 return -errno;
3598         }
3599
3600         errno = 0;
3601         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
3602         close_nointr_nofail(fd);
3603
3604         if (r < 0) {
3605                 log_error("Failed to write to "INIT_FIFO": %m");
3606                 return errno ? -errno : -EIO;
3607         }
3608
3609         return 1;
3610 }
3611
3612 static int systemctl_main(DBusConnection *bus, int argc, char *argv[]) {
3613
3614         static const struct {
3615                 const char* verb;
3616                 const enum {
3617                         MORE,
3618                         LESS,
3619                         EQUAL
3620                 } argc_cmp;
3621                 const int argc;
3622                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
3623         } verbs[] = {
3624                 { "list-units",        LESS,  1, list_units      },
3625                 { "list-jobs",         EQUAL, 1, list_jobs       },
3626                 { "clear-jobs",        EQUAL, 1, clear_jobs      },
3627                 { "load",              MORE,  2, load_unit       },
3628                 { "cancel",            MORE,  2, cancel_job      },
3629                 { "start",             MORE,  2, start_unit      },
3630                 { "stop",              MORE,  2, start_unit      },
3631                 { "reload",            MORE,  2, start_unit      },
3632                 { "restart",           MORE,  2, start_unit      },
3633                 { "try-restart",       MORE,  2, start_unit      },
3634                 { "reload-or-restart", MORE,  2, start_unit      },
3635                 { "reload-or-try-restart", MORE, 2, start_unit   },
3636                 { "isolate",           EQUAL, 2, start_unit      },
3637                 { "check",             MORE,  2, check_unit      },
3638                 { "show",              MORE,  1, show            },
3639                 { "status",            MORE,  2, show            },
3640                 { "monitor",           EQUAL, 1, monitor         },
3641                 { "dump",              EQUAL, 1, dump            },
3642                 { "dot",               EQUAL, 1, dot             },
3643                 { "snapshot",          LESS,  2, snapshot        },
3644                 { "delete",            MORE,  2, delete_snapshot },
3645                 { "daemon-reload",     EQUAL, 1, clear_jobs      },
3646                 { "daemon-reexec",     EQUAL, 1, clear_jobs      },
3647                 { "daemon-exit",       EQUAL, 1, clear_jobs      },
3648                 { "show-environment",  EQUAL, 1, show_enviroment },
3649                 { "set-environment",   MORE,  2, set_environment },
3650                 { "unset-environment", MORE,  2, set_environment },
3651                 { "halt",              EQUAL, 1, start_special   },
3652                 { "poweroff",          EQUAL, 1, start_special   },
3653                 { "reboot",            EQUAL, 1, start_special   },
3654                 { "default",           EQUAL, 1, start_special   },
3655                 { "rescue",            EQUAL, 1, start_special   },
3656                 { "emergency",         EQUAL, 1, start_special   },
3657                 { "reset-maintenance", MORE,  1, reset_maintenance },
3658         };
3659
3660         int left;
3661         unsigned i;
3662
3663         assert(bus);
3664         assert(argc >= 0);
3665         assert(argv);
3666
3667         left = argc - optind;
3668
3669         if (left <= 0)
3670                 /* Special rule: no arguments means "list-units" */
3671                 i = 0;
3672         else {
3673                 if (streq(argv[optind], "help")) {
3674                         systemctl_help();
3675                         return 0;
3676                 }
3677
3678                 for (i = 0; i < ELEMENTSOF(verbs); i++)
3679                         if (streq(argv[optind], verbs[i].verb))
3680                                 break;
3681
3682                 if (i >= ELEMENTSOF(verbs)) {
3683                         log_error("Unknown operation %s", argv[optind]);
3684                         return -EINVAL;
3685                 }
3686         }
3687
3688         switch (verbs[i].argc_cmp) {
3689
3690         case EQUAL:
3691                 if (left != verbs[i].argc) {
3692                         log_error("Invalid number of arguments.");
3693                         return -EINVAL;
3694                 }
3695
3696                 break;
3697
3698         case MORE:
3699                 if (left < verbs[i].argc) {
3700                         log_error("Too few arguments.");
3701                         return -EINVAL;
3702                 }
3703
3704                 break;
3705
3706         case LESS:
3707                 if (left > verbs[i].argc) {
3708                         log_error("Too many arguments.");
3709                         return -EINVAL;
3710                 }
3711
3712                 break;
3713
3714         default:
3715                 assert_not_reached("Unknown comparison operator.");
3716         }
3717
3718         return verbs[i].dispatch(bus, argv + optind, left);
3719 }
3720
3721 static int reload_with_fallback(DBusConnection *bus) {
3722         int r;
3723
3724         if (bus) {
3725                 /* First, try systemd via D-Bus. */
3726                 if ((r = clear_jobs(bus, NULL, 0)) > 0)
3727                         return 0;
3728         }
3729
3730         /* Nothing else worked, so let's try signals */
3731         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
3732
3733         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
3734                 log_error("kill() failed: %m");
3735                 return -errno;
3736         }
3737
3738         return 0;
3739 }
3740
3741 static int start_with_fallback(DBusConnection *bus) {
3742         int r;
3743
3744
3745         if (bus) {
3746                 /* First, try systemd via D-Bus. */
3747                 if ((r = start_unit(bus, NULL, 0)) > 0)
3748                         goto done;
3749
3750                 /* Hmm, talking to systemd via D-Bus didn't work. Then
3751                  * let's try to talk to Upstart via D-Bus. */
3752                 if ((r = talk_upstart()) > 0)
3753                         goto done;
3754         }
3755
3756         /* Nothing else worked, so let's try
3757          * /dev/initctl */
3758         if ((r = talk_initctl()) != 0)
3759                 goto done;
3760
3761         log_error("Failed to talk to init daemon.");
3762         return -EIO;
3763
3764 done:
3765         warn_wall(arg_action);
3766         return 0;
3767 }
3768
3769 static int halt_main(DBusConnection *bus) {
3770         int r;
3771
3772         if (geteuid() != 0) {
3773                 log_error("Must to be root.");
3774                 return -EPERM;
3775         }
3776
3777         if (!arg_dry && !arg_immediate)
3778                 return start_with_fallback(bus);
3779
3780         if (!arg_no_wtmp)
3781                 if ((r = utmp_put_shutdown(0)) < 0)
3782                         log_warning("Failed to write utmp record: %s", strerror(-r));
3783
3784         if (!arg_no_sync)
3785                 sync();
3786
3787         if (arg_dry)
3788                 return 0;
3789
3790         /* Make sure C-A-D is handled by the kernel from this
3791          * point on... */
3792         reboot(RB_ENABLE_CAD);
3793
3794         switch (arg_action) {
3795
3796         case ACTION_HALT:
3797                 log_info("Halting");
3798                 reboot(RB_HALT_SYSTEM);
3799                 break;
3800
3801         case ACTION_POWEROFF:
3802                 log_info("Powering off");
3803                 reboot(RB_POWER_OFF);
3804                 break;
3805
3806         case ACTION_REBOOT:
3807                 log_info("Rebooting");
3808                 reboot(RB_AUTOBOOT);
3809                 break;
3810
3811         default:
3812                 assert_not_reached("Unknown halt action.");
3813         }
3814
3815         /* We should never reach this. */
3816         return -ENOSYS;
3817 }
3818
3819 static int runlevel_main(void) {
3820         int r, runlevel, previous;
3821
3822         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
3823                 printf("unknown");
3824                 return r;
3825         }
3826
3827         printf("%c %c\n",
3828                previous <= 0 ? 'N' : previous,
3829                runlevel <= 0 ? 'N' : runlevel);
3830
3831         return 0;
3832 }
3833
3834 int main(int argc, char*argv[]) {
3835         int r, retval = 1;
3836         DBusConnection *bus = NULL;
3837         DBusError error;
3838
3839         dbus_error_init(&error);
3840
3841         log_parse_environment();
3842
3843         if ((r = parse_argv(argc, argv)) < 0)
3844                 goto finish;
3845         else if (r == 0) {
3846                 retval = 0;
3847                 goto finish;
3848         }
3849
3850         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
3851          * let's shortcut this */
3852         if (arg_action == ACTION_RUNLEVEL) {
3853                 retval = runlevel_main() < 0;
3854                 goto finish;
3855         }
3856
3857         bus_connect(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
3858
3859         switch (arg_action) {
3860
3861         case ACTION_SYSTEMCTL: {
3862
3863                 if (!bus) {
3864                         log_error("Failed to get D-Bus connection: %s", error.message);
3865                         goto finish;
3866                 }
3867
3868                 retval = systemctl_main(bus, argc, argv) < 0;
3869                 break;
3870         }
3871
3872         case ACTION_HALT:
3873         case ACTION_POWEROFF:
3874         case ACTION_REBOOT:
3875                 retval = halt_main(bus) < 0;
3876                 break;
3877
3878         case ACTION_RUNLEVEL2:
3879         case ACTION_RUNLEVEL3:
3880         case ACTION_RUNLEVEL4:
3881         case ACTION_RUNLEVEL5:
3882         case ACTION_RESCUE:
3883         case ACTION_EMERGENCY:
3884         case ACTION_DEFAULT:
3885                 retval = start_with_fallback(bus) < 0;
3886                 break;
3887
3888         case ACTION_RELOAD:
3889         case ACTION_REEXEC:
3890                 retval = reload_with_fallback(bus) < 0;
3891                 break;
3892
3893         case ACTION_INVALID:
3894         case ACTION_RUNLEVEL:
3895         default:
3896                 assert_not_reached("Unknown action");
3897         }
3898
3899 finish:
3900
3901         if (bus) {
3902                 dbus_connection_close(bus);
3903                 dbus_connection_unref(bus);
3904         }
3905
3906         dbus_error_free(&error);
3907
3908         dbus_shutdown();
3909
3910         return retval;
3911 }