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