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