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