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