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