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