chiark / gitweb /
72bb7d804460830d0d064731346ad4b912f7d029
[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")) {
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") || strstr(name, "Mode"))
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                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
1115                         DBusMessageIter sub;
1116
1117                         dbus_message_iter_recurse(iter, &sub);
1118
1119                         if (arg_all ||
1120                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1121                                 printf("%s=", name);
1122
1123                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1124                                         uint8_t u;
1125
1126                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1127                                         dbus_message_iter_get_basic(&sub, &u);
1128                                         printf("%02x", u);
1129
1130                                         dbus_message_iter_next(&sub);
1131                                 }
1132
1133                                 puts("");
1134                         }
1135
1136                         return 0;
1137                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
1138                         DBusMessageIter sub, sub2;
1139
1140                         dbus_message_iter_recurse(iter, &sub);
1141
1142                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1143                                 const char *type, *path;
1144
1145                                 dbus_message_iter_recurse(&sub, &sub2);
1146
1147                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
1148                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
1149                                         printf("%s=%s\n", type, path);
1150
1151                                 dbus_message_iter_next(&sub);
1152                         }
1153
1154                         return 0;
1155                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
1156                         DBusMessageIter sub, sub2;
1157
1158                         dbus_message_iter_recurse(iter, &sub);
1159
1160                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1161                                 const char *base;
1162                                 uint64_t value, next_elapse;
1163
1164                                 dbus_message_iter_recurse(&sub, &sub2);
1165
1166                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
1167                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
1168                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0)
1169                                         printf("%s={ value=%llu ; next_elapse=%llu }\n",
1170                                                base,
1171                                                (unsigned long long) value,
1172                                                (unsigned long long) next_elapse);
1173
1174                                 dbus_message_iter_next(&sub);
1175                         }
1176
1177                         return 0;
1178                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
1179
1180                         DBusMessageIter sub, sub2, sub3;
1181
1182                         dbus_message_iter_recurse(iter, &sub);
1183
1184                         while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
1185                                 const char *path;
1186                                 uint64_t start_time, exit_time;
1187                                 uint32_t pid;
1188                                 int32_t code, status;
1189
1190                                 dbus_message_iter_recurse(&sub, &sub2);
1191
1192                                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1193                                         continue;
1194
1195                                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1196                                     dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1197                                         continue;
1198
1199                                 printf("%s={ path=%s ; argv[]=", name, path);
1200
1201                                 dbus_message_iter_recurse(&sub2, &sub3);
1202
1203                                 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1204                                         const char *s;
1205
1206                                         assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1207                                         dbus_message_iter_get_basic(&sub3, &s);
1208                                         printf("%s ", s);
1209                                         dbus_message_iter_next(&sub3);
1210                                 }
1211
1212                                 if (dbus_message_iter_next(&sub2) &&
1213                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_time, true) >= 0 &&
1214                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_time, true) >= 0 &&
1215                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) >= 0 &&
1216                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) >= 0 &&
1217                                     bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) >= 0) {
1218
1219                                         char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
1220
1221                                         printf("; start=%s ; stop=%s ; pid=%u ; code=%s ; status=%i/%s",
1222                                                strna(format_timestamp(timestamp1, sizeof(timestamp1), start_time)),
1223                                                strna(format_timestamp(timestamp2, sizeof(timestamp2), exit_time)),
1224                                                (unsigned) pid,
1225                                                sigchld_code_to_string(code),
1226                                                status,
1227                                                strna(code == CLD_EXITED ? NULL : strsignal(status)));
1228                                 }
1229
1230                                 printf(" }\n");
1231
1232                                 dbus_message_iter_next(&sub);
1233                         }
1234
1235                         return 0;
1236                 }
1237
1238                 break;
1239         }
1240
1241         if (arg_all)
1242                 printf("%s=[unprintable]\n", name);
1243
1244         return 0;
1245 }
1246
1247 static int show_one(DBusConnection *bus, const char *path) {
1248         DBusMessage *m = NULL, *reply = NULL;
1249         const char *interface = "";
1250         int r;
1251         DBusError error;
1252         DBusMessageIter iter, sub, sub2, sub3;
1253
1254         assert(bus);
1255         assert(path);
1256
1257         dbus_error_init(&error);
1258
1259         if (!(m = dbus_message_new_method_call(
1260                               "org.freedesktop.systemd1",
1261                               path,
1262                               "org.freedesktop.DBus.Properties",
1263                               "GetAll"))) {
1264                 log_error("Could not allocate message.");
1265                 r = -ENOMEM;
1266                 goto finish;
1267         }
1268
1269         if (!dbus_message_append_args(m,
1270                                       DBUS_TYPE_STRING, &interface,
1271                                       DBUS_TYPE_INVALID)) {
1272                 log_error("Could not append arguments to message.");
1273                 r = -ENOMEM;
1274                 goto finish;
1275         }
1276
1277         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1278                 log_error("Failed to issue method call: %s", error.message);
1279                 r = -EIO;
1280                 goto finish;
1281         }
1282
1283         if (!dbus_message_iter_init(reply, &iter) ||
1284             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1285             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
1286                 log_error("Failed to parse reply.");
1287                 r = -EIO;
1288                 goto finish;
1289         }
1290
1291         dbus_message_iter_recurse(&iter, &sub);
1292
1293         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1294                 const char *name;
1295
1296                 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
1297                         log_error("Failed to parse reply.");
1298                         r = -EIO;
1299                         goto finish;
1300                 }
1301
1302                 dbus_message_iter_recurse(&sub, &sub2);
1303
1304                 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
1305                         log_error("Failed to parse reply.");
1306                         r = -EIO;
1307                         goto finish;
1308                 }
1309
1310                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
1311                         log_error("Failed to parse reply.");
1312                         r = -EIO;
1313                         goto finish;
1314                 }
1315
1316                 dbus_message_iter_recurse(&sub2, &sub3);
1317
1318                 if (print_property(name, &sub3) < 0) {
1319                         log_error("Failed to parse reply.");
1320                         r = -EIO;
1321                         goto finish;
1322                 }
1323
1324                 dbus_message_iter_next(&sub);
1325         }
1326
1327         r = 0;
1328
1329 finish:
1330         if (m)
1331                 dbus_message_unref(m);
1332
1333         if (reply)
1334                 dbus_message_unref(reply);
1335
1336         dbus_error_free(&error);
1337
1338         return r;
1339 }
1340
1341 static int show(DBusConnection *bus, char **args, unsigned n) {
1342         DBusMessage *m = NULL, *reply = NULL;
1343         int r;
1344         DBusError error;
1345         unsigned i;
1346
1347         assert(bus);
1348         assert(args);
1349
1350         dbus_error_init(&error);
1351
1352         if (n <= 1) {
1353                 /* If not argument is specified inspect the manager
1354                  * itself */
1355
1356                 r = show_one(bus, "/org/freedesktop/systemd1");
1357                 goto finish;
1358         }
1359
1360         for (i = 1; i < n; i++) {
1361                 const char *path = NULL;
1362                 uint32_t id;
1363
1364                 if (safe_atou32(args[i], &id) < 0) {
1365
1366                         if (!(m = dbus_message_new_method_call(
1367                                               "org.freedesktop.systemd1",
1368                                               "/org/freedesktop/systemd1",
1369                                               "org.freedesktop.systemd1.Manager",
1370                                               "LoadUnit"))) {
1371                                 log_error("Could not allocate message.");
1372                                 r = -ENOMEM;
1373                                 goto finish;
1374                         }
1375
1376                         if (!dbus_message_append_args(m,
1377                                                       DBUS_TYPE_STRING, &args[i],
1378                                                       DBUS_TYPE_INVALID)) {
1379                                 log_error("Could not append arguments to message.");
1380                                 r = -ENOMEM;
1381                                 goto finish;
1382                         }
1383
1384                 } else {
1385
1386                         if (!(m = dbus_message_new_method_call(
1387                                               "org.freedesktop.systemd1",
1388                                               "/org/freedesktop/systemd1",
1389                                               "org.freedesktop.systemd1.Manager",
1390                                               "GetJob"))) {
1391                                 log_error("Could not allocate message.");
1392                                 r = -ENOMEM;
1393                                 goto finish;
1394                         }
1395
1396                         if (!dbus_message_append_args(m,
1397                                                       DBUS_TYPE_UINT32, &id,
1398                                                       DBUS_TYPE_INVALID)) {
1399                                 log_error("Could not append arguments to message.");
1400                                 r = -ENOMEM;
1401                                 goto finish;
1402                         }
1403                 }
1404
1405                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1406                         log_error("Failed to issue method call: %s", error.message);
1407                         r = -EIO;
1408                         goto finish;
1409                 }
1410
1411                 if (!dbus_message_get_args(reply, &error,
1412                                            DBUS_TYPE_OBJECT_PATH, &path,
1413                                            DBUS_TYPE_INVALID)) {
1414                         log_error("Failed to parse reply: %s", error.message);
1415                         r = -EIO;
1416                         goto finish;
1417                 }
1418
1419                 if ((r = show_one(bus, path)) < 0)
1420                         goto finish;
1421
1422                 dbus_message_unref(m);
1423                 dbus_message_unref(reply);
1424                 m = reply = NULL;
1425         }
1426
1427         r = 0;
1428
1429 finish:
1430         if (m)
1431                 dbus_message_unref(m);
1432
1433         if (reply)
1434                 dbus_message_unref(reply);
1435
1436         dbus_error_free(&error);
1437
1438         return r;
1439 }
1440
1441 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1442         DBusError error;
1443         DBusMessage *m = NULL, *reply = NULL;
1444
1445         assert(connection);
1446         assert(message);
1447
1448         dbus_error_init(&error);
1449
1450         /* log_debug("Got D-Bus request: %s.%s() on %s", */
1451         /*           dbus_message_get_interface(message), */
1452         /*           dbus_message_get_member(message), */
1453         /*           dbus_message_get_path(message)); */
1454
1455         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1456                 log_error("Warning! D-Bus connection terminated.");
1457                 dbus_connection_close(connection);
1458
1459         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
1460                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
1461                 const char *id, *path;
1462
1463                 if (!dbus_message_get_args(message, &error,
1464                                            DBUS_TYPE_STRING, &id,
1465                                            DBUS_TYPE_OBJECT_PATH, &path,
1466                                            DBUS_TYPE_INVALID))
1467                         log_error("Failed to parse message: %s", error.message);
1468                 else if (streq(dbus_message_get_member(message), "UnitNew"))
1469                         printf("Unit %s added.\n", id);
1470                 else
1471                         printf("Unit %s removed.\n", id);
1472
1473         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew") ||
1474                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1475                 uint32_t id;
1476                 const char *path;
1477
1478                 if (!dbus_message_get_args(message, &error,
1479                                            DBUS_TYPE_UINT32, &id,
1480                                            DBUS_TYPE_OBJECT_PATH, &path,
1481                                            DBUS_TYPE_INVALID))
1482                         log_error("Failed to parse message: %s", error.message);
1483                 else if (streq(dbus_message_get_member(message), "JobNew"))
1484                         printf("Job %u added.\n", id);
1485                 else
1486                         printf("Job %u removed.\n", id);
1487
1488
1489         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Unit", "Changed") ||
1490                    dbus_message_is_signal(message, "org.freedesktop.systemd1.Job", "Changed")) {
1491
1492                 const char *path, *interface, *property = "Id";
1493                 DBusMessageIter iter, sub;
1494
1495                 path = dbus_message_get_path(message);
1496                 interface = dbus_message_get_interface(message);
1497
1498                 if (!(m = dbus_message_new_method_call(
1499                               "org.freedesktop.systemd1",
1500                               path,
1501                               "org.freedesktop.DBus.Properties",
1502                               "Get"))) {
1503                         log_error("Could not allocate message.");
1504                         goto oom;
1505                 }
1506
1507                 if (!dbus_message_append_args(m,
1508                                               DBUS_TYPE_STRING, &interface,
1509                                               DBUS_TYPE_STRING, &property,
1510                                               DBUS_TYPE_INVALID)) {
1511                         log_error("Could not append arguments to message.");
1512                         goto finish;
1513                 }
1514
1515                 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
1516                         log_error("Failed to issue method call: %s", error.message);
1517                         goto finish;
1518                 }
1519
1520                 if (!dbus_message_iter_init(reply, &iter) ||
1521                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1522                         log_error("Failed to parse reply.");
1523                         goto finish;
1524                 }
1525
1526                 dbus_message_iter_recurse(&iter, &sub);
1527
1528                 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
1529                         const char *id;
1530
1531                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1532                                 log_error("Failed to parse reply.");
1533                                 goto finish;
1534                         }
1535
1536                         dbus_message_iter_get_basic(&sub, &id);
1537                         printf("Unit %s changed.\n", id);
1538                 } else {
1539                         uint32_t id;
1540
1541                         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)  {
1542                                 log_error("Failed to parse reply.");
1543                                 goto finish;
1544                         }
1545
1546                         dbus_message_iter_get_basic(&sub, &id);
1547                         printf("Job %u changed.\n", id);
1548                 }
1549         }
1550
1551 finish:
1552         if (m)
1553                 dbus_message_unref(m);
1554
1555         if (reply)
1556                 dbus_message_unref(reply);
1557
1558         dbus_error_free(&error);
1559         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1560
1561 oom:
1562         if (m)
1563                 dbus_message_unref(m);
1564
1565         if (reply)
1566                 dbus_message_unref(reply);
1567
1568         dbus_error_free(&error);
1569         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1570 }
1571
1572 static int monitor(DBusConnection *bus, char **args, unsigned n) {
1573         DBusMessage *m = NULL, *reply = NULL;
1574         DBusError error;
1575         int r;
1576
1577         dbus_error_init(&error);
1578
1579         dbus_bus_add_match(bus,
1580                            "type='signal',"
1581                            "sender='org.freedesktop.systemd1',"
1582                            "interface='org.freedesktop.systemd1.Manager',"
1583                            "path='/org/freedesktop/systemd1'",
1584                            &error);
1585
1586         if (dbus_error_is_set(&error)) {
1587                 log_error("Failed to add match: %s", error.message);
1588                 r = -EIO;
1589                 goto finish;
1590         }
1591
1592         dbus_bus_add_match(bus,
1593                            "type='signal',"
1594                            "sender='org.freedesktop.systemd1',"
1595                            "interface='org.freedesktop.systemd1.Unit',"
1596                            "member='Changed'",
1597                            &error);
1598
1599         if (dbus_error_is_set(&error)) {
1600                 log_error("Failed to add match: %s", error.message);
1601                 r = -EIO;
1602                 goto finish;
1603         }
1604
1605         dbus_bus_add_match(bus,
1606                            "type='signal',"
1607                            "sender='org.freedesktop.systemd1',"
1608                            "interface='org.freedesktop.systemd1.Job',"
1609                            "member='Changed'",
1610                            &error);
1611
1612         if (dbus_error_is_set(&error)) {
1613                 log_error("Failed to add match: %s", error.message);
1614                 r = -EIO;
1615                 goto finish;
1616         }
1617
1618         if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
1619                 log_error("Failed to add filter.");
1620                 r = -ENOMEM;
1621                 goto finish;
1622         }
1623
1624         if (!(m = dbus_message_new_method_call(
1625                               "org.freedesktop.systemd1",
1626                               "/org/freedesktop/systemd1",
1627                               "org.freedesktop.systemd1.Manager",
1628                               "Subscribe"))) {
1629                 log_error("Could not allocate message.");
1630                 r = -ENOMEM;
1631                 goto finish;
1632         }
1633
1634         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1635                 log_error("Failed to issue method call: %s", error.message);
1636                 r = -EIO;
1637                 goto finish;
1638         }
1639
1640         while (dbus_connection_read_write_dispatch(bus, -1))
1641                 ;
1642
1643         r = 0;
1644
1645 finish:
1646
1647         /* This is slightly dirty, since we don't undo the filter or the matches. */
1648
1649         if (m)
1650                 dbus_message_unref(m);
1651
1652         if (reply)
1653                 dbus_message_unref(reply);
1654
1655         dbus_error_free(&error);
1656
1657         return r;
1658 }
1659
1660 static int dump(DBusConnection *bus, char **args, unsigned n) {
1661         DBusMessage *m = NULL, *reply = NULL;
1662         DBusError error;
1663         int r;
1664         const char *text;
1665
1666         dbus_error_init(&error);
1667
1668         if (!(m = dbus_message_new_method_call(
1669                               "org.freedesktop.systemd1",
1670                               "/org/freedesktop/systemd1",
1671                               "org.freedesktop.systemd1.Manager",
1672                               "Dump"))) {
1673                 log_error("Could not allocate message.");
1674                 return -ENOMEM;
1675         }
1676
1677         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1678                 log_error("Failed to issue method call: %s", error.message);
1679                 r = -EIO;
1680                 goto finish;
1681         }
1682
1683         if (!dbus_message_get_args(reply, &error,
1684                                    DBUS_TYPE_STRING, &text,
1685                                    DBUS_TYPE_INVALID)) {
1686                 log_error("Failed to parse reply: %s", error.message);
1687                 r = -EIO;
1688                 goto finish;
1689         }
1690
1691         fputs(text, stdout);
1692
1693         r = 0;
1694
1695 finish:
1696         if (m)
1697                 dbus_message_unref(m);
1698
1699         if (reply)
1700                 dbus_message_unref(reply);
1701
1702         dbus_error_free(&error);
1703
1704         return r;
1705 }
1706
1707 static int snapshot(DBusConnection *bus, char **args, unsigned n) {
1708         DBusMessage *m = NULL, *reply = NULL;
1709         DBusError error;
1710         int r;
1711         const char *name = "", *path, *id;
1712         dbus_bool_t cleanup = FALSE;
1713         DBusMessageIter iter, sub;
1714         const char
1715                 *interface = "org.freedesktop.systemd1.Unit",
1716                 *property = "Id";
1717
1718         dbus_error_init(&error);
1719
1720         if (!(m = dbus_message_new_method_call(
1721                               "org.freedesktop.systemd1",
1722                               "/org/freedesktop/systemd1",
1723                               "org.freedesktop.systemd1.Manager",
1724                               "CreateSnapshot"))) {
1725                 log_error("Could not allocate message.");
1726                 return -ENOMEM;
1727         }
1728
1729         if (n > 1)
1730                 name = args[1];
1731
1732         if (!dbus_message_append_args(m,
1733                                       DBUS_TYPE_STRING, &name,
1734                                       DBUS_TYPE_BOOLEAN, &cleanup,
1735                                       DBUS_TYPE_INVALID)) {
1736                 log_error("Could not append arguments to message.");
1737                 r = -ENOMEM;
1738                 goto finish;
1739         }
1740
1741         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1742                 log_error("Failed to issue method call: %s", error.message);
1743                 r = -EIO;
1744                 goto finish;
1745         }
1746
1747         if (!dbus_message_get_args(reply, &error,
1748                                    DBUS_TYPE_OBJECT_PATH, &path,
1749                                    DBUS_TYPE_INVALID)) {
1750                 log_error("Failed to parse reply: %s", error.message);
1751                 r = -EIO;
1752                 goto finish;
1753         }
1754
1755         dbus_message_unref(m);
1756         if (!(m = dbus_message_new_method_call(
1757                               "org.freedesktop.systemd1",
1758                               path,
1759                               "org.freedesktop.DBus.Properties",
1760                               "Get"))) {
1761                 log_error("Could not allocate message.");
1762                 return -ENOMEM;
1763         }
1764
1765         if (!dbus_message_append_args(m,
1766                                       DBUS_TYPE_STRING, &interface,
1767                                       DBUS_TYPE_STRING, &property,
1768                                       DBUS_TYPE_INVALID)) {
1769                 log_error("Could not append arguments to message.");
1770                 r = -ENOMEM;
1771                 goto finish;
1772         }
1773
1774         dbus_message_unref(reply);
1775         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1776                 log_error("Failed to issue method call: %s", error.message);
1777                 r = -EIO;
1778                 goto finish;
1779         }
1780
1781         if (!dbus_message_iter_init(reply, &iter) ||
1782             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1783                 log_error("Failed to parse reply.");
1784                 r = -EIO;
1785                 goto finish;
1786         }
1787
1788         dbus_message_iter_recurse(&iter, &sub);
1789
1790         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)  {
1791                 log_error("Failed to parse reply.");
1792                 r = -EIO;
1793                 goto finish;
1794         }
1795
1796         dbus_message_iter_get_basic(&sub, &id);
1797
1798         if (!arg_quiet)
1799                 puts(id);
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 delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
1815         DBusMessage *m = NULL, *reply = NULL;
1816         int r;
1817         DBusError error;
1818         unsigned i;
1819
1820         assert(bus);
1821         assert(args);
1822
1823         dbus_error_init(&error);
1824
1825         for (i = 1; i < n; i++) {
1826                 const char *path = NULL;
1827
1828                 if (!(m = dbus_message_new_method_call(
1829                                       "org.freedesktop.systemd1",
1830                                       "/org/freedesktop/systemd1",
1831                                       "org.freedesktop.systemd1.Manager",
1832                                       "GetUnit"))) {
1833                         log_error("Could not allocate message.");
1834                         r = -ENOMEM;
1835                         goto finish;
1836                 }
1837
1838                 if (!dbus_message_append_args(m,
1839                                               DBUS_TYPE_STRING, &args[i],
1840                                               DBUS_TYPE_INVALID)) {
1841                         log_error("Could not append arguments to message.");
1842                         r = -ENOMEM;
1843                         goto finish;
1844                 }
1845
1846                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1847                         log_error("Failed to issue method call: %s", error.message);
1848                         r = -EIO;
1849                         goto finish;
1850                 }
1851
1852                 if (!dbus_message_get_args(reply, &error,
1853                                            DBUS_TYPE_OBJECT_PATH, &path,
1854                                            DBUS_TYPE_INVALID)) {
1855                         log_error("Failed to parse reply: %s", error.message);
1856                         r = -EIO;
1857                         goto finish;
1858                 }
1859
1860                 dbus_message_unref(m);
1861                 if (!(m = dbus_message_new_method_call(
1862                                       "org.freedesktop.systemd1",
1863                                       path,
1864                                       "org.freedesktop.systemd1.Snapshot",
1865                                       "Remove"))) {
1866                         log_error("Could not allocate message.");
1867                         r = -ENOMEM;
1868                         goto finish;
1869                 }
1870
1871                 dbus_message_unref(reply);
1872                 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1873                         log_error("Failed to issue method call: %s", error.message);
1874                         r = -EIO;
1875                         goto finish;
1876                 }
1877
1878                 dbus_message_unref(m);
1879                 dbus_message_unref(reply);
1880                 m = reply = NULL;
1881         }
1882
1883         r = 0;
1884
1885 finish:
1886         if (m)
1887                 dbus_message_unref(m);
1888
1889         if (reply)
1890                 dbus_message_unref(reply);
1891
1892         dbus_error_free(&error);
1893
1894         return r;
1895 }
1896
1897 static int clear_jobs(DBusConnection *bus, char **args, unsigned n) {
1898         DBusMessage *m = NULL, *reply = NULL;
1899         DBusError error;
1900         int r;
1901         const char *method;
1902
1903         dbus_error_init(&error);
1904
1905         if (arg_action == ACTION_RELOAD)
1906                 method = "Reload";
1907         else if (arg_action == ACTION_REEXEC)
1908                 method = "Reexecute";
1909         else {
1910                 assert(arg_action == ACTION_SYSTEMCTL);
1911
1912                 method =
1913                         streq(args[0], "clear-jobs")    ? "ClearJobs" :
1914                         streq(args[0], "daemon-reload") ? "Reload" :
1915                         streq(args[0], "daemon-reexec") ? "Reexecute" :
1916                                                           "Exit";
1917         }
1918
1919         if (!(m = dbus_message_new_method_call(
1920                               "org.freedesktop.systemd1",
1921                               "/org/freedesktop/systemd1",
1922                               "org.freedesktop.systemd1.Manager",
1923                               method))) {
1924                 log_error("Could not allocate message.");
1925                 return -ENOMEM;
1926         }
1927
1928         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1929
1930                 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
1931                         /* There's always a fallback possible for
1932                          * legacy actions. */
1933                         r = 0;
1934                         goto finish;
1935                 }
1936
1937                 log_error("Failed to issue method call: %s", error.message);
1938                 r = -EIO;
1939                 goto finish;
1940         }
1941
1942         r = 1;
1943
1944 finish:
1945         if (m)
1946                 dbus_message_unref(m);
1947
1948         if (reply)
1949                 dbus_message_unref(reply);
1950
1951         dbus_error_free(&error);
1952
1953         return r;
1954 }
1955
1956 static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
1957         DBusMessage *m = NULL, *reply = NULL;
1958         DBusError error;
1959         DBusMessageIter iter, sub, sub2;
1960         int r;
1961         const char
1962                 *interface = "org.freedesktop.systemd1.Manager",
1963                 *property = "Environment";
1964
1965         dbus_error_init(&error);
1966
1967         if (!(m = dbus_message_new_method_call(
1968                               "org.freedesktop.systemd1",
1969                               "/org/freedesktop/systemd1",
1970                               "org.freedesktop.DBus.Properties",
1971                               "Get"))) {
1972                 log_error("Could not allocate message.");
1973                 return -ENOMEM;
1974         }
1975
1976         if (!dbus_message_append_args(m,
1977                                       DBUS_TYPE_STRING, &interface,
1978                                       DBUS_TYPE_STRING, &property,
1979                                       DBUS_TYPE_INVALID)) {
1980                 log_error("Could not append arguments to message.");
1981                 r = -ENOMEM;
1982                 goto finish;
1983         }
1984
1985         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1986                 log_error("Failed to issue method call: %s", error.message);
1987                 r = -EIO;
1988                 goto finish;
1989         }
1990
1991         if (!dbus_message_iter_init(reply, &iter) ||
1992             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)  {
1993                 log_error("Failed to parse reply.");
1994                 r = -EIO;
1995                 goto finish;
1996         }
1997
1998         dbus_message_iter_recurse(&iter, &sub);
1999
2000         if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
2001             dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING)  {
2002                 log_error("Failed to parse reply.");
2003                 r = -EIO;
2004                 goto finish;
2005         }
2006
2007         dbus_message_iter_recurse(&sub, &sub2);
2008
2009         while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
2010                 const char *text;
2011
2012                 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
2013                         log_error("Failed to parse reply.");
2014                         r = -EIO;
2015                         goto finish;
2016                 }
2017
2018                 dbus_message_iter_get_basic(&sub2, &text);
2019                 printf("%s\n", text);
2020
2021                 dbus_message_iter_next(&sub2);
2022         }
2023
2024         r = 0;
2025
2026 finish:
2027         if (m)
2028                 dbus_message_unref(m);
2029
2030         if (reply)
2031                 dbus_message_unref(reply);
2032
2033         dbus_error_free(&error);
2034
2035         return r;
2036 }
2037
2038 static int set_environment(DBusConnection *bus, char **args, unsigned n) {
2039         DBusMessage *m = NULL, *reply = NULL;
2040         DBusError error;
2041         int r;
2042         const char *method;
2043         DBusMessageIter iter, sub;
2044         unsigned i;
2045
2046         dbus_error_init(&error);
2047
2048         method = streq(args[0], "set-environment")
2049                 ? "SetEnvironment"
2050                 : "UnsetEnvironment";
2051
2052         if (!(m = dbus_message_new_method_call(
2053                               "org.freedesktop.systemd1",
2054                               "/org/freedesktop/systemd1",
2055                               "org.freedesktop.systemd1.Manager",
2056                               method))) {
2057
2058                 log_error("Could not allocate message.");
2059                 return -ENOMEM;
2060         }
2061
2062         dbus_message_iter_init_append(m, &iter);
2063
2064         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
2065                 log_error("Could not append arguments to message.");
2066                 r = -ENOMEM;
2067                 goto finish;
2068         }
2069
2070         for (i = 1; i < n; i++)
2071                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
2072                         log_error("Could not append arguments to message.");
2073                         r = -ENOMEM;
2074                         goto finish;
2075                 }
2076
2077         if (!dbus_message_iter_close_container(&iter, &sub)) {
2078                 log_error("Could not append arguments to message.");
2079                 r = -ENOMEM;
2080                 goto finish;
2081         }
2082
2083         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2084                 log_error("Failed to issue method call: %s", error.message);
2085                 r = -EIO;
2086                 goto finish;
2087         }
2088
2089         r = 0;
2090
2091 finish:
2092         if (m)
2093                 dbus_message_unref(m);
2094
2095         if (reply)
2096                 dbus_message_unref(reply);
2097
2098         dbus_error_free(&error);
2099
2100         return r;
2101 }
2102
2103 static int systemctl_help(void) {
2104
2105         printf("%s [OPTIONS...] {COMMAND} ...\n\n"
2106                "Send control commands to the systemd manager.\n\n"
2107                "  -h --help          Show this help\n"
2108                "  -t --type=TYPE     List only units of a particular type\n"
2109                "  -p --property=NAME Show only properties by this name\n"
2110                "  -a --all           Show all units/properties, including dead/empty ones\n"
2111                "     --replace       When installing a new job, replace existing conflicting ones\n"
2112                "     --system        Connect to system bus\n"
2113                "     --session       Connect to session bus\n"
2114                "  -q --quiet         Suppress output\n"
2115                "     --no-block      Do not wait until operation finished\n"
2116                "     --no-wall       Don't send wall message before halt/power-off/reboot\n\n"
2117                "Commands:\n"
2118                "  list-units                      List units\n"
2119                "  start [NAME...]                 Start one or more units\n"
2120                "  stop [NAME...]                  Stop one or more units\n"
2121                "  restart [NAME...]               Restart one or more units\n"
2122                "  reload [NAME...]                Reload one or more units\n"
2123                "  isolate [NAME]                  Start one unit and stop all others\n"
2124                "  check [NAME...]                 Check whether any of the passed units are active\n"
2125                "  show [NAME...|JOB...]           Show information about one or more units/jobs/manager\n"
2126                "  load [NAME...]                  Load one or more units\n"
2127                "  list-jobs                       List jobs\n"
2128                "  cancel [JOB...]                 Cancel one or more jobs\n"
2129                "  clear-jobs                      Cancel all jobs\n"
2130                "  monitor                         Monitor unit/job changes\n"
2131                "  dump                            Dump server status\n"
2132                "  snapshot [NAME]                 Create a snapshot\n"
2133                "  delete [NAME...]                Remove one or more snapshots\n"
2134                "  daemon-reload                   Reload systemd manager configuration\n"
2135                "  daemon-reexec                   Reexecute systemd manager\n"
2136                "  daemon-exit                     Ask the systemd manager to quit\n"
2137                "  show-environment                Dump environment\n"
2138                "  set-environment [NAME=VALUE...] Set one or more environment variables\n"
2139                "  unset-environment [NAME...]     Unset one or more environment variables\n"
2140                "  halt                            Shut down and halt the system\n"
2141                "  poweroff                        Shut down and power-off the system\n"
2142                "  reboot                          Shut down and reboot the system\n"
2143                "  default                         Enter default mode\n"
2144                "  rescue                          Enter rescue mode\n"
2145                "  emergency                       Enter emergency mode\n",
2146                program_invocation_short_name);
2147
2148         return 0;
2149 }
2150
2151 static int halt_help(void) {
2152
2153         printf("%s [OPTIONS...]\n\n"
2154                "%s the system.\n\n"
2155                "     --help      Show this help\n"
2156                "     --halt      Halt the machine\n"
2157                "  -p --poweroff  Switch off the machine\n"
2158                "     --reboot    Reboot the machine\n"
2159                "  -f --force     Force immediate halt/power-off/reboot\n"
2160                "  -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
2161                "  -d --no-wtmp   Don't write wtmp record\n"
2162                "  -n --no-sync   Don't sync before halt/power-off/reboot\n"
2163                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
2164                program_invocation_short_name,
2165                arg_action == ACTION_REBOOT   ? "Reboot" :
2166                arg_action == ACTION_POWEROFF ? "Power off" :
2167                                                "Halt");
2168
2169         return 0;
2170 }
2171
2172 static int shutdown_help(void) {
2173
2174         printf("%s [OPTIONS...] [now] [WALL...]\n\n"
2175                "Shut down the system.\n\n"
2176                "     --help      Show this help\n"
2177                "  -H --halt      Halt the machine\n"
2178                "  -P --poweroff  Power-off the machine\n"
2179                "  -r --reboot    Reboot the machine\n"
2180                "  -h             Equivalent to --poweroff, overriden by --halt\n"
2181                "  -k             Don't halt/power-off/reboot, just send warnings\n"
2182                "     --no-wall   Don't send wall message before halt/power-off/reboot\n",
2183                program_invocation_short_name);
2184
2185         return 0;
2186 }
2187
2188 static int telinit_help(void) {
2189
2190         printf("%s [OPTIONS...] {COMMAND}\n\n"
2191                "Send control commands to the init daemon.\n\n"
2192                "     --help      Show this help\n"
2193                "     --no-wall   Don't send wall message before halt/power-off/reboot\n\n"
2194                "Commands:\n"
2195                "  0              Power-off the machine\n"
2196                "  6              Reboot the machine\n"
2197                "  2, 3, 4, 5     Start runlevelX.target unit\n"
2198                "  1, s, S        Enter rescue mode\n"
2199                "  q, Q           Reload init daemon configuration\n"
2200                "  u, U           Reexecute init daemon\n",
2201                program_invocation_short_name);
2202
2203         return 0;
2204 }
2205
2206 static int runlevel_help(void) {
2207
2208         printf("%s [OPTIONS...]\n\n"
2209                "Prints the previous and current runlevel of the init system.\n\n"
2210                "     --help      Show this help\n",
2211                program_invocation_short_name);
2212
2213         return 0;
2214 }
2215
2216 static int systemctl_parse_argv(int argc, char *argv[]) {
2217
2218         enum {
2219                 ARG_REPLACE = 0x100,
2220                 ARG_SESSION,
2221                 ARG_SYSTEM,
2222                 ARG_NO_BLOCK,
2223                 ARG_NO_WALL
2224         };
2225
2226         static const struct option options[] = {
2227                 { "help",      no_argument,       NULL, 'h'          },
2228                 { "type",      required_argument, NULL, 't'          },
2229                 { "property",  required_argument, NULL, 'p'          },
2230                 { "all",       no_argument,       NULL, 'a'          },
2231                 { "replace",   no_argument,       NULL, ARG_REPLACE  },
2232                 { "session",   no_argument,       NULL, ARG_SESSION  },
2233                 { "system",    no_argument,       NULL, ARG_SYSTEM   },
2234                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK },
2235                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL  },
2236                 { "quiet",     no_argument,       NULL, 'q'          },
2237                 { NULL,        0,                 NULL, 0            }
2238         };
2239
2240         int c;
2241
2242         assert(argc >= 0);
2243         assert(argv);
2244
2245         while ((c = getopt_long(argc, argv, "ht:p:aq", options, NULL)) >= 0) {
2246
2247                 switch (c) {
2248
2249                 case 'h':
2250                         systemctl_help();
2251                         return 0;
2252
2253                 case 't':
2254                         arg_type = optarg;
2255                         break;
2256
2257                 case 'p':
2258                         arg_property = optarg;
2259
2260                         /* If the user asked for a particular
2261                          * property, show it to him, even if it is
2262                          * empty. */
2263                         arg_all = true;
2264                         break;
2265
2266                 case 'a':
2267                         arg_all = true;
2268                         break;
2269
2270                 case ARG_REPLACE:
2271                         arg_replace = true;
2272                         break;
2273
2274                 case ARG_SESSION:
2275                         arg_session = true;
2276                         break;
2277
2278                 case ARG_SYSTEM:
2279                         arg_session = false;
2280                         break;
2281
2282                 case ARG_NO_BLOCK:
2283                         arg_no_block = true;
2284                         break;
2285
2286                 case ARG_NO_WALL:
2287                         arg_no_wall = true;
2288                         break;
2289
2290                 case 'q':
2291                         arg_quiet = true;
2292                         break;
2293
2294                 case '?':
2295                         return -EINVAL;
2296
2297                 default:
2298                         log_error("Unknown option code %c", c);
2299                         return -EINVAL;
2300                 }
2301         }
2302
2303         return 1;
2304 }
2305
2306 static int halt_parse_argv(int argc, char *argv[]) {
2307
2308         enum {
2309                 ARG_HELP = 0x100,
2310                 ARG_HALT,
2311                 ARG_REBOOT,
2312                 ARG_NO_WALL
2313         };
2314
2315         static const struct option options[] = {
2316                 { "help",      no_argument,       NULL, ARG_HELP    },
2317                 { "halt",      no_argument,       NULL, ARG_HALT    },
2318                 { "poweroff",  no_argument,       NULL, 'p'         },
2319                 { "reboot",    no_argument,       NULL, ARG_REBOOT  },
2320                 { "force",     no_argument,       NULL, 'f'         },
2321                 { "wtmp-only", no_argument,       NULL, 'w'         },
2322                 { "no-wtmp",   no_argument,       NULL, 'd'         },
2323                 { "no-sync",   no_argument,       NULL, 'n'         },
2324                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
2325                 { NULL,        0,                 NULL, 0           }
2326         };
2327
2328         int c, runlevel;
2329
2330         assert(argc >= 0);
2331         assert(argv);
2332
2333         if (utmp_get_runlevel(&runlevel, NULL) >= 0)
2334                 if (runlevel == '0' || runlevel == '6')
2335                         arg_immediate = true;
2336
2337         while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
2338                 switch (c) {
2339
2340                 case ARG_HELP:
2341                         halt_help();
2342                         return 0;
2343
2344                 case ARG_HALT:
2345                         arg_action = ACTION_HALT;
2346                         break;
2347
2348                 case 'p':
2349                         arg_action = ACTION_POWEROFF;
2350                         break;
2351
2352                 case ARG_REBOOT:
2353                         arg_action = ACTION_REBOOT;
2354                         break;
2355
2356                 case 'f':
2357                         arg_immediate = true;
2358                         break;
2359
2360                 case 'w':
2361                         arg_dry = true;
2362                         break;
2363
2364                 case 'd':
2365                         arg_no_wtmp = true;
2366                         break;
2367
2368                 case 'n':
2369                         arg_no_sync = true;
2370                         break;
2371
2372                 case ARG_NO_WALL:
2373                         arg_no_wall = true;
2374                         break;
2375
2376                 case 'i':
2377                 case 'h':
2378                         /* Compatibility nops */
2379                         break;
2380
2381                 case '?':
2382                         return -EINVAL;
2383
2384                 default:
2385                         log_error("Unknown option code %c", c);
2386                         return -EINVAL;
2387                 }
2388         }
2389
2390         if (optind < argc) {
2391                 log_error("Too many arguments.");
2392                 return -EINVAL;
2393         }
2394
2395         return 1;
2396 }
2397
2398 static int shutdown_parse_argv(int argc, char *argv[]) {
2399
2400         enum {
2401                 ARG_HELP = 0x100,
2402                 ARG_NO_WALL
2403         };
2404
2405         static const struct option options[] = {
2406                 { "help",      no_argument,       NULL, ARG_HELP    },
2407                 { "halt",      no_argument,       NULL, 'H'         },
2408                 { "poweroff",  no_argument,       NULL, 'P'         },
2409                 { "reboot",    no_argument,       NULL, 'r'         },
2410                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
2411                 { NULL,        0,                 NULL, 0           }
2412         };
2413
2414         int c;
2415
2416         assert(argc >= 0);
2417         assert(argv);
2418
2419         while ((c = getopt_long(argc, argv, "HPrhkt:a", options, NULL)) >= 0) {
2420                 switch (c) {
2421
2422                 case ARG_HELP:
2423                         shutdown_help();
2424                         return 0;
2425
2426                 case 'H':
2427                         arg_action = ACTION_HALT;
2428                         break;
2429
2430                 case 'P':
2431                         arg_action = ACTION_POWEROFF;
2432                         break;
2433
2434                 case 'r':
2435                         arg_action = ACTION_REBOOT;
2436                         break;
2437
2438                 case 'h':
2439                         if (arg_action != ACTION_HALT)
2440                                 arg_action = ACTION_POWEROFF;
2441                         break;
2442
2443                 case 'k':
2444                         arg_dry = true;
2445                         break;
2446
2447                 case ARG_NO_WALL:
2448                         arg_no_wall = true;
2449                         break;
2450
2451                 case 't':
2452                 case 'a':
2453                         /* Compatibility nops */
2454                         break;
2455
2456                 case '?':
2457                         return -EINVAL;
2458
2459                 default:
2460                         log_error("Unknown option code %c", c);
2461                         return -EINVAL;
2462                 }
2463         }
2464
2465         if (argc > optind && !streq(argv[optind], "now"))
2466                 log_warning("First argument '%s' isn't 'now'. Ignoring.", argv[optind]);
2467
2468         /* We ignore the time argument */
2469         if (argc > optind + 1)
2470                 arg_wall = argv + optind + 1;
2471
2472         optind = argc;
2473
2474         return 1;
2475 }
2476
2477 static int telinit_parse_argv(int argc, char *argv[]) {
2478
2479         enum {
2480                 ARG_HELP = 0x100,
2481                 ARG_NO_WALL
2482         };
2483
2484         static const struct option options[] = {
2485                 { "help",      no_argument,       NULL, ARG_HELP    },
2486                 { "no-wall",   no_argument,       NULL, ARG_NO_WALL },
2487                 { NULL,        0,                 NULL, 0           }
2488         };
2489
2490         static const struct {
2491                 char from;
2492                 enum action to;
2493         } table[] = {
2494                 { '0', ACTION_POWEROFF },
2495                 { '6', ACTION_REBOOT },
2496                 { '1', ACTION_RESCUE },
2497                 { '2', ACTION_RUNLEVEL2 },
2498                 { '3', ACTION_RUNLEVEL3 },
2499                 { '4', ACTION_RUNLEVEL4 },
2500                 { '5', ACTION_RUNLEVEL5 },
2501                 { 's', ACTION_RESCUE },
2502                 { 'S', ACTION_RESCUE },
2503                 { 'q', ACTION_RELOAD },
2504                 { 'Q', ACTION_RELOAD },
2505                 { 'u', ACTION_REEXEC },
2506                 { 'U', ACTION_REEXEC }
2507         };
2508
2509         unsigned i;
2510         int c;
2511
2512         assert(argc >= 0);
2513         assert(argv);
2514
2515         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
2516                 switch (c) {
2517
2518                 case ARG_HELP:
2519                         telinit_help();
2520                         return 0;
2521
2522                 case ARG_NO_WALL:
2523                         arg_no_wall = true;
2524                         break;
2525
2526                 case '?':
2527                         return -EINVAL;
2528
2529                 default:
2530                         log_error("Unknown option code %c", c);
2531                         return -EINVAL;
2532                 }
2533         }
2534
2535         if (optind >= argc) {
2536                 telinit_help();
2537                 return -EINVAL;
2538         }
2539
2540         if (optind + 1 < argc) {
2541                 log_error("Too many arguments.");
2542                 return -EINVAL;
2543         }
2544
2545         if (strlen(argv[optind]) != 1) {
2546                 log_error("Expected single character argument.");
2547                 return -EINVAL;
2548         }
2549
2550         for (i = 0; i < ELEMENTSOF(table); i++)
2551                 if (table[i].from == argv[optind][0])
2552                         break;
2553
2554         if (i >= ELEMENTSOF(table)) {
2555                 log_error("Unknown command %s.", argv[optind]);
2556                 return -EINVAL;
2557         }
2558
2559         arg_action = table[i].to;
2560
2561         optind ++;
2562
2563         return 1;
2564 }
2565
2566 static int runlevel_parse_argv(int argc, char *argv[]) {
2567
2568         enum {
2569                 ARG_HELP = 0x100,
2570         };
2571
2572         static const struct option options[] = {
2573                 { "help",      no_argument,       NULL, ARG_HELP    },
2574                 { NULL,        0,                 NULL, 0           }
2575         };
2576
2577         int c;
2578
2579         assert(argc >= 0);
2580         assert(argv);
2581
2582         while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
2583                 switch (c) {
2584
2585                 case ARG_HELP:
2586                         runlevel_help();
2587                         return 0;
2588
2589                 case '?':
2590                         return -EINVAL;
2591
2592                 default:
2593                         log_error("Unknown option code %c", c);
2594                         return -EINVAL;
2595                 }
2596         }
2597
2598         if (optind < argc) {
2599                 log_error("Too many arguments.");
2600                 return -EINVAL;
2601         }
2602
2603         return 1;
2604 }
2605
2606 static int parse_argv(int argc, char *argv[]) {
2607         assert(argc >= 0);
2608         assert(argv);
2609
2610         if (program_invocation_short_name) {
2611
2612                 if (strstr(program_invocation_short_name, "halt")) {
2613                         arg_action = ACTION_HALT;
2614                         return halt_parse_argv(argc, argv);
2615                 } else if (strstr(program_invocation_short_name, "poweroff")) {
2616                         arg_action = ACTION_POWEROFF;
2617                         return halt_parse_argv(argc, argv);
2618                 } else if (strstr(program_invocation_short_name, "reboot")) {
2619                         arg_action = ACTION_REBOOT;
2620                         return halt_parse_argv(argc, argv);
2621                 } else if (strstr(program_invocation_short_name, "shutdown")) {
2622                         arg_action = ACTION_POWEROFF;
2623                         return shutdown_parse_argv(argc, argv);
2624                 } else if (strstr(program_invocation_short_name, "init")) {
2625                         arg_action = ACTION_INVALID;
2626                         return telinit_parse_argv(argc, argv);
2627                 } else if (strstr(program_invocation_short_name, "runlevel")) {
2628                         arg_action = ACTION_RUNLEVEL;
2629                         return runlevel_parse_argv(argc, argv);
2630                 }
2631         }
2632
2633         arg_action = ACTION_SYSTEMCTL;
2634         return systemctl_parse_argv(argc, argv);
2635 }
2636
2637 static int action_to_runlevel(void) {
2638
2639         static const char table[_ACTION_MAX] = {
2640                 [ACTION_HALT] =      '0',
2641                 [ACTION_POWEROFF] =  '0',
2642                 [ACTION_REBOOT] =    '6',
2643                 [ACTION_RUNLEVEL2] = '2',
2644                 [ACTION_RUNLEVEL3] = '3',
2645                 [ACTION_RUNLEVEL4] = '4',
2646                 [ACTION_RUNLEVEL5] = '5',
2647                 [ACTION_RESCUE] =    '1'
2648         };
2649
2650         assert(arg_action < _ACTION_MAX);
2651
2652         return table[arg_action];
2653 }
2654
2655 static int talk_upstart(void) {
2656         DBusMessage *m = NULL, *reply = NULL;
2657         DBusError error;
2658         int previous, rl, r;
2659         char
2660                 env1_buf[] = "RUNLEVEL=X",
2661                 env2_buf[] = "PREVLEVEL=X";
2662         char *env1 = env1_buf, *env2 = env2_buf;
2663         const char *emit = "runlevel";
2664         dbus_bool_t b_false = FALSE;
2665         DBusMessageIter iter, sub;
2666         DBusConnection *bus;
2667
2668         dbus_error_init(&error);
2669
2670         if (!(rl = action_to_runlevel()))
2671                 return 0;
2672
2673         if (utmp_get_runlevel(&previous, NULL) < 0)
2674                 previous = 'N';
2675
2676         if (!(bus = dbus_connection_open("unix:abstract=/com/ubuntu/upstart", &error))) {
2677                 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
2678                         r = 0;
2679                         goto finish;
2680                 }
2681
2682                 log_error("Failed to connect to Upstart bus: %s", error.message);
2683                 r = -EIO;
2684                 goto finish;
2685         }
2686
2687         if ((r = bus_check_peercred(bus)) < 0) {
2688                 log_error("Failed to verify owner of bus.");
2689                 goto finish;
2690         }
2691
2692         if (!(m = dbus_message_new_method_call(
2693                               "com.ubuntu.Upstart",
2694                               "/com/ubuntu/Upstart",
2695                               "com.ubuntu.Upstart0_6",
2696                               "EmitEvent"))) {
2697
2698                 log_error("Could not allocate message.");
2699                 r = -ENOMEM;
2700                 goto finish;
2701         }
2702
2703         dbus_message_iter_init_append(m, &iter);
2704
2705         env1_buf[sizeof(env1_buf)-2] = rl;
2706         env2_buf[sizeof(env2_buf)-2] = previous;
2707
2708         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
2709             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
2710             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
2711             !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
2712             !dbus_message_iter_close_container(&iter, &sub) ||
2713             !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
2714                 log_error("Could not append arguments to message.");
2715                 r = -ENOMEM;
2716                 goto finish;
2717         }
2718
2719         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2720
2721                 if (error_is_no_service(&error)) {
2722                         r = 0;
2723                         goto finish;
2724                 }
2725
2726                 log_error("Failed to issue method call: %s", error.message);
2727                 r = -EIO;
2728                 goto finish;
2729         }
2730
2731         r = 1;
2732
2733 finish:
2734         if (m)
2735                 dbus_message_unref(m);
2736
2737         if (reply)
2738                 dbus_message_unref(reply);
2739
2740         if (bus)
2741                 dbus_connection_unref(bus);
2742
2743         dbus_error_free(&error);
2744
2745         return r;
2746 }
2747
2748 static int talk_initctl(void) {
2749         struct init_request request;
2750         int r, fd;
2751         char rl;
2752
2753         if (!(rl = action_to_runlevel()))
2754                 return 0;
2755
2756         zero(request);
2757         request.magic = INIT_MAGIC;
2758         request.sleeptime = 0;
2759         request.cmd = INIT_CMD_RUNLVL;
2760         request.runlevel = rl;
2761
2762         if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
2763
2764                 if (errno == ENOENT)
2765                         return 0;
2766
2767                 log_error("Failed to open "INIT_FIFO": %m");
2768                 return -errno;
2769         }
2770
2771         errno = 0;
2772         r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
2773         close_nointr_nofail(fd);
2774
2775         if (r < 0) {
2776                 log_error("Failed to write to "INIT_FIFO": %m");
2777                 return errno ? -errno : -EIO;
2778         }
2779
2780         return 1;
2781 }
2782
2783 static int systemctl_main(DBusConnection *bus, int argc, char *argv[]) {
2784
2785         static const struct {
2786                 const char* verb;
2787                 const enum {
2788                         MORE,
2789                         LESS,
2790                         EQUAL
2791                 } argc_cmp;
2792                 const int argc;
2793                 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
2794         } verbs[] = {
2795                 { "list-units",        LESS,  1, list_units      },
2796                 { "list-jobs",         EQUAL, 1, list_jobs       },
2797                 { "clear-jobs",        EQUAL, 1, clear_jobs      },
2798                 { "load",              MORE,  2, load_unit       },
2799                 { "cancel",            MORE,  2, cancel_job      },
2800                 { "start",             MORE,  2, start_unit      },
2801                 { "stop",              MORE,  2, start_unit      },
2802                 { "reload",            MORE,  2, start_unit      },
2803                 { "restart",           MORE,  2, start_unit      },
2804                 { "isolate",           EQUAL, 2, start_unit      },
2805                 { "check",             MORE,  2, check_unit      },
2806                 { "show",              MORE,  1, show            },
2807                 { "monitor",           EQUAL, 1, monitor         },
2808                 { "dump",              EQUAL, 1, dump            },
2809                 { "snapshot",          LESS,  2, snapshot        },
2810                 { "delete",            MORE,  2, delete_snapshot },
2811                 { "daemon-reload",     EQUAL, 1, clear_jobs      },
2812                 { "daemon-reexec",     EQUAL, 1, clear_jobs      },
2813                 { "daemon-exit",       EQUAL, 1, clear_jobs      },
2814                 { "show-environment",  EQUAL, 1, show_enviroment },
2815                 { "set-environment",   MORE,  2, set_environment },
2816                 { "unset-environment", MORE,  2, set_environment },
2817                 { "halt",              EQUAL, 1, start_special   },
2818                 { "poweroff",          EQUAL, 1, start_special   },
2819                 { "reboot",            EQUAL, 1, start_special   },
2820                 { "default",           EQUAL, 1, start_special   },
2821                 { "rescue",            EQUAL, 1, start_special   },
2822                 { "emergency",         EQUAL, 1, start_special   },
2823         };
2824
2825         int left;
2826         unsigned i;
2827
2828         assert(bus);
2829         assert(argc >= 0);
2830         assert(argv);
2831
2832         left = argc - optind;
2833
2834         if (left <= 0)
2835                 /* Special rule: no arguments means "list-units" */
2836                 i = 0;
2837         else {
2838                 if (streq(argv[optind], "help")) {
2839                         systemctl_help();
2840                         return 0;
2841                 }
2842
2843                 for (i = 0; i < ELEMENTSOF(verbs); i++)
2844                         if (streq(argv[optind], verbs[i].verb))
2845                                 break;
2846
2847                 if (i >= ELEMENTSOF(verbs)) {
2848                         log_error("Unknown operation %s", argv[optind]);
2849                         return -EINVAL;
2850                 }
2851         }
2852
2853         switch (verbs[i].argc_cmp) {
2854
2855         case EQUAL:
2856                 if (left != verbs[i].argc) {
2857                         log_error("Invalid number of arguments.");
2858                         return -EINVAL;
2859                 }
2860
2861                 break;
2862
2863         case MORE:
2864                 if (left < verbs[i].argc) {
2865                         log_error("Too few arguments.");
2866                         return -EINVAL;
2867                 }
2868
2869                 break;
2870
2871         case LESS:
2872                 if (left > verbs[i].argc) {
2873                         log_error("Too many arguments.");
2874                         return -EINVAL;
2875                 }
2876
2877                 break;
2878
2879         default:
2880                 assert_not_reached("Unknown comparison operator.");
2881         }
2882
2883         return verbs[i].dispatch(bus, argv + optind, left);
2884 }
2885
2886 static int reload_with_fallback(DBusConnection *bus) {
2887         int r;
2888
2889         if (bus) {
2890                 /* First, try systemd via D-Bus. */
2891                 if ((r = clear_jobs(bus, NULL, 0)) > 0)
2892                         return 0;
2893         }
2894
2895         /* Nothing else worked, so let's try signals */
2896         assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
2897
2898         if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
2899                 log_error("kill() failed: %m");
2900                 return -errno;
2901         }
2902
2903         return 0;
2904 }
2905
2906 static int start_with_fallback(DBusConnection *bus) {
2907         int r;
2908
2909         warn_wall(arg_action);
2910
2911         if (bus) {
2912                 /* First, try systemd via D-Bus. */
2913                 if ((r = start_unit(bus, NULL, 0)) > 0)
2914                         return 0;
2915
2916                 /* Hmm, talking to systemd via D-Bus didn't work. Then
2917                  * let's try to talk to Upstart via D-Bus. */
2918                 if ((r = talk_upstart()) > 0)
2919                         return 0;
2920         }
2921
2922         /* Nothing else worked, so let's try
2923          * /dev/initctl */
2924         if ((r = talk_initctl()) != 0)
2925                 return 0;
2926
2927         log_error("Failed to talk to init daemon.");
2928         return -EIO;
2929 }
2930
2931 static int halt_main(DBusConnection *bus) {
2932         int r;
2933
2934         if (!arg_immediate)
2935                 return start_with_fallback(bus);
2936
2937         if (!arg_no_wtmp)
2938                 if ((r = utmp_put_shutdown(0)) < 0)
2939                         log_warning("Failed to write utmp record: %s", strerror(-r));
2940
2941         if (!arg_no_sync)
2942                 sync();
2943
2944         if (arg_dry)
2945                 return 0;
2946
2947         /* Make sure C-A-D is handled by the kernel from this
2948          * point on... */
2949         reboot(RB_ENABLE_CAD);
2950
2951         switch (arg_action) {
2952
2953         case ACTION_HALT:
2954                 log_info("Halting");
2955                 reboot(RB_HALT_SYSTEM);
2956                 break;
2957
2958         case ACTION_POWEROFF:
2959                 log_info("Powering off");
2960                 reboot(RB_POWER_OFF);
2961                 break;
2962
2963         case ACTION_REBOOT:
2964                 log_info("Rebooting");
2965                 reboot(RB_AUTOBOOT);
2966                 break;
2967
2968         default:
2969                 assert_not_reached("Unknown halt action.");
2970         }
2971
2972         /* We should never reach this. */
2973         return -ENOSYS;
2974 }
2975
2976 static int runlevel_main(void) {
2977         int r, runlevel, previous;
2978
2979         if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
2980                 printf("unknown");
2981                 return r;
2982         }
2983
2984         printf("%c %c\n",
2985                previous <= 0 ? 'N' : previous,
2986                runlevel <= 0 ? 'N' : runlevel);
2987
2988         return 0;
2989 }
2990
2991 int main(int argc, char*argv[]) {
2992         int r, retval = 1;
2993         DBusConnection *bus = NULL;
2994         DBusError error;
2995
2996         dbus_error_init(&error);
2997
2998         log_parse_environment();
2999
3000         if ((r = parse_argv(argc, argv)) < 0)
3001                 goto finish;
3002         else if (r == 0) {
3003                 retval = 0;
3004                 goto finish;
3005         }
3006
3007         /* /sbin/runlevel doesn't need to communicate via D-Bus, so
3008          * let's shortcut this */
3009         if (arg_action == ACTION_RUNLEVEL) {
3010                 retval = runlevel_main() < 0;
3011                 goto finish;
3012         }
3013
3014         /* If we are root, then let's not go via the bus */
3015         if (geteuid() == 0 && !arg_session) {
3016                 bus = dbus_connection_open("unix:abstract=/org/freedesktop/systemd1/private", &error);
3017
3018                 if (bus && bus_check_peercred(bus) < 0) {
3019                         log_error("Failed to verify owner of bus.");
3020                         goto finish;
3021                 }
3022         } else
3023                 bus = dbus_bus_get(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error);
3024
3025         if (bus)
3026                 dbus_connection_set_exit_on_disconnect(bus, FALSE);
3027
3028         switch (arg_action) {
3029
3030         case ACTION_SYSTEMCTL: {
3031
3032                 if (!bus) {
3033                         log_error("Failed to get D-Bus connection: %s", error.message);
3034                         goto finish;
3035                 }
3036
3037                 retval = systemctl_main(bus, argc, argv) < 0;
3038                 break;
3039         }
3040
3041         case ACTION_HALT:
3042         case ACTION_POWEROFF:
3043         case ACTION_REBOOT:
3044                 retval = halt_main(bus) < 0;
3045                 break;
3046
3047         case ACTION_RUNLEVEL2:
3048         case ACTION_RUNLEVEL3:
3049         case ACTION_RUNLEVEL4:
3050         case ACTION_RUNLEVEL5:
3051         case ACTION_RESCUE:
3052         case ACTION_EMERGENCY:
3053         case ACTION_DEFAULT:
3054                 retval = start_with_fallback(bus) < 0;
3055                 break;
3056
3057         case ACTION_RELOAD:
3058         case ACTION_REEXEC:
3059                 retval = reload_with_fallback(bus) < 0;
3060                 break;
3061
3062         case ACTION_INVALID:
3063         case ACTION_RUNLEVEL:
3064         default:
3065                 assert_not_reached("Unknown action");
3066         }
3067
3068 finish:
3069
3070         if (bus)
3071                 dbus_connection_unref(bus);
3072
3073         dbus_error_free(&error);
3074
3075         dbus_shutdown();
3076
3077         return retval;
3078 }