chiark / gitweb /
dbus: complete coverage of timer units
[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
45 static const char *arg_type = NULL;
46 static const char *arg_property = NULL;
47 static bool arg_all = false;
48 static bool arg_replace = false;
49 static bool arg_session = false;
50 static bool arg_no_block = false;
51 static bool arg_immediate = false;
52 static bool arg_no_wtmp = false;
53 static bool arg_no_sync = false;
54 static bool arg_no_wall = false;
55 static bool arg_dry = false;
56 static bool arg_quiet = false;
57 static char **arg_wall = NULL;
58 enum action {
59         ACTION_INVALID,
60         ACTION_SYSTEMCTL,
61         ACTION_HALT,
62         ACTION_POWEROFF,
63         ACTION_REBOOT,
64         ACTION_RUNLEVEL2,
65         ACTION_RUNLEVEL3,
66         ACTION_RUNLEVEL4,
67         ACTION_RUNLEVEL5,
68         ACTION_RESCUE,
69         ACTION_EMERGENCY,
70         ACTION_DEFAULT,
71         ACTION_RELOAD,
72         ACTION_REEXEC,
73         ACTION_RUNLEVEL,
74         _ACTION_MAX
75 } arg_action = ACTION_SYSTEMCTL;
76
77 static bool error_is_no_service(DBusError *error) {
78
79         assert(error);
80
81         if (!dbus_error_is_set(error))
82                 return false;
83
84         if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
85                 return true;
86
87         if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
88                 return true;
89
90         return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
91 }
92
93 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
94
95         assert(iter);
96         assert(data);
97
98         if (dbus_message_iter_get_arg_type(iter) != type)
99                 return -EIO;
100
101         dbus_message_iter_get_basic(iter, data);
102
103         if (!dbus_message_iter_next(iter) != !next)
104                 return -EIO;
105
106         return 0;
107 }
108
109 static int bus_check_peercred(DBusConnection *c) {
110         int fd;
111         struct ucred ucred;
112         socklen_t l;
113
114         assert(c);
115
116         assert_se(dbus_connection_get_unix_fd(c, &fd));
117
118         l = sizeof(struct ucred);
119         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0) {
120                 log_error("SO_PEERCRED failed: %m");
121                 return -errno;
122         }
123
124         if (l != sizeof(struct ucred)) {
125                 log_error("SO_PEERCRED returned wrong size.");
126                 return -E2BIG;
127         }
128
129         if (ucred.uid != 0)
130                 return -EPERM;
131
132         return 1;
133 }
134
135 static int columns(void) {
136         static int parsed_columns = 0;
137         const char *e;
138
139         if (parsed_columns > 0)
140                 return parsed_columns;
141
142         if ((e = getenv("COLUMNS")))
143                 parsed_columns = atoi(e);
144
145         if (parsed_columns <= 0) {
146                 struct winsize ws;
147                 zero(ws);
148
149                 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
150                         parsed_columns = ws.ws_col;
151         }
152
153         if (parsed_columns <= 0)
154                 parsed_columns = 80;
155
156         return parsed_columns;
157
158 }
159
160 static void warn_wall(enum action action) {
161         static const char *table[_ACTION_MAX] = {
162                 [ACTION_HALT]      = "The system is going down for system halt NOW!",
163                 [ACTION_REBOOT]    = "The system is going down for reboot NOW!",
164                 [ACTION_POWEROFF]  = "The system is going down for power-off NOW!",
165                 [ACTION_RESCUE]    = "The system is going down to rescue mode NOW!",
166                 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
167         };
168
169         if (arg_no_wall)
170                 return;
171
172         if (arg_wall) {
173                 char *p;
174
175                 if (!(p = strv_join(arg_wall, " "))) {
176                         log_error("Failed to join strings.");
177                         return;
178                 }
179
180                 if (*p) {
181                         utmp_wall(p);
182                         free(p);
183                         return;
184                 }
185
186                 free(p);
187         }
188
189         if (!table[action])
190                 return;
191
192         utmp_wall(table[action]);
193 }
194
195 static int list_units(DBusConnection *bus, char **args, unsigned n) {
196         DBusMessage *m = NULL, *reply = NULL;
197         DBusError error;
198         int r;
199         DBusMessageIter iter, sub, sub2;
200         unsigned k = 0;
201
202         dbus_error_init(&error);
203
204         assert(bus);
205
206         if (!(m = dbus_message_new_method_call(
207                               "org.freedesktop.systemd1",
208                               "/org/freedesktop/systemd1",
209                               "org.freedesktop.systemd1.Manager",
210                               "ListUnits"))) {
211                 log_error("Could not allocate message.");
212                 return -ENOMEM;
213         }
214
215         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
216                 log_error("Failed to issue method call: %s", error.message);
217                 r = -EIO;
218                 goto finish;
219         }
220
221         if (!dbus_message_iter_init(reply, &iter) ||
222             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
223             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
224                 log_error("Failed to parse reply.");
225                 r = -EIO;
226                 goto finish;
227         }
228
229         dbus_message_iter_recurse(&iter, &sub);
230
231         printf("%-45s %-6s %-12s %-12s %-15s %s\n", "UNIT", "LOAD", "ACTIVE", "SUB", "JOB", "DESCRIPTION");
232
233         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
234                 const char *id, *description, *load_state, *active_state, *sub_state, *unit_state, *job_type, *job_path, *dot;
235                 uint32_t job_id;
236
237                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
238                         log_error("Failed to parse reply.");
239                         r = -EIO;
240                         goto finish;
241                 }
242
243                 dbus_message_iter_recurse(&sub, &sub2);
244
245                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
246                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
247                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
248                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
249                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
250                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_state, true) < 0 ||
251                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &job_id, true) < 0 ||
252                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &job_type, true) < 0 ||
253                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, false) < 0) {
254                         log_error("Failed to parse reply.");
255                         r = -EIO;
256                         goto finish;
257                 }
258
259                 if ((!arg_type || ((dot = strrchr(id, '.')) &&
260                                    streq(dot+1, arg_type))) &&
261                     (arg_all || !streq(active_state, "inactive"))) {
262
263                         int a = 0, b = 0;
264
265                         printf("%-45s %-6s %-12s %-12s%n", id, load_state, active_state, sub_state, &a);
266
267                         if (job_id != 0)
268                                 printf(" %-15s%n", job_type, &b);
269                         else
270                                 b = 1 + 15;
271
272                         if (a + b + 2 < columns()) {
273                                 if (job_id == 0)
274                                         printf("                ");
275
276                                 printf("%.*s", columns() - a - b - 2, description);
277                         }
278
279                         fputs("\n", stdout);
280                         k++;
281                 }
282
283                 dbus_message_iter_next(&sub);
284         }
285
286         if (arg_all)
287                 printf("\n%u units listed.\n", k);
288         else
289                 printf("\n%u live units listed. Pass --all to see dead units, too.\n", k);
290
291         r = 0;
292
293 finish:
294         if (m)
295                 dbus_message_unref(m);
296
297         if (reply)
298                 dbus_message_unref(reply);
299
300         dbus_error_free(&error);
301
302         return r;
303 }
304
305 static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
306         DBusMessage *m = NULL, *reply = NULL;
307         DBusError error;
308         int r;
309         DBusMessageIter iter, sub, sub2;
310         unsigned k = 0;
311
312         dbus_error_init(&error);
313
314         assert(bus);
315
316         if (!(m = dbus_message_new_method_call(
317                               "org.freedesktop.systemd1",
318                               "/org/freedesktop/systemd1",
319                               "org.freedesktop.systemd1.Manager",
320                               "ListJobs"))) {
321                 log_error("Could not allocate message.");
322                 return -ENOMEM;
323         }
324
325         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
326                 log_error("Failed to issue method call: %s", error.message);
327                 r = -EIO;
328                 goto finish;
329         }
330
331         if (!dbus_message_iter_init(reply, &iter) ||
332             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
333             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
334                 log_error("Failed to parse reply.");
335                 r = -EIO;
336                 goto finish;
337         }
338
339         dbus_message_iter_recurse(&iter, &sub);
340
341         printf("%4s %-45s %-17s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
342
343         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
344                 const char *name, *type, *state, *job_path, *unit_path;
345                 uint32_t id;
346
347                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
348                         log_error("Failed to parse reply.");
349                         r = -EIO;
350                         goto finish;
351                 }
352
353                 dbus_message_iter_recurse(&sub, &sub2);
354
355                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
356                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
357                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
358                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
359                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
360                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
361                         log_error("Failed to parse reply.");
362                         r = -EIO;
363                         goto finish;
364                 }
365
366                 printf("%4u %-45s %-17s %-7s\n", id, name, type, state);
367                 k++;
368
369                 dbus_message_iter_next(&sub);
370         }
371
372         printf("\n%u jobs listed.\n", k);
373         r = 0;
374
375 finish:
376         if (m)
377                 dbus_message_unref(m);
378
379         if (reply)
380                 dbus_message_unref(reply);
381
382         dbus_error_free(&error);
383
384         return r;
385 }
386
387 static int load_unit(DBusConnection *bus, char **args, unsigned n) {
388         DBusMessage *m = NULL, *reply = NULL;
389         DBusError error;
390         int r;
391         unsigned i;
392
393         dbus_error_init(&error);
394
395         assert(bus);
396         assert(args);
397
398         for (i = 1; i < n; i++) {
399
400                 if (!(m = dbus_message_new_method_call(
401                                       "org.freedesktop.systemd1",
402                                       "/org/freedesktop/systemd1",
403                                       "org.freedesktop.systemd1.Manager",
404                                       "LoadUnit"))) {
405                         log_error("Could not allocate message.");
406                         r = -ENOMEM;
407                         goto finish;
408                 }
409
410                 if (!dbus_message_append_args(m,
411                                               DBUS_TYPE_STRING, &args[i],
412                                               DBUS_TYPE_INVALID)) {
413                         log_error("Could not append arguments to message.");
414                         r = -ENOMEM;
415                         goto finish;
416                 }
417
418                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
419                         log_error("Failed to issue method call: %s", error.message);
420                         r = -EIO;
421                         goto finish;
422                 }
423
424                 dbus_message_unref(m);
425                 dbus_message_unref(reply);
426
427                 m = reply = NULL;
428         }
429
430         r = 0;
431
432 finish:
433         if (m)
434                 dbus_message_unref(m);
435
436         if (reply)
437                 dbus_message_unref(reply);
438
439         dbus_error_free(&error);
440
441         return r;
442 }
443
444 static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
445         DBusMessage *m = NULL, *reply = NULL;
446         DBusError error;
447         int r;
448         unsigned i;
449
450         dbus_error_init(&error);
451
452         assert(bus);
453         assert(args);
454
455         for (i = 1; i < n; i++) {
456                 unsigned id;
457                 const char *path;
458
459                 if (!(m = dbus_message_new_method_call(
460                                       "org.freedesktop.systemd1",
461                                       "/org/freedesktop/systemd1",
462                                       "org.freedesktop.systemd1.Manager",
463                                       "GetJob"))) {
464                         log_error("Could not allocate message.");
465                         r = -ENOMEM;
466                         goto finish;
467                 }
468
469                 if ((r = safe_atou(args[i], &id)) < 0) {
470                         log_error("Failed to parse job id: %s", strerror(-r));
471                         goto finish;
472                 }
473
474                 assert_cc(sizeof(uint32_t) == sizeof(id));
475                 if (!dbus_message_append_args(m,
476                                               DBUS_TYPE_UINT32, &id,
477                                               DBUS_TYPE_INVALID)) {
478                         log_error("Could not append arguments to message.");
479                         r = -ENOMEM;
480                         goto finish;
481                 }
482
483                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
484                         log_error("Failed to issue method call: %s", error.message);
485                         r = -EIO;
486                         goto finish;
487                 }
488
489                 if (!dbus_message_get_args(reply, &error,
490                                            DBUS_TYPE_OBJECT_PATH, &path,
491                                            DBUS_TYPE_INVALID)) {
492                         log_error("Failed to parse reply: %s", error.message);
493                         r = -EIO;
494                         goto finish;
495                 }
496
497                 dbus_message_unref(m);
498                 if (!(m = dbus_message_new_method_call(
499                                       "org.freedesktop.systemd1",
500                                       path,
501                                       "org.freedesktop.systemd1.Job",
502                                       "Cancel"))) {
503                         log_error("Could not allocate message.");
504                         r = -ENOMEM;
505                         goto finish;
506                 }
507
508                 dbus_message_unref(reply);
509                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
510                         log_error("Failed to issue method call: %s", error.message);
511                         r = -EIO;
512                         goto finish;
513                 }
514
515                 dbus_message_unref(m);
516                 dbus_message_unref(reply);
517                 m = reply = NULL;
518         }
519
520         r = 0;
521
522 finish:
523         if (m)
524                 dbus_message_unref(m);
525
526         if (reply)
527                 dbus_message_unref(reply);
528
529         dbus_error_free(&error);
530
531         return r;
532 }
533
534 typedef struct WaitData {
535         Set *set;
536         bool failed;
537 } WaitData;
538
539 static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
540         DBusError error;
541         WaitData *d = data;
542
543         assert(connection);
544         assert(message);
545         assert(d);
546
547         dbus_error_init(&error);
548
549         /* log_debug("Got D-Bus request: %s.%s() on %s", */
550         /*           dbus_message_get_interface(message), */
551         /*           dbus_message_get_member(message), */
552         /*           dbus_message_get_path(message)); */
553
554         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
555                 log_error("Warning! D-Bus connection terminated.");
556                 dbus_connection_close(connection);
557
558         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
559                 uint32_t id;
560                 const char *path;
561                 dbus_bool_t success = true;
562
563                 if (!dbus_message_get_args(message, &error,
564                                            DBUS_TYPE_UINT32, &id,
565                                            DBUS_TYPE_OBJECT_PATH, &path,
566                                            DBUS_TYPE_BOOLEAN, &success,
567                                            DBUS_TYPE_INVALID))
568                         log_error("Failed to parse message: %s", error.message);
569                 else {
570                         char *p;
571
572                         if ((p = set_remove(d->set, (char*) path)))
573                                 free(p);
574
575                         if (!success)
576                                 d->failed = true;
577                 }
578         }
579
580         dbus_error_free(&error);
581         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
582 }
583
584 static int enable_wait_for_jobs(DBusConnection *bus) {
585         DBusError error;
586         DBusMessage *m = NULL, *reply = NULL;
587         int r;
588
589         assert(bus);
590
591         dbus_error_init(&error);
592
593         dbus_bus_add_match(bus,
594                            "type='signal',"
595                            "sender='org.freedesktop.systemd1',"
596                            "interface='org.freedesktop.systemd1.Manager',"
597                            "member='JobRemoved',"
598                            "path='/org/freedesktop/systemd1'",
599                            &error);
600
601         if (dbus_error_is_set(&error)) {
602                 log_error("Failed to add match: %s", error.message);
603                 r = -EIO;
604                 goto finish;
605         }
606
607         if (!(m = dbus_message_new_method_call(
608                               "org.freedesktop.systemd1",
609                               "/org/freedesktop/systemd1",
610                               "org.freedesktop.systemd1.Manager",
611                               "Subscribe"))) {
612                 log_error("Could not allocate message.");
613                 r = -ENOMEM;
614                 goto finish;
615         }
616
617         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
618                 log_error("Failed to issue method call: %s", error.message);
619                 r = -EIO;
620                 goto finish;
621         }
622
623         r = 0;
624
625 finish:
626         /* This is slightly dirty, since we don't undo the match registrations. */
627
628         if (m)
629                 dbus_message_unref(m);
630
631         if (reply)
632                 dbus_message_unref(reply);
633
634         dbus_error_free(&error);
635
636         return r;
637 }
638
639 static int wait_for_jobs(DBusConnection *bus, Set *s) {
640         int r;
641         WaitData d;
642
643         assert(bus);
644         assert(s);
645
646         zero(d);
647         d.set = s;
648         d.failed = false;
649
650         if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
651                 log_error("Failed to add filter.");
652                 r = -ENOMEM;
653                 goto finish;
654         }
655
656         while (!set_isempty(s) &&
657                dbus_connection_read_write_dispatch(bus, -1))
658                 ;
659
660         if (!arg_quiet && d.failed)
661                 log_error("Job failed, see logs for details.");
662
663         r = d.failed ? -EIO : 0;
664
665 finish:
666         /* This is slightly dirty, since we don't undo the filter registration. */
667
668         return r;
669 }
670
671 static int start_unit_one(
672                 DBusConnection *bus,
673                 const char *method,
674                 const char *name,
675                 const char *mode,
676                 Set *s) {
677
678         DBusMessage *m = NULL, *reply = NULL;
679         DBusError error;
680         int r;
681
682         assert(bus);
683         assert(method);
684         assert(name);
685         assert(mode);
686         assert(arg_no_block || s);
687
688         dbus_error_init(&error);
689
690         if (!(m = dbus_message_new_method_call(
691                               "org.freedesktop.systemd1",
692                               "/org/freedesktop/systemd1",
693                               "org.freedesktop.systemd1.Manager",
694                               method))) {
695                 log_error("Could not allocate message.");
696                 r = -ENOMEM;
697                 goto finish;
698         }
699
700         if (!dbus_message_append_args(m,
701                                       DBUS_TYPE_STRING, &name,
702                                       DBUS_TYPE_STRING, &mode,
703                                       DBUS_TYPE_INVALID)) {
704                 log_error("Could not append arguments to message.");
705                 r = -ENOMEM;
706                 goto finish;
707         }
708
709         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
710
711                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
712                         /* There's always a fallback possible for
713                          * legacy actions. */
714                         r = 0;
715                         goto finish;
716                 }
717
718                 log_error("Failed to issue method call: %s", error.message);
719                 r = -EIO;
720                 goto finish;
721         }
722
723         if (!arg_no_block) {
724                 const char *path;
725                 char *p;
726
727                 if (!dbus_message_get_args(reply, &error,
728                                            DBUS_TYPE_OBJECT_PATH, &path,
729                                            DBUS_TYPE_INVALID)) {
730                         log_error("Failed to parse reply: %s", error.message);
731                         r = -EIO;
732                         goto finish;
733                 }
734
735                 if (!(p = strdup(path))) {
736                         log_error("Failed to duplicate path.");
737                         r = -ENOMEM;
738                         goto finish;
739                 }
740
741                 if ((r = set_put(s, p)) < 0) {
742                         free(p);
743                         log_error("Failed to add path to set.");
744                         goto finish;
745                 }
746         }
747
748         r = 1;
749
750 finish:
751         if (m)
752                 dbus_message_unref(m);
753
754         if (reply)
755                 dbus_message_unref(reply);
756
757         dbus_error_free(&error);
758
759         return r;
760 }
761
762 static enum action verb_to_action(const char *verb) {
763         if (streq(verb, "halt"))
764                 return ACTION_HALT;
765         else if (streq(verb, "poweroff"))
766                 return ACTION_POWEROFF;
767         else if (streq(verb, "reboot"))
768                 return ACTION_REBOOT;
769         else if (streq(verb, "rescue"))
770                 return ACTION_RESCUE;
771         else if (streq(verb, "emergency"))
772                 return ACTION_EMERGENCY;
773         else if (streq(verb, "default"))
774                 return ACTION_DEFAULT;
775         else
776                 return ACTION_INVALID;
777 }
778
779 static int start_unit(DBusConnection *bus, char **args, unsigned n) {
780
781         static const char * const table[_ACTION_MAX] = {
782                 [ACTION_HALT] = SPECIAL_HALT_TARGET,
783                 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
784                 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
785                 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
786                 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
787                 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
788                 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
789                 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
790                 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_SERVICE,
791                 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET
792         };
793
794         int r;
795         unsigned i;
796         const char *method, *mode, *one_name;
797         Set *s = NULL;
798
799         assert(bus);
800
801         if (arg_action == ACTION_SYSTEMCTL) {
802                 method =
803                         streq(args[0], "stop")    ? "StopUnit" :
804                         streq(args[0], "reload")  ? "ReloadUnit" :
805                         streq(args[0], "restart") ? "RestartUnit" :
806                                                     "StartUnit";
807
808                 mode =
809                         (streq(args[0], "isolate") ||
810                          streq(args[0], "rescue")  ||
811                          streq(args[0], "emergency")) ? "isolate" :
812                                           arg_replace ? "replace" :
813                                                         "fail";
814
815                 one_name = table[verb_to_action(args[0])];
816
817         } else {
818                 assert(arg_action < ELEMENTSOF(table));
819                 assert(table[arg_action]);
820
821                 method = "StartUnit";
822
823                 mode = (arg_action == ACTION_EMERGENCY ||
824                         arg_action == ACTION_RESCUE) ? "isolate" : "replace";
825
826                 one_name = table[arg_action];
827         }
828
829         if (!arg_no_block) {
830                 if ((r = enable_wait_for_jobs(bus)) < 0) {
831                         log_error("Could not watch jobs: %s", strerror(-r));
832                         goto finish;
833                 }
834
835                 if (!(s = set_new(string_hash_func, string_compare_func))) {
836                         log_error("Failed to allocate set.");
837                         r = -ENOMEM;
838                         goto finish;
839                 }
840         }
841
842         r = 0;
843
844         if (one_name) {
845                 if ((r = start_unit_one(bus, method, one_name, mode, s)) <= 0)
846                         goto finish;
847         } else {
848                 for (i = 1; i < n; i++)
849                         if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
850                                 goto finish;
851         }
852
853         if (!arg_no_block)
854                 r = wait_for_jobs(bus, s);
855
856 finish:
857         if (s)
858                 set_free_free(s);
859
860         return r;
861 }
862
863 static int start_special(DBusConnection *bus, char **args, unsigned n) {
864         assert(bus);
865         assert(args);
866
867         warn_wall(verb_to_action(args[0]));
868
869         return start_unit(bus, args, n);
870 }
871
872 static int check_unit(DBusConnection *bus, char **args, unsigned n) {
873         DBusMessage *m = NULL, *reply = NULL;
874         const char
875                 *interface = "org.freedesktop.systemd1.Unit",
876                 *property = "ActiveState";
877         int r = -EADDRNOTAVAIL;
878         DBusError error;
879         unsigned i;
880
881         assert(bus);
882         assert(args);
883
884         dbus_error_init(&error);
885
886         for (i = 1; i < n; i++) {
887                 const char *path = NULL;
888                 const char *state;
889                 DBusMessageIter iter, sub;
890
891                 if (!(m = dbus_message_new_method_call(
892                                       "org.freedesktop.systemd1",
893                                       "/org/freedesktop/systemd1",
894                                       "org.freedesktop.systemd1.Manager",
895                                       "GetUnit"))) {
896                         log_error("Could not allocate message.");
897                         r = -ENOMEM;
898                         goto finish;
899                 }
900
901                 if (!dbus_message_append_args(m,
902                                               DBUS_TYPE_STRING, &args[i],
903                                               DBUS_TYPE_INVALID)) {
904                         log_error("Could not append arguments to message.");
905                         r = -ENOMEM;
906                         goto finish;
907                 }
908
909                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
910
911                         /* Hmm, cannot figure out anything about this unit... */
912                         if (!arg_quiet)
913                                 puts("unknown");
914
915                         continue;
916                 }
917
918                 if (!dbus_message_get_args(reply, &error,
919                                            DBUS_TYPE_OBJECT_PATH, &path,
920                                            DBUS_TYPE_INVALID)) {
921                         log_error("Failed to parse reply: %s", error.message);
922                         r = -EIO;
923                         goto finish;
924                 }
925
926                 dbus_message_unref(m);
927                 if (!(m = dbus_message_new_method_call(
928                                       "org.freedesktop.systemd1",
929                                       path,
930                                       "org.freedesktop.DBus.Properties",
931                                       "Get"))) {
932                         log_error("Could not allocate message.");
933                         r = -ENOMEM;
934                         goto finish;
935                 }
936
937                 if (!dbus_message_append_args(m,
938                                               DBUS_TYPE_STRING, &interface,
939                                               DBUS_TYPE_STRING, &property,
940                                               DBUS_TYPE_INVALID)) {
941                         log_error("Could not append arguments to message.");
942                         r = -ENOMEM;
943                         goto finish;
944                 }
945
946                 dbus_message_unref(reply);
947                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
948                         log_error("Failed to issue method call: %s", error.message);
949                         r = -EIO;
950                         goto finish;
951                 }
952
953                 if (!dbus_message_iter_init(reply, &iter) ||
954                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
955                         log_error("Failed to parse reply.");
956                         r = -EIO;
957                         goto finish;
958                 }
959
960                 dbus_message_iter_recurse(&iter, &sub);
961
962                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
963                         log_error("Failed to parse reply.");
964                         r = -EIO;
965                         goto finish;
966                 }
967
968                 dbus_message_iter_get_basic(&sub, &state);
969
970                 if (!arg_quiet)
971                         puts(state);
972
973                 if (streq(state, "active") || startswith(state, "reloading"))
974                         r = 0;
975
976                 dbus_message_unref(m);
977                 dbus_message_unref(reply);
978                 m = reply = NULL;
979         }
980
981 finish:
982         if (m)
983                 dbus_message_unref(m);
984
985         if (reply)
986                 dbus_message_unref(reply);
987
988         dbus_error_free(&error);
989
990         return r;
991 }
992
993 static int print_property(const char *name, DBusMessageIter *iter) {
994         assert(name);
995         assert(iter);
996
997         if (arg_property && !streq(name, arg_property))
998                 return 0;
999
1000         switch (dbus_message_iter_get_arg_type(iter)) {
1001
1002         case DBUS_TYPE_STRING: {
1003                 const char *s;
1004                 dbus_message_iter_get_basic(iter, &s);
1005
1006                 if (arg_all || s[0])
1007                         printf("%s=%s\n", name, s);
1008
1009                 return 0;
1010         }
1011
1012         case DBUS_TYPE_BOOLEAN: {
1013                 dbus_bool_t b;
1014                 dbus_message_iter_get_basic(iter, &b);
1015                 printf("%s=%s\n", name, yes_no(b));
1016
1017                 return 0;
1018         }
1019
1020         case DBUS_TYPE_UINT64: {
1021                 uint64_t u;
1022                 dbus_message_iter_get_basic(iter, &u);
1023
1024                 /* Yes, heuristics! But we can change this check
1025                  * should it turn out to not be sufficient */
1026
1027                 if (strstr(name, "Timestamp") || strstr(name, "Elapse")) {
1028                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
1029
1030                         if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
1031                                 printf("%s=%s\n", name, strempty(t));
1032                 } else
1033                         printf("%s=%llu\n", name, (unsigned long long) u);
1034
1035                 return 0;
1036         }
1037
1038         case DBUS_TYPE_UINT32: {
1039                 uint32_t u;
1040                 dbus_message_iter_get_basic(iter, &u);
1041
1042                 if (strstr(name, "UMask"))
1043                         printf("%s=%04o\n", name, u);
1044                 else
1045                         printf("%s=%u\n", name, (unsigned) u);
1046
1047                 return 0;
1048         }
1049
1050         case DBUS_TYPE_INT32: {
1051                 int32_t i;
1052                 dbus_message_iter_get_basic(iter, &i);
1053
1054                 printf("%s=%i\n", name, (int) i);
1055                 return 0;
1056         }
1057
1058         case DBUS_TYPE_STRUCT: {
1059                 DBusMessageIter sub;
1060                 dbus_message_iter_recurse(iter, &sub);
1061
1062                 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
1063                         uint32_t u;
1064
1065                         dbus_message_iter_get_basic(&sub, &u);
1066
1067                         if (u)
1068                                 printf("%s=%u\n", name, (unsigned) u);
1069                         else if (arg_all)
1070                                 printf("%s=\n", name);
1071
1072                         return 0;
1073                 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
1074                         const char *s;
1075
1076                         dbus_message_iter_get_basic(&sub, &s);
1077
1078                         if (arg_all || s[0])
1079                                 printf("%s=%s\n", name, s);
1080
1081                         return 0;
1082                 }
1083
1084                 break;
1085         }
1086
1087         case DBUS_TYPE_ARRAY:
1088
1089                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
1090                         DBusMessageIter sub;
1091                         bool space = false;
1092
1093                         dbus_message_iter_recurse(iter, &sub);
1094
1095                         if (arg_all ||
1096                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1097                                 printf("%s=", name);
1098
1099                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1100                                         const char *s;
1101
1102                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1103                                         dbus_message_iter_get_basic(&sub, &s);
1104                                         printf("%s%s", space ? " " : "", s);
1105
1106                                         space = true;
1107                                         dbus_message_iter_next(&sub);
1108                                 }
1109
1110                                 puts("");
1111                         }
1112
1113                         return 0;
1114
1115                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1116                         DBusMessageIter sub, sub2;
1117
1118                         dbus_message_iter_recurse(iter, &sub);
1119
1120                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1121                                 const char *type, *path;
1122
1123                                 dbus_message_iter_recurse(&sub, &sub2);
1124
1125                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1126                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1127                                         printf("%s=%s\n", type, path);
1128
1129                                 dbus_message_iter_next(&sub);
1130                         }
1131
1132                         return 0;
1133                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1134                         DBusMessageIter sub, sub2;
1135
1136                         dbus_message_iter_recurse(iter, &sub);
1137
1138                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1139                                 const char *base;
1140                                 uint64_t value, next_elapse;
1141
1142                                 dbus_message_iter_recurse(&sub, &sub2);
1143
1144                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
1145                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
1146                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0)
1147                                         printf("%s=%llu\n", base, (unsigned long long) value);
1148
1149                                 dbus_message_iter_next(&sub);
1150                         }
1151
1152                         return 0;
1153                 }
1154
1155                 break;
1156         }
1157
1158         if (arg_all)
1159                 printf("%s=[unprintable]\n", name);
1160
1161         return 0;
1162 }
1163
1164 static int show_one(DBusConnection *bus, const char *path) {
1165         DBusMessage *m = NULL, *reply = NULL;
1166         const char *interface = "";
1167         int r;
1168         DBusError error;
1169         DBusMessageIter iter, sub, sub2, sub3;
1170
1171         assert(bus);
1172         assert(path);
1173
1174         dbus_error_init(&error);
1175
1176         if (!(m = dbus_message_new_method_call(
1177                               "org.freedesktop.systemd1",
1178                               path,
1179                               "org.freedesktop.DBus.Properties",
1180                               "GetAll"))) {
1181                 log_error("Could not allocate message.");
1182                 r = -ENOMEM;
1183                 goto finish;
1184         }
1185
1186         if (!dbus_message_append_args(m,
1187                                       DBUS_TYPE_STRING, &interface,
1188                                       DBUS_TYPE_INVALID)) {
1189                 log_error("Could not append arguments to message.");
1190                 r = -ENOMEM;
1191                 goto finish;
1192         }
1193
1194         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1195                 log_error("Failed to issue method call: %s", error.message);
1196                 r = -EIO;
1197                 goto finish;
1198         }
1199
1200         if (!dbus_message_iter_init(reply, &iter) ||
1201             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1202             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
1203                 log_error("Failed to parse reply.");
1204                 r = -EIO;
1205                 goto finish;
1206         }
1207
1208         dbus_message_iter_recurse(&iter, &sub);
1209
1210         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1211                 const char *name;
1212
1213                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
1214                         log_error("Failed to parse reply.");
1215                         r = -EIO;
1216                         goto finish;
1217                 }
1218
1219                 dbus_message_iter_recurse(&sub, &sub2);
1220
1221                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
1222                         log_error("Failed to parse reply.");
1223                         r = -EIO;
1224                         goto finish;
1225                 }
1226
1227                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
1228                         log_error("Failed to parse reply.");
1229                         r = -EIO;
1230                         goto finish;
1231                 }
1232
1233                 dbus_message_iter_recurse(&sub2, &sub3);
1234
1235                 if (print_property(name, &sub3) < 0) {
1236                         log_error("Failed to parse reply.");
1237                         r = -EIO;
1238                         goto finish;
1239                 }
1240
1241                 dbus_message_iter_next(&sub);
1242         }
1243
1244         r = 0;
1245
1246 finish:
1247         if (m)
1248                 dbus_message_unref(m);
1249
1250         if (reply)
1251                 dbus_message_unref(reply);
1252
1253         dbus_error_free(&error);
1254
1255         return r;
1256 }
1257
1258 static int show(DBusConnection *bus, char **args, unsigned n) {
1259         DBusMessage *m = NULL, *reply = NULL;
1260         int r;
1261         DBusError error;
1262         unsigned i;
1263
1264         assert(bus);
1265         assert(args);
1266
1267         dbus_error_init(&error);
1268
1269         if (n <= 1) {
1270                 /* If not argument is specified inspect the manager
1271                  * itself */
1272
1273                 r = show_one(bus, "/org/freedesktop/systemd1");
1274                 goto finish;
1275         }
1276
1277         for (i = 1; i < n; i++) {
1278                 const char *path = NULL;
1279                 uint32_t id;
1280
1281                 if (safe_atou32(args[i], &id) < 0) {
1282
1283                         if (!(m = dbus_message_new_method_call(
1284                                               "org.freedesktop.systemd1",
1285                                               "/org/freedesktop/systemd1",
1286                                               "org.freedesktop.systemd1.Manager",
1287                                               "LoadUnit"))) {
1288                                 log_error("Could not allocate message.");
1289                                 r = -ENOMEM;
1290                                 goto finish;
1291                         }
1292
1293                         if (!dbus_message_append_args(m,
1294                                                       DBUS_TYPE_STRING, &args[i],
1295                                                       DBUS_TYPE_INVALID)) {
1296                                 log_error("Could not append arguments to message.");
1297                                 r = -ENOMEM;
1298                                 goto finish;
1299                         }
1300
1301                 } else {
1302
1303                         if (!(m = dbus_message_new_method_call(
1304                                               "org.freedesktop.systemd1",
1305                                               "/org/freedesktop/systemd1",
1306                                               "org.freedesktop.systemd1.Manager",
1307                                               "GetJob"))) {
1308                                 log_error("Could not allocate message.");
1309                                 r = -ENOMEM;
1310                                 goto finish;
1311                         }
1312
1313                         if (!dbus_message_append_args(m,
1314                                                       DBUS_TYPE_UINT32, &id,
1315                                                       DBUS_TYPE_INVALID)) {
1316                                 log_error("Could not append arguments to message.");
1317                                 r = -ENOMEM;
1318                                 goto finish;
1319                         }
1320                 }
1321
1322                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1323                         log_error("Failed to issue method call: %s", error.message);
1324                         r = -EIO;
1325                         goto finish;
1326                 }
1327
1328                 if (!dbus_message_get_args(reply, &error,
1329                                            DBUS_TYPE_OBJECT_PATH, &path,
1330                                            DBUS_TYPE_INVALID)) {
1331                         log_error("Failed to parse reply: %s", error.message);
1332                         r = -EIO;
1333                         goto finish;
1334                 }
1335
1336                 if ((r = show_one(bus, path)) < 0)
1337                         goto finish;
1338
1339                 dbus_message_unref(m);
1340                 dbus_message_unref(reply);
1341                 m = reply = NULL;
1342         }
1343
1344         r = 0;
1345
1346 finish:
1347         if (m)
1348                 dbus_message_unref(m);
1349
1350         if (reply)
1351                 dbus_message_unref(reply);
1352
1353         dbus_error_free(&error);
1354
1355         return r;
1356 }
1357
1358 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1359         DBusError error;
1360         DBusMessage *m = NULL, *reply = NULL;
1361
1362         assert(connection);
1363         assert(message);
1364
1365         dbus_error_init(&error);
1366
1367         /* log_debug("Got D-Bus request: %s.%s() on %s", */
1368         /*           dbus_message_get_interface(message), */
1369         /*           dbus_message_get_member(message), */
1370         /*           dbus_message_get_path(message)); */
1371
1372         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1373                 log_error("Warning! D-Bus connection terminated.");
1374                 dbus_connection_close(connection);
1375
1376         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
1377                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
1378                 const char *id, *path;
1379
1380                 if (!dbus_message_get_args(message, &error,
1381                                            DBUS_TYPE_STRING, &id,
1382                                            DBUS_TYPE_OBJECT_PATH, &path,
1383                                            DBUS_TYPE_INVALID))
1384                         log_error("Failed to parse message: %s", error.message);
1385                 else if (streq(dbus_message_get_member(message), "UnitNew"))
1386                         printf("Unit %s added.\n", id);
1387                 else
1388                         printf("Unit %s removed.\n", id);
1389
1390         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
1391                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1392                 uint32_t id;
1393                 const char *path;
1394
1395                 if (!dbus_message_get_args(message, &error,
1396                                            DBUS_TYPE_UINT32, &id,
1397                                            DBUS_TYPE_OBJECT_PATH, &path,
1398                                            DBUS_TYPE_INVALID))
1399                         log_error("Failed to parse message: %s", error.message);
1400                 else if (streq(dbus_message_get_member(message), "JobNew"))
1401                         printf("Job %u added.\n", id);
1402                 else
1403                         printf("Job %u removed.\n", id);
1404
1405
1406         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Unit", "Changed") ||
1407                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Job", "Changed")) {
1408
1409                 const char *path, *interface, *property = "Id";
1410                 DBusMessageIter iter, sub;
1411
1412                 path = dbus_message_get_path(message);
1413                 interface = dbus_message_get_interface(message);
1414
1415                 if (!(m = dbus_message_new_method_call(
1416                               "org.freedesktop.systemd1",
1417                               path,
1418                               "org.freedesktop.DBus.Properties",
1419                               "Get"))) {
1420                         log_error("Could not allocate message.");
1421                         goto oom;
1422                 }
1423
1424                 if (!dbus_message_append_args(m,
1425                                               DBUS_TYPE_STRING, &interface,
1426                                               DBUS_TYPE_STRING, &property,
1427                                               DBUS_TYPE_INVALID)) {
1428                         log_error("Could not append arguments to message.");
1429                         goto finish;
1430                 }
1431
1432                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
1433                         log_error("Failed to issue method call: %s", error.message);
1434                         goto finish;
1435                 }
1436
1437                 if (!dbus_message_iter_init(reply, &iter) ||
1438                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1439                         log_error("Failed to parse reply.");
1440                         goto finish;
1441                 }
1442
1443                 dbus_message_iter_recurse(&iter, &sub);
1444
1445                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
1446                         const char *id;
1447
1448                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1449                                 log_error("Failed to parse reply.");
1450                                 goto finish;
1451                         }
1452
1453                         dbus_message_iter_get_basic(&sub, &id);
1454                         printf("Unit %s changed.\n", id);
1455                 } else {
1456                         uint32_t id;
1457
1458                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
1459                                 log_error("Failed to parse reply.");
1460                                 goto finish;
1461                         }
1462
1463                         dbus_message_iter_get_basic(&sub, &id);
1464                         printf("Job %u changed.\n", id);
1465                 }
1466         }
1467
1468 finish:
1469         if (m)
1470                 dbus_message_unref(m);
1471
1472         if (reply)
1473                 dbus_message_unref(reply);
1474
1475         dbus_error_free(&error);
1476         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1477
1478 oom:
1479         if (m)
1480                 dbus_message_unref(m);
1481
1482         if (reply)
1483                 dbus_message_unref(reply);
1484
1485         dbus_error_free(&error);
1486         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1487 }
1488
1489 static int monitor(DBusConnection *bus, char **args, unsigned n) {
1490         DBusMessage *m = NULL, *reply = NULL;
1491         DBusError error;
1492         int r;
1493
1494         dbus_error_init(&error);
1495
1496         dbus_bus_add_match(bus,
1497                            "type='signal',"
1498                            "sender='org.freedesktop.systemd1',"
1499                            "interface='org.freedesktop.systemd1.Manager',"
1500                            "path='/org/freedesktop/systemd1'",
1501                            &error);
1502
1503         if (dbus_error_is_set(&error)) {
1504                 log_error("Failed to add match: %s", error.message);
1505                 r = -EIO;
1506                 goto finish;
1507         }
1508
1509         dbus_bus_add_match(bus,
1510                            "type='signal',"
1511                            "sender='org.freedesktop.systemd1',"
1512                            "interface='org.freedesktop.systemd1.Unit',"
1513                            "member='Changed'",
1514                            &error);
1515
1516         if (dbus_error_is_set(&error)) {
1517                 log_error("Failed to add match: %s", error.message);
1518                 r = -EIO;
1519                 goto finish;
1520         }
1521
1522         dbus_bus_add_match(bus,
1523                            "type='signal',"
1524                            "sender='org.freedesktop.systemd1',"
1525                            "interface='org.freedesktop.systemd1.Job',"
1526                            "member='Changed'",
1527                            &error);
1528
1529         if (dbus_error_is_set(&error)) {
1530                 log_error("Failed to add match: %s", error.message);
1531                 r = -EIO;
1532                 goto finish;
1533         }
1534
1535         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
1536                 log_error("Failed to add filter.");
1537                 r = -ENOMEM;
1538                 goto finish;
1539         }
1540
1541         if (!(m = dbus_message_new_method_call(
1542                               "org.freedesktop.systemd1",
1543                               "/org/freedesktop/systemd1",
1544                               "org.freedesktop.systemd1.Manager",
1545                               "Subscribe"))) {
1546                 log_error("Could not allocate message.");
1547                 r = -ENOMEM;
1548                 goto finish;
1549         }
1550
1551         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1552                 log_error("Failed to issue method call: %s", error.message);
1553                 r = -EIO;
1554                 goto finish;
1555         }
1556
1557         while (dbus_connection_read_write_dispatch(bus, -1))
1558                 ;
1559
1560         r = 0;
1561
1562 finish:
1563
1564         /* This is slightly dirty, since we don't undo the filter or the matches. */
1565
1566         if (m)
1567                 dbus_message_unref(m);
1568
1569         if (reply)
1570                 dbus_message_unref(reply);
1571
1572         dbus_error_free(&error);
1573
1574         return r;
1575 }
1576
1577 static int dump(DBusConnection *bus, char **args, unsigned n) {
1578         DBusMessage *m = NULL, *reply = NULL;
1579         DBusError error;
1580         int r;
1581         const char *text;
1582
1583         dbus_error_init(&error);
1584
1585         if (!(m = dbus_message_new_method_call(
1586                               "org.freedesktop.systemd1",
1587                               "/org/freedesktop/systemd1",
1588                               "org.freedesktop.systemd1.Manager",
1589                               "Dump"))) {
1590                 log_error("Could not allocate message.");
1591                 return -ENOMEM;
1592         }
1593
1594         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1595                 log_error("Failed to issue method call: %s", error.message);
1596                 r = -EIO;
1597                 goto finish;
1598         }
1599
1600         if (!dbus_message_get_args(reply, &error,
1601                                    DBUS_TYPE_STRING, &text,
1602                                    DBUS_TYPE_INVALID)) {
1603                 log_error("Failed to parse reply: %s", error.message);
1604                 r = -EIO;
1605                 goto finish;
1606         }
1607
1608         fputs(text, stdout);
1609
1610         r = 0;
1611
1612 finish:
1613         if (m)
1614                 dbus_message_unref(m);
1615
1616         if (reply)
1617                 dbus_message_unref(reply);
1618
1619         dbus_error_free(&error);
1620
1621         return r;
1622 }
1623
1624 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
1625         DBusMessage *m = NULL, *reply = NULL;
1626         DBusError error;
1627         int r;
1628         const char *name = "", *path, *id;
1629         dbus_bool_t cleanup = FALSE;
1630         DBusMessageIter iter, sub;
1631         const char
1632                 *interface = "org.freedesktop.systemd1.Unit",
1633                 *property = "Id";
1634
1635         dbus_error_init(&error);
1636
1637         if (!(m = dbus_message_new_method_call(
1638                               "org.freedesktop.systemd1",
1639                               "/org/freedesktop/systemd1",
1640                               "org.freedesktop.systemd1.Manager",
1641                               "CreateSnapshot"))) {
1642                 log_error("Could not allocate message.");
1643                 return -ENOMEM;
1644         }
1645
1646         if (n > 1)
1647                 name = args[1];
1648
1649         if (!dbus_message_append_args(m,
1650                                       DBUS_TYPE_STRING, &name,
1651                                       DBUS_TYPE_BOOLEAN, &cleanup,
1652                                       DBUS_TYPE_INVALID)) {
1653                 log_error("Could not append arguments to message.");
1654                 r = -ENOMEM;
1655                 goto finish;
1656         }
1657
1658         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1659                 log_error("Failed to issue method call: %s", error.message);
1660                 r = -EIO;
1661                 goto finish;
1662         }
1663
1664         if (!dbus_message_get_args(reply, &error,
1665                                    DBUS_TYPE_OBJECT_PATH, &path,
1666                                    DBUS_TYPE_INVALID)) {
1667                 log_error("Failed to parse reply: %s", error.message);
1668                 r = -EIO;
1669                 goto finish;
1670         }
1671
1672         dbus_message_unref(m);
1673         if (!(m = dbus_message_new_method_call(
1674                               "org.freedesktop.systemd1",
1675                               path,
1676                               "org.freedesktop.DBus.Properties",
1677                               "Get"))) {
1678                 log_error("Could not allocate message.");
1679                 return -ENOMEM;
1680         }
1681
1682         if (!dbus_message_append_args(m,
1683                                       DBUS_TYPE_STRING, &interface,
1684                                       DBUS_TYPE_STRING, &property,
1685                                       DBUS_TYPE_INVALID)) {
1686                 log_error("Could not append arguments to message.");
1687                 r = -ENOMEM;
1688                 goto finish;
1689         }
1690
1691         dbus_message_unref(reply);
1692         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1693                 log_error("Failed to issue method call: %s", error.message);
1694                 r = -EIO;
1695                 goto finish;
1696         }
1697
1698         if (!dbus_message_iter_init(reply, &iter) ||
1699             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1700                 log_error("Failed to parse reply.");
1701                 r = -EIO;
1702                 goto finish;
1703         }
1704
1705         dbus_message_iter_recurse(&iter, &sub);
1706
1707         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1708                 log_error("Failed to parse reply.");
1709                 r = -EIO;
1710                 goto finish;
1711         }
1712
1713         dbus_message_iter_get_basic(&sub, &id);
1714
1715         if (!arg_quiet)
1716                 puts(id);
1717         r = 0;
1718
1719 finish:
1720         if (m)
1721                 dbus_message_unref(m);
1722
1723         if (reply)
1724                 dbus_message_unref(reply);
1725
1726         dbus_error_free(&error);
1727
1728         return r;
1729 }
1730
1731 static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
1732         DBusMessage *m = NULL, *reply = NULL;
1733         int r;
1734         DBusError error;
1735         unsigned i;
1736
1737         assert(bus);
1738         assert(args);
1739
1740         dbus_error_init(&error);
1741
1742         for (i = 1; i < n; i++) {
1743                 const char *path = NULL;
1744
1745                 if (!(m = dbus_message_new_method_call(
1746                                       "org.freedesktop.systemd1",
1747                                       "/org/freedesktop/systemd1",
1748                                       "org.freedesktop.systemd1.Manager",
1749                                       "GetUnit"))) {
1750                         log_error("Could not allocate message.");
1751                         r = -ENOMEM;
1752                         goto finish;
1753                 }
1754
1755                 if (!dbus_message_append_args(m,
1756                                               DBUS_TYPE_STRING, &args[i],
1757                                               DBUS_TYPE_INVALID)) {
1758                         log_error("Could not append arguments to message.");
1759                         r = -ENOMEM;
1760                         goto finish;
1761                 }
1762
1763                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1764                         log_error("Failed to issue method call: %s", error.message);
1765                         r = -EIO;
1766                         goto finish;
1767                 }
1768
1769                 if (!dbus_message_get_args(reply, &error,
1770                                            DBUS_TYPE_OBJECT_PATH, &path,
1771                                            DBUS_TYPE_INVALID)) {
1772                         log_error("Failed to parse reply: %s", error.message);
1773                         r = -EIO;
1774                         goto finish;
1775                 }
1776
1777                 dbus_message_unref(m);
1778                 if (!(m = dbus_message_new_method_call(
1779                                       "org.freedesktop.systemd1",
1780                                       path,
1781                                       "org.freedesktop.systemd1.Snapshot",
1782                                       "Remove"))) {
1783                         log_error("Could not allocate message.");
1784                         r = -ENOMEM;
1785                         goto finish;
1786                 }
1787
1788                 dbus_message_unref(reply);
1789                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1790                         log_error("Failed to issue method call: %s", error.message);
1791                         r = -EIO;
1792                         goto finish;
1793                 }
1794
1795                 dbus_message_unref(m);
1796                 dbus_message_unref(reply);
1797                 m = reply = NULL;
1798         }
1799
1800         r = 0;
1801
1802 finish:
1803         if (m)
1804                 dbus_message_unref(m);
1805
1806         if (reply)
1807                 dbus_message_unref(reply);
1808
1809         dbus_error_free(&error);
1810
1811         return r;
1812 }
1813
1814 static int clear_jobs(DBusConnection *bus, char **args, unsigned n) {
1815         DBusMessage *m = NULL, *reply = NULL;
1816         DBusError error;
1817         int r;
1818         const char *method;
1819
1820         dbus_error_init(&error);
1821
1822         if (arg_action == ACTION_RELOAD)
1823                 method = "Reload";
1824         else if (arg_action == ACTION_REEXEC)
1825                 method = "Reexecute";
1826         else {
1827                 assert(arg_action == ACTION_SYSTEMCTL);
1828
1829                 method =
1830                         streq(args[0], "clear-jobs")    ? "ClearJobs" :
1831                         streq(args[0], "daemon-reload") ? "Reload" :
1832                         streq(args[0], "daemon-reexec") ? "Reexecute" :
1833                                                           "Exit";
1834         }
1835
1836         if (!(m = dbus_message_new_method_call(
1837                               "org.freedesktop.systemd1",
1838                               "/org/freedesktop/systemd1",
1839                               "org.freedesktop.systemd1.Manager",
1840                               method))) {
1841                 log_error("Could not allocate message.");
1842                 return -ENOMEM;
1843         }
1844
1845         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1846
1847                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
1848                         /* There's always a fallback possible for
1849                          * legacy actions. */
1850                         r = 0;
1851                         goto finish;
1852                 }
1853
1854                 log_error("Failed to issue method call: %s", error.message);
1855                 r = -EIO;
1856                 goto finish;
1857         }
1858
1859         r = 1;
1860
1861 finish:
1862         if (m)
1863                 dbus_message_unref(m);
1864
1865         if (reply)
1866                 dbus_message_unref(reply);
1867
1868         dbus_error_free(&error);
1869
1870         return r;
1871 }
1872
1873 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
1874         DBusMessage *m = NULL, *reply = NULL;
1875         DBusError error;
1876         DBusMessageIter iter, sub, sub2;
1877         int r;
1878         const char
1879                 *interface = "org.freedesktop.systemd1.Manager",
1880                 *property = "Environment";
1881
1882         dbus_error_init(&error);
1883
1884         if (!(m = dbus_message_new_method_call(
1885                               "org.freedesktop.systemd1",
1886                               "/org/freedesktop/systemd1",
1887                               "org.freedesktop.DBus.Properties",
1888                               "Get"))) {
1889                 log_error("Could not allocate message.");
1890                 return -ENOMEM;
1891         }
1892
1893         if (!dbus_message_append_args(m,
1894                                       DBUS_TYPE_STRING, &interface,
1895                                       DBUS_TYPE_STRING, &property,
1896                                       DBUS_TYPE_INVALID)) {
1897                 log_error("Could not append arguments to message.");
1898                 r = -ENOMEM;
1899                 goto finish;
1900         }
1901
1902         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1903                 log_error("Failed to issue method call: %s", error.message);
1904                 r = -EIO;
1905                 goto finish;
1906         }
1907
1908         if (!dbus_message_iter_init(reply, &iter) ||
1909             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1910                 log_error("Failed to parse reply.");
1911                 r = -EIO;
1912                 goto finish;
1913         }
1914
1915         dbus_message_iter_recurse(&iter, &sub);
1916
1917         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
1918             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
1919                 log_error("Failed to parse reply.");
1920                 r = -EIO;
1921                 goto finish;
1922         }
1923
1924         dbus_message_iter_recurse(&sub, &sub2);
1925
1926         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
1927                 const char *text;
1928
1929                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
1930                         log_error("Failed to parse reply.");
1931                         r = -EIO;
1932                         goto finish;
1933                 }
1934
1935                 dbus_message_iter_get_basic(&sub2, &text);
1936                 printf("%s\n", text);
1937
1938                 dbus_message_iter_next(&sub2);
1939         }
1940
1941         r = 0;
1942
1943 finish:
1944         if (m)
1945                 dbus_message_unref(m);
1946
1947         if (reply)
1948                 dbus_message_unref(reply);
1949
1950         dbus_error_free(&error);
1951
1952         return r;
1953 }
1954
1955 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
1956         DBusMessage *m = NULL, *reply = NULL;
1957         DBusError error;
1958         int r;
1959         const char *method;
1960         DBusMessageIter iter, sub;
1961         unsigned i;
1962
1963         dbus_error_init(&error);
1964
1965         method = streq(args[0], "set-environment")
1966                 ? "SetEnvironment"
1967                 : "UnsetEnvironment";
1968
1969         if (!(m = dbus_message_new_method_call(
1970                               "org.freedesktop.systemd1",
1971                               "/org/freedesktop/systemd1",
1972                               "org.freedesktop.systemd1.Manager",
1973                               method))) {
1974
1975                 log_error("Could not allocate message.");
1976                 return -ENOMEM;
1977         }
1978
1979         dbus_message_iter_init_append(m, &iter);
1980
1981         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
1982                 log_error("Could not append arguments to message.");
1983                 r = -ENOMEM;
1984                 goto finish;
1985         }
1986
1987         for (i = 1; i < n; i++)
1988                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
1989                         log_error("Could not append arguments to message.");
1990                         r = -ENOMEM;
1991                         goto finish;
1992                 }
1993
1994         if (!dbus_message_iter_close_container(&iter, &sub)) {
1995                 log_error("Could not append arguments to message.");
1996                 r = -ENOMEM;
1997                 goto finish;
1998         }
1999
2000         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2001                 log_error("Failed to issue method call: %s", error.message);
2002                 r = -EIO;
2003                 goto finish;
2004         }
2005
2006         r = 0;
2007
2008 finish:
2009         if (m)
2010                 dbus_message_unref(m);
2011
2012         if (reply)
2013                 dbus_message_unref(reply);
2014
2015         dbus_error_free(&error);
2016
2017         return r;
2018 }
2019
2020 static int systemctl_help(void) {
2021
2022         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
2023                "Send control commands to the systemd manager.\n\n"
2024                "  -h --help          Show this help\n"
2025                "  -t --type=TYPE     List only units of a particular type\n"
2026                "  -p --property=NAME Show only property by this name\n"
2027                "  -a --all           Show all units/properties, including dead/empty ones\n"
2028                "     --replace       When installing a new job, replace existing conflicting ones\n"
2029                "     --system        Connect to system bus\n"
2030                "     --session       Connect to session bus\n"
2031                "  -q --quiet         Suppress output\n"
2032                "     --no-block      Do not wait until operation finished\n"
2033                "     --no-wall       Don't send wall message before halt/power-off/reboot\n\n"
2034                "Commands:\n"
2035                "  list-units                      List units\n"
2036                "  start [NAME...]                 Start one or more units\n"
2037                "  stop [NAME...]                  Stop one or more units\n"
2038                "  restart [NAME...]               Restart one or more units\n"
2039                "  reload [NAME...]                Reload one or more units\n"
2040                "  isolate [NAME]                  Start one unit and stop all others\n"
2041                "  check [NAME...]                 Check whether any of the passed units are active\n"
2042                "  show [NAME...|JOB...]           Show information about one or more units\n"
2043                "  load [NAME...]                  Load one or more units\n"
2044                "  list-jobs                       List jobs\n"
2045                "  cancel [JOB...]                 Cancel one or more jobs\n"
2046                "  clear-jobs                      Cancel all jobs\n"
2047                "  monitor                         Monitor unit/job changes\n"
2048                "  dump                            Dump server status\n"
2049                "  snapshot [NAME]                 Create a snapshot\n"
2050                "  delete [NAME...]                Remove one or more snapshots\n"
2051                "  daemon-reload                   Reload systemd manager configuration\n"
2052                "  daemon-reexec                   Reexecute systemd manager\n"
2053                "  daemon-exit                     Ask the systemd manager to quit\n"
2054                "  show-environment                Dump environment\n"
2055                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
2056                "  unset-environment [NAME...]     Unset one or more environment variables\n"
2057                "  halt                            Shut down and halt the system\n"
2058                "  poweroff                        Shut down and power-off the system\n"
2059                "  reboot                          Shut down and reboot the system\n"
2060                "  default                         Enter default mode\n"
2061                "  rescue                          Enter rescue mode\n"
2062                "  emergency                       Enter emergency mode\n",
2063                program_invocation_short_name);
2064
2065         return 0;
2066 }
2067
2068 static int halt_help(void) {
2069
2070         printf("%s [OPTIONS...]\n\n"
2071                "%s the system.\n\n"
2072                "     --help      Show this help\n"
2073                "     --halt      Halt the machine\n"
2074                "  -p --poweroff  Switch off the machine\n"
2075                "     --reboot    Reboot the machine\n"
2076                "  -f --force     Force immediate halt/power-off/reboot\n"
2077                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
2078                "  -d --no-wtmp   Don't write wtmp record\n"
2079                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
2080                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
2081                program_invocation_short_name,
2082                arg_action == ACTION_REBOOT   ? "Reboot" :
2083                arg_action == ACTION_POWEROFF ? "Power off" :
2084                                                "Halt");
2085
2086         return 0;
2087 }
2088
2089 static int shutdown_help(void) {
2090
2091         printf("%s [OPTIONS...] [now] [WALL...]\n\n"
2092                "Shut down the system.\n\n"
2093                "     --help      Show this help\n"
2094                "  -H --halt      Halt the machine\n"
2095                "  -P --poweroff  Power-off the machine\n"
2096                "  -r --reboot    Reboot the machine\n"
2097                "  -h             Equivalent to --poweroff, overriden by --halt\n"
2098                "  -k             Don't halt/power-off/reboot, just send warnings\n"
2099                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
2100                program_invocation_short_name);
2101
2102         return 0;
2103 }
2104
2105 static int telinit_help(void) {
2106
2107         printf("%s [OPTIONS...] {COMMAND}\n\n"
2108                "Send control commands to the init daemon.\n\n"
2109                "     --help      Show this help\n"
2110                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
2111                "Commands:\n"
2112                "  0              Power-off the machine\n"
2113                "  6              Reboot the machine\n"
2114                "  2, 3, 4, 5     Start runlevelX.target unit\n"
2115                "  1, s, S        Enter rescue mode\n"
2116                "  q, Q           Reload init daemon configuration\n"
2117                "  u, U           Reexecute init daemon\n",
2118                program_invocation_short_name);
2119
2120         return 0;
2121 }
2122
2123 static int runlevel_help(void) {
2124
2125         printf("%s [OPTIONS...]\n\n"
2126                "Prints the previous and current runlevel of the init system.\n\n"
2127                "     --help      Show this help\n",
2128                program_invocation_short_name);
2129
2130         return 0;
2131 }
2132
2133 static int systemctl_parse_argv(int argc, char *argv[]) {
2134
2135         enum {
2136                 ARG_REPLACE = 0x100,
2137                 ARG_SESSION,
2138                 ARG_SYSTEM,
2139                 ARG_NO_BLOCK,
2140                 ARG_NO_WALL
2141         };
2142
2143         static const struct option options[] = {
2144                 { "help",      no_argument,       NULL, 'h'          },
2145                 { "type",      required_argument, NULL, 't'          },
2146                 { "property",  required_argument, NULL, 'p'          },
2147                 { "all",       no_argument,       NULL, 'a'          },
2148                 { "replace",   no_argument,       NULL, ARG_REPLACE  },
2149                 { "session",   no_argument,       NULL, ARG_SESSION  },
2150                 { "system",    no_argument,       NULL, ARG_SYSTEM   },
2151                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK },
2152                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL  },
2153                 { "quiet",     no_argument,       NULL, 'q'          },
2154                 { NULL,        0,                 NULL, 0            }
2155         };
2156
2157         int c;
2158
2159         assert(argc >= 0);
2160         assert(argv);
2161
2162         while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
2163
2164                 switch (c) {
2165
2166                 case 'h':
2167                         systemctl_help();
2168                         return 0;
2169
2170                 case 't':
2171                         arg_type = optarg;
2172                         break;
2173
2174                 case 'p':
2175                         arg_property = optarg;
2176
2177                         /* If the user asked for a particular
2178                          * property, show it to him, even if it is
2179                          * empty. */
2180                         arg_all = true;
2181                         break;
2182
2183                 case 'a':
2184                         arg_all = true;
2185                         break;
2186
2187                 case ARG_REPLACE:
2188                         arg_replace = true;
2189                         break;
2190
2191                 case ARG_SESSION:
2192                         arg_session = true;
2193                         break;
2194
2195                 case ARG_SYSTEM:
2196                         arg_session = false;
2197                         break;
2198
2199                 case ARG_NO_BLOCK:
2200                         arg_no_block = true;
2201                         break;
2202
2203                 case ARG_NO_WALL:
2204                         arg_no_wall = true;
2205                         break;
2206
2207                 case 'q':
2208                         arg_quiet = true;
2209                         break;
2210
2211                 case '?':
2212                         return -EINVAL;
2213
2214                 default:
2215                         log_error("Unknown option code %c", c);
2216                         return -EINVAL;
2217                 }
2218         }
2219
2220         return 1;
2221 }
2222
2223 static int halt_parse_argv(int argc, char *argv[]) {
2224
2225         enum {
2226                 ARG_HELP = 0x100,
2227                 ARG_HALT,
2228                 ARG_REBOOT,
2229                 ARG_NO_WALL
2230         };
2231
2232         static const struct option options[] = {
2233                 { "help",      no_argument,       NULL, ARG_HELP    },
2234                 { "halt",      no_argument,       NULL, ARG_HALT    },
2235                 { "poweroff",  no_argument,       NULL, 'p'         },
2236                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
2237                 { "force",     no_argument,       NULL, 'f'         },
2238                 { "wtmp-only", no_argument,       NULL, 'w'         },
2239                 { "no-wtmp",   no_argument,       NULL, 'd'         },
2240                 { "no-sync",   no_argument,       NULL, 'n'         },
2241                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
2242                 { NULL,        0,                 NULL, 0           }
2243         };
2244
2245         int c, runlevel;
2246
2247         assert(argc >= 0);
2248         assert(argv);
2249
2250         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
2251                 if (runlevel == '0' || runlevel == '6')
2252                         arg_immediate = true;
2253
2254         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
2255                 switch (c) {
2256
2257                 case ARG_HELP:
2258                         halt_help();
2259                         return 0;
2260
2261                 case ARG_HALT:
2262                         arg_action = ACTION_HALT;
2263                         break;
2264
2265                 case 'p':
2266                         arg_action = ACTION_POWEROFF;
2267                         break;
2268
2269                 case ARG_REBOOT:
2270                         arg_action = ACTION_REBOOT;
2271                         break;
2272
2273                 case 'f':
2274                         arg_immediate = true;
2275                         break;
2276
2277                 case 'w':
2278                         arg_dry = true;
2279                         break;
2280
2281                 case 'd':
2282                         arg_no_wtmp = true;
2283                         break;
2284
2285                 case 'n':
2286                         arg_no_sync = true;
2287                         break;
2288
2289                 case ARG_NO_WALL:
2290                         arg_no_wall = true;
2291                         break;
2292
2293                 case 'i':
2294                 case 'h':
2295                         /* Compatibility nops */
2296                         break;
2297
2298                 case '?':
2299                         return -EINVAL;
2300
2301                 default:
2302                         log_error("Unknown option code %c", c);
2303                         return -EINVAL;
2304                 }
2305         }
2306
2307         if (optind < argc) {
2308                 log_error("Too many arguments.");
2309                 return -EINVAL;
2310         }
2311
2312         return 1;
2313 }
2314
2315 static int shutdown_parse_argv(int argc, char *argv[]) {
2316
2317         enum {
2318                 ARG_HELP = 0x100,
2319                 ARG_NO_WALL
2320         };
2321
2322         static const struct option options[] = {
2323                 { "help",      no_argument,       NULL, ARG_HELP    },
2324                 { "halt",      no_argument,       NULL, 'H'         },
2325                 { "poweroff",  no_argument,       NULL, 'P'         },
2326                 { "reboot",    no_argument,       NULL, 'r'         },
2327                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
2328                 { NULL,        0,                 NULL, 0           }
2329         };
2330
2331         int c;
2332
2333         assert(argc >= 0);
2334         assert(argv);
2335
2336         while ((c = getopt_long(argc, argv, "HPrhkt:a", options, NULL)) >= 0) {
2337                 switch (c) {
2338
2339                 case ARG_HELP:
2340                         shutdown_help();
2341                         return 0;
2342
2343                 case 'H':
2344                         arg_action = ACTION_HALT;
2345                         break;
2346
2347                 case 'P':
2348                         arg_action = ACTION_POWEROFF;
2349                         break;
2350
2351                 case 'r':
2352                         arg_action = ACTION_REBOOT;
2353                         break;
2354
2355                 case 'h':
2356                         if (arg_action != ACTION_HALT)
2357                                 arg_action = ACTION_POWEROFF;
2358                         break;
2359
2360                 case 'k':
2361                         arg_dry = true;
2362                         break;
2363
2364                 case ARG_NO_WALL:
2365                         arg_no_wall = true;
2366                         break;
2367
2368                 case 't':
2369                 case 'a':
2370                         /* Compatibility nops */
2371                         break;
2372
2373                 case '?':
2374                         return -EINVAL;
2375
2376                 default:
2377                         log_error("Unknown option code %c", c);
2378                         return -EINVAL;
2379                 }
2380         }
2381
2382         if (argc > optind && !streq(argv[optind], "now"))
2383                 log_warning("First argument '%s' isn't 'now'. Ignoring.", argv[optind]);
2384
2385         /* We ignore the time argument */
2386         if (argc > optind + 1)
2387                 arg_wall = argv + optind + 1;
2388
2389         optind = argc;
2390
2391         return 1;
2392 }
2393
2394 static int telinit_parse_argv(int argc, char *argv[]) {
2395
2396         enum {
2397                 ARG_HELP = 0x100,
2398                 ARG_NO_WALL
2399         };
2400
2401         static const struct option options[] = {
2402                 { "help",      no_argument,       NULL, ARG_HELP    },
2403                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
2404                 { NULL,        0,                 NULL, 0           }
2405         };
2406
2407         static const struct {
2408                 char from;
2409                 enum action to;
2410         } table[] = {
2411                 { '0', ACTION_POWEROFF },
2412                 { '6', ACTION_REBOOT },
2413                 { '1', ACTION_RESCUE },
2414                 { '2', ACTION_RUNLEVEL2 },
2415                 { '3', ACTION_RUNLEVEL3 },
2416                 { '4', ACTION_RUNLEVEL4 },
2417                 { '5', ACTION_RUNLEVEL5 },
2418                 { 's', ACTION_RESCUE },
2419                 { 'S', ACTION_RESCUE },
2420                 { 'q', ACTION_RELOAD },
2421                 { 'Q', ACTION_RELOAD },
2422                 { 'u', ACTION_REEXEC },
2423                 { 'U', ACTION_REEXEC }
2424         };
2425
2426         unsigned i;
2427         int c;
2428
2429         assert(argc >= 0);
2430         assert(argv);
2431
2432         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
2433                 switch (c) {
2434
2435                 case ARG_HELP:
2436                         telinit_help();
2437                         return 0;
2438
2439                 case ARG_NO_WALL:
2440                         arg_no_wall = true;
2441                         break;
2442
2443                 case '?':
2444                         return -EINVAL;
2445
2446                 default:
2447                         log_error("Unknown option code %c", c);
2448                         return -EINVAL;
2449                 }
2450         }
2451
2452         if (optind >= argc) {
2453                 telinit_help();
2454                 return -EINVAL;
2455         }
2456
2457         if (optind + 1 < argc) {
2458                 log_error("Too many arguments.");
2459                 return -EINVAL;
2460         }
2461
2462         if (strlen(argv[optind]) != 1) {
2463                 log_error("Expected single character argument.");
2464                 return -EINVAL;
2465         }
2466
2467         for (i = 0; i < ELEMENTSOF(table); i++)
2468                 if (table[i].from == argv[optind][0])
2469                         break;
2470
2471         if (i >= ELEMENTSOF(table)) {
2472                 log_error("Unknown command %s.", argv[optind]);
2473                 return -EINVAL;
2474         }
2475
2476         arg_action = table[i].to;
2477
2478         optind ++;
2479
2480         return 1;
2481 }
2482
2483 static int runlevel_parse_argv(int argc, char *argv[]) {
2484
2485         enum {
2486                 ARG_HELP = 0x100,
2487         };
2488
2489         static const struct option options[] = {
2490                 { "help",      no_argument,       NULL, ARG_HELP    },
2491                 { NULL,        0,                 NULL, 0           }
2492         };
2493
2494         int c;
2495
2496         assert(argc >= 0);
2497         assert(argv);
2498
2499         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
2500                 switch (c) {
2501
2502                 case ARG_HELP:
2503                         runlevel_help();
2504                         return 0;
2505
2506                 case '?':
2507                         return -EINVAL;
2508
2509                 default:
2510                         log_error("Unknown option code %c", c);
2511                         return -EINVAL;
2512                 }
2513         }
2514
2515         if (optind < argc) {
2516                 log_error("Too many arguments.");
2517                 return -EINVAL;
2518         }
2519
2520         return 1;
2521 }
2522
2523 static int parse_argv(int argc, char *argv[]) {
2524         assert(argc >= 0);
2525         assert(argv);
2526
2527         if (program_invocation_short_name) {
2528
2529                 if (strstr(program_invocation_short_name, "halt")) {
2530                         arg_action = ACTION_HALT;
2531                         return halt_parse_argv(argc, argv);
2532                 } else if (strstr(program_invocation_short_name, "poweroff")) {
2533                         arg_action = ACTION_POWEROFF;
2534                         return halt_parse_argv(argc, argv);
2535                 } else if (strstr(program_invocation_short_name, "reboot")) {
2536                         arg_action = ACTION_REBOOT;
2537                         return halt_parse_argv(argc, argv);
2538                 } else if (strstr(program_invocation_short_name, "shutdown")) {
2539                         arg_action = ACTION_POWEROFF;
2540                         return shutdown_parse_argv(argc, argv);
2541                 } else if (strstr(program_invocation_short_name, "init")) {
2542                         arg_action = ACTION_INVALID;
2543                         return telinit_parse_argv(argc, argv);
2544                 } else if (strstr(program_invocation_short_name, "runlevel")) {
2545                         arg_action = ACTION_RUNLEVEL;
2546                         return runlevel_parse_argv(argc, argv);
2547                 }
2548         }
2549
2550         arg_action = ACTION_SYSTEMCTL;
2551         return systemctl_parse_argv(argc, argv);
2552 }
2553
2554 static int action_to_runlevel(void) {
2555
2556         static const char table[_ACTION_MAX] = {
2557                 [ACTION_HALT] =      '0',
2558                 [ACTION_POWEROFF] =  '0',
2559                 [ACTION_REBOOT] =    '6',
2560                 [ACTION_RUNLEVEL2] = '2',
2561                 [ACTION_RUNLEVEL3] = '3',
2562                 [ACTION_RUNLEVEL4] = '4',
2563                 [ACTION_RUNLEVEL5] = '5',
2564                 [ACTION_RESCUE] =    '1'
2565         };
2566
2567         assert(arg_action < _ACTION_MAX);
2568
2569         return table[arg_action];
2570 }
2571
2572 static int talk_upstart(void) {
2573         DBusMessage *m = NULL, *reply = NULL;
2574         DBusError error;
2575         int previous, rl, r;
2576         char
2577                 env1_buf[] = "RUNLEVEL=X",
2578                 env2_buf[] = "PREVLEVEL=X";
2579         char *env1 = env1_buf, *env2 = env2_buf;
2580         const char *emit = "runlevel";
2581         dbus_bool_t b_false = FALSE;
2582         DBusMessageIter iter, sub;
2583         DBusConnection *bus;
2584
2585         dbus_error_init(&error);
2586
2587         if (!(rl = action_to_runlevel()))
2588                 return 0;
2589
2590         if (utmp_get_runlevel(&previous, NULL) < 0)
2591                 previous = 'N';
2592
2593         if (!(bus = dbus_connection_open("unix:abstract=/com/ubuntu/upstart", &error))) {
2594                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
2595                         r = 0;
2596                         goto finish;
2597                 }
2598
2599                 log_error("Failed to connect to Upstart bus: %s", error.message);
2600                 r = -EIO;
2601                 goto finish;
2602         }
2603
2604         if ((r = bus_check_peercred(bus)) < 0) {
2605                 log_error("Failed to verify owner of bus.");
2606                 goto finish;
2607         }
2608
2609         if (!(m = dbus_message_new_method_call(
2610                               "com.ubuntu.Upstart",
2611                               "/com/ubuntu/Upstart",
2612                               "com.ubuntu.Upstart0_6",
2613                               "EmitEvent"))) {
2614
2615                 log_error("Could not allocate message.");
2616                 r = -ENOMEM;
2617                 goto finish;
2618         }
2619
2620         dbus_message_iter_init_append(m, &iter);
2621
2622         env1_buf[sizeof(env1_buf)-2] = rl;
2623         env2_buf[sizeof(env2_buf)-2] = previous;
2624
2625         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
2626             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
2627             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
2628             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
2629             !dbus_message_iter_close_container(&iter, &sub) ||
2630             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
2631                 log_error("Could not append arguments to message.");
2632                 r = -ENOMEM;
2633                 goto finish;
2634         }
2635
2636         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2637
2638                 if (error_is_no_service(&error)) {
2639                         r = 0;
2640                         goto finish;
2641                 }
2642
2643                 log_error("Failed to issue method call: %s", error.message);
2644                 r = -EIO;
2645                 goto finish;
2646         }
2647
2648         r = 1;
2649
2650 finish:
2651         if (m)
2652                 dbus_message_unref(m);
2653
2654         if (reply)
2655                 dbus_message_unref(reply);
2656
2657         if (bus)
2658                 dbus_connection_unref(bus);
2659
2660         dbus_error_free(&error);
2661
2662         return r;
2663 }
2664
2665 static int talk_initctl(void) {
2666         struct init_request request;
2667         int r, fd;
2668         char rl;
2669
2670         if (!(rl = action_to_runlevel()))
2671                 return 0;
2672
2673         zero(request);
2674         request.magic = INIT_MAGIC;
2675         request.sleeptime = 0;
2676         request.cmd = INIT_CMD_RUNLVL;
2677         request.runlevel = rl;
2678
2679         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
2680
2681                 if (errno == ENOENT)
2682                         return 0;
2683
2684                 log_error("Failed to open "INIT_FIFO": %m");
2685                 return -errno;
2686         }
2687
2688         errno = 0;
2689         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
2690         close_nointr_nofail(fd);
2691
2692         if (r < 0) {
2693                 log_error("Failed to write to "INIT_FIFO": %m");
2694                 return errno ? -errno : -EIO;
2695         }
2696
2697         return 1;
2698 }
2699
2700 static int systemctl_main(DBusConnection *bus, int argc, char *argv[]) {
2701
2702         static const struct {
2703                 const char* verb;
2704                 const enum {
2705                         MORE,
2706                         LESS,
2707                         EQUAL
2708                 } argc_cmp;
2709                 const int argc;
2710                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
2711         } verbs[] = {
2712                 { "list-units",        LESS,  1, list_units      },
2713                 { "list-jobs",         EQUAL, 1, list_jobs       },
2714                 { "clear-jobs",        EQUAL, 1, clear_jobs      },
2715                 { "load",              MORE,  2, load_unit       },
2716                 { "cancel",            MORE,  2, cancel_job      },
2717                 { "start",             MORE,  2, start_unit      },
2718                 { "stop",              MORE,  2, start_unit      },
2719                 { "reload",            MORE,  2, start_unit      },
2720                 { "restart",           MORE,  2, start_unit      },
2721                 { "isolate",           EQUAL, 2, start_unit      },
2722                 { "check",             MORE,  2, check_unit      },
2723                 { "show",              MORE,  1, show            },
2724                 { "monitor",           EQUAL, 1, monitor         },
2725                 { "dump",              EQUAL, 1, dump            },
2726                 { "snapshot",          LESS,  2, snapshot        },
2727                 { "delete",            MORE,  2, delete_snapshot },
2728                 { "daemon-reload",     EQUAL, 1, clear_jobs      },
2729                 { "daemon-reexec",     EQUAL, 1, clear_jobs      },
2730                 { "daemon-exit",       EQUAL, 1, clear_jobs      },
2731                 { "show-environment",  EQUAL, 1, show_enviroment },
2732                 { "set-environment",   MORE,  2, set_environment },
2733                 { "unset-environment", MORE,  2, set_environment },
2734                 { "halt",              EQUAL, 1, start_special   },
2735                 { "poweroff",          EQUAL, 1, start_special   },
2736                 { "reboot",            EQUAL, 1, start_special   },
2737                 { "default",           EQUAL, 1, start_special   },
2738                 { "rescue",            EQUAL, 1, start_special   },
2739                 { "emergency",         EQUAL, 1, start_special   },
2740         };
2741
2742         int left;
2743         unsigned i;
2744
2745         assert(bus);
2746         assert(argc >= 0);
2747         assert(argv);
2748
2749         left = argc - optind;
2750
2751         if (left <= 0)
2752                 /* Special rule: no arguments means "list-units" */
2753                 i = 0;
2754         else {
2755                 if (streq(argv[optind], "help")) {
2756                         systemctl_help();
2757                         return 0;
2758                 }
2759
2760                 for (i = 0; i < ELEMENTSOF(verbs); i++)
2761                         if (streq(argv[optind], verbs[i].verb))
2762                                 break;
2763
2764                 if (i >= ELEMENTSOF(verbs)) {
2765                         log_error("Unknown operation %s", argv[optind]);
2766                         return -EINVAL;
2767                 }
2768         }
2769
2770         switch (verbs[i].argc_cmp) {
2771
2772         case EQUAL:
2773                 if (left != verbs[i].argc) {
2774                         log_error("Invalid number of arguments.");
2775                         return -EINVAL;
2776                 }
2777
2778                 break;
2779
2780         case MORE:
2781                 if (left < verbs[i].argc) {
2782                         log_error("Too few arguments.");
2783                         return -EINVAL;
2784                 }
2785
2786                 break;
2787
2788         case LESS:
2789                 if (left > verbs[i].argc) {
2790                         log_error("Too many arguments.");
2791                         return -EINVAL;
2792                 }
2793
2794                 break;
2795
2796         default:
2797                 assert_not_reached("Unknown comparison operator.");
2798         }
2799
2800         return verbs[i].dispatch(bus, argv + optind, left);
2801 }
2802
2803 static int reload_with_fallback(DBusConnection *bus) {
2804         int r;
2805
2806         if (bus) {
2807                 /* First, try systemd via D-Bus. */
2808                 if ((r = clear_jobs(bus, NULL, 0)) > 0)
2809                         return 0;
2810         }
2811
2812         /* Nothing else worked, so let's try signals */
2813         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
2814
2815         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
2816                 log_error("kill() failed: %m");
2817                 return -errno;
2818         }
2819
2820         return 0;
2821 }
2822
2823 static int start_with_fallback(DBusConnection *bus) {
2824         int r;
2825
2826         warn_wall(arg_action);
2827
2828         if (bus) {
2829                 /* First, try systemd via D-Bus. */
2830                 if ((r = start_unit(bus, NULL, 0)) > 0)
2831                         return 0;
2832
2833                 /* Hmm, talking to systemd via D-Bus didn't work. Then
2834                  * let's try to talk to Upstart via D-Bus. */
2835                 if ((r = talk_upstart()) > 0)
2836                         return 0;
2837         }
2838
2839         /* Nothing else worked, so let's try
2840          * /dev/initctl */
2841         if ((r = talk_initctl()) != 0)
2842                 return 0;
2843
2844         log_error("Failed to talk to init daemon.");
2845         return -EIO;
2846 }
2847
2848 static int halt_main(DBusConnection *bus) {
2849         int r;
2850
2851         if (!arg_immediate)
2852                 return start_with_fallback(bus);
2853
2854         if (!arg_no_wtmp)
2855                 if ((r = utmp_put_shutdown(0)) < 0)
2856                         log_warning("Failed to write utmp record: %s", strerror(-r));
2857
2858         if (!arg_no_sync)
2859                 sync();
2860
2861         if (arg_dry)
2862                 return 0;
2863
2864         /* Make sure C-A-D is handled by the kernel from this
2865          * point on... */
2866         reboot(RB_ENABLE_CAD);
2867
2868         switch (arg_action) {
2869
2870         case ACTION_HALT:
2871                 log_info("Halting");
2872                 reboot(RB_HALT_SYSTEM);
2873                 break;
2874
2875         case ACTION_POWEROFF:
2876                 log_info("Powering off");
2877                 reboot(RB_POWER_OFF);
2878                 break;
2879
2880         case ACTION_REBOOT:
2881                 log_info("Rebooting");
2882                 reboot(RB_AUTOBOOT);
2883                 break;
2884
2885         default:
2886                 assert_not_reached("Unknown halt action.");
2887         }
2888
2889         /* We should never reach this. */
2890         return -ENOSYS;
2891 }
2892
2893 static int runlevel_main(void) {
2894         int r, runlevel, previous;
2895
2896         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
2897                 printf("unknown");
2898                 return r;
2899         }
2900
2901         printf("%c %c\n",
2902                previous <= 0 ? 'N' : previous,
2903                runlevel <= 0 ? 'N' : runlevel);
2904
2905         return 0;
2906 }
2907
2908 int main(int argc, char*argv[]) {
2909         int r, retval = 1;
2910         DBusConnection *bus = NULL;
2911         DBusError error;
2912
2913         dbus_error_init(&error);
2914
2915         log_parse_environment();
2916
2917         if ((r = parse_argv(argc, argv)) < 0)
2918                 goto finish;
2919         else if (r == 0) {
2920                 retval = 0;
2921                 goto finish;
2922         }
2923
2924         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
2925          * let's shortcut this */
2926         if (arg_action == ACTION_RUNLEVEL) {
2927                 retval = runlevel_main() < 0;
2928                 goto finish;
2929         }
2930
2931         /* If we are root, then let's not go via the bus */
2932         if (geteuid() == 0 && !arg_session) {
2933                 bus = dbus_connection_open("unix:abstract=/org/freedesktop/systemd1/private", &error);
2934
2935                 if (bus && bus_check_peercred(bus) < 0) {
2936                         log_error("Failed to verify owner of bus.");
2937                         goto finish;
2938                 }
2939         } else
2940                 bus = dbus_bus_get(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error);
2941
2942         if (bus)
2943                 dbus_connection_set_exit_on_disconnect(bus, FALSE);
2944
2945         switch (arg_action) {
2946
2947         case ACTION_SYSTEMCTL: {
2948
2949                 if (!bus) {
2950                         log_error("Failed to get D-Bus connection: %s", error.message);
2951                         goto finish;
2952                 }
2953
2954                 retval = systemctl_main(bus, argc, argv) < 0;
2955                 break;
2956         }
2957
2958         case ACTION_HALT:
2959         case ACTION_POWEROFF:
2960         case ACTION_REBOOT:
2961                 retval = halt_main(bus) < 0;
2962                 break;
2963
2964         case ACTION_RUNLEVEL2:
2965         case ACTION_RUNLEVEL3:
2966         case ACTION_RUNLEVEL4:
2967         case ACTION_RUNLEVEL5:
2968         case ACTION_RESCUE:
2969         case ACTION_EMERGENCY:
2970         case ACTION_DEFAULT:
2971                 retval = start_with_fallback(bus) < 0;
2972                 break;
2973
2974         case ACTION_RELOAD:
2975         case ACTION_REEXEC:
2976                 retval = reload_with_fallback(bus) < 0;
2977                 break;
2978
2979         case ACTION_INVALID:
2980         case ACTION_RUNLEVEL:
2981         default:
2982                 assert_not_reached("Unknown action");
2983         }
2984
2985 finish:
2986
2987         if (bus)
2988                 dbus_connection_unref(bus);
2989
2990         dbus_error_free(&error);
2991
2992         dbus_shutdown();
2993
2994         return retval;
2995 }