]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/systemctl.c
dbus: send our finished signal when we are finished booting
[thirdparty/systemd.git] / src / systemctl.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
7e4249b9
LP
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
e4b61340 22#include <sys/reboot.h>
7e4249b9
LP
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>
eb22ac37 31#include <fcntl.h>
f1c5860b 32#include <sys/socket.h>
ee5762e3 33#include <sys/stat.h>
0e098b15 34#include <stddef.h>
501fc174 35#include <sys/prctl.h>
7e4249b9
LP
36
37#include <dbus/dbus.h>
38
39#include "log.h"
40#include "util.h"
41#include "macro.h"
42#include "set.h"
e4b61340 43#include "utmp-wtmp.h"
514f4ef5 44#include "special.h"
eb22ac37 45#include "initreq.h"
e4a9373f 46#include "strv.h"
9a1ac7b9 47#include "dbus-common.h"
ab35fb1b 48#include "cgroup-show.h"
c6c18be3 49#include "cgroup-util.h"
582a507f 50#include "list.h"
ee5762e3
LP
51#include "path-lookup.h"
52#include "conf-parser.h"
53#include "sd-daemon.h"
f6144808 54#include "shutdownd.h"
d06dacd0 55#include "exit-status.h"
22f4096c 56#include "bus-errors.h"
7d568925 57#include "build.h"
71fad675 58#include "unit-name.h"
7e4249b9
LP
59
60static const char *arg_type = NULL;
ea4a240d 61static char **arg_property = NULL;
7e4249b9 62static bool arg_all = false;
e67c3609 63static const char *arg_job_mode = "replace";
af2d49f7 64static bool arg_user = false;
ee5762e3 65static bool arg_global = false;
e4b61340 66static bool arg_immediate = false;
ee5762e3 67static bool arg_no_block = false;
0736af98 68static bool arg_no_pager = false;
e4b61340
LP
69static bool arg_no_wtmp = false;
70static bool arg_no_sync = false;
514f4ef5 71static bool arg_no_wall = false;
ee5762e3 72static bool arg_no_reload = false;
e4b61340 73static bool arg_dry = false;
0183528f 74static bool arg_quiet = false;
ee5762e3
LP
75static bool arg_full = false;
76static bool arg_force = false;
77static bool arg_defaults = false;
501fc174 78static bool arg_ask_password = false;
30732560 79static bool arg_failed = false;
e4b61340 80static char **arg_wall = NULL;
8a0867d6
LP
81static const char *arg_kill_who = NULL;
82static const char *arg_kill_mode = NULL;
83static int arg_signal = SIGTERM;
f6144808 84static usec_t arg_when = 0;
4445a875 85static enum action {
e4b61340
LP
86 ACTION_INVALID,
87 ACTION_SYSTEMCTL,
88 ACTION_HALT,
89 ACTION_POWEROFF,
90 ACTION_REBOOT,
20b09ca7
LP
91 ACTION_KEXEC,
92 ACTION_EXIT,
e4b61340
LP
93 ACTION_RUNLEVEL2,
94 ACTION_RUNLEVEL3,
95 ACTION_RUNLEVEL4,
96 ACTION_RUNLEVEL5,
97 ACTION_RESCUE,
514f4ef5
LP
98 ACTION_EMERGENCY,
99 ACTION_DEFAULT,
e4b61340
LP
100 ACTION_RELOAD,
101 ACTION_REEXEC,
102 ACTION_RUNLEVEL,
f6144808 103 ACTION_CANCEL_SHUTDOWN,
e4b61340
LP
104 _ACTION_MAX
105} arg_action = ACTION_SYSTEMCTL;
4445a875
LP
106static enum dot {
107 DOT_ALL,
108 DOT_ORDER,
109 DOT_REQUIRE
110} arg_dot = DOT_ALL;
a8f11321
LP
111static enum transport {
112 TRANSPORT_NORMAL,
113 TRANSPORT_SSH,
114 TRANSPORT_POLKIT
115} arg_transport = TRANSPORT_NORMAL;
116static const char *arg_host = NULL;
e4b61340 117
f4579ce7
LP
118static bool private_bus = false;
119
1888c907 120static pid_t pager_pid = 0;
c0f9c7da 121static pid_t agent_pid = 0;
1888c907 122
ee5762e3 123static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
ec14911e 124static void pager_open(void);
ee5762e3 125
2ee68f72 126static bool on_tty(void) {
2cc59dbf
LP
127 static int t = -1;
128
75d12d57
LP
129 /* Note that this is invoked relatively early, before we start
130 * the pager. That means the value we return reflects whether
131 * we originally were started on a tty, not if we currently
060ed82e 132 * are. But this is intended, since we want colour and so on
75d12d57
LP
133 * when run in our own pager. */
134
2cc59dbf
LP
135 if (_unlikely_(t < 0))
136 t = isatty(STDOUT_FILENO) > 0;
137
2ee68f72
LP
138 return t;
139}
140
501fc174 141static void spawn_ask_password_agent(void) {
c0f9c7da
LP
142 pid_t parent;
143
144 if (agent_pid > 0)
145 return;
501fc174
LP
146
147 /* We check STDIN here, not STDOUT, since this is about input,
148 * not output */
149 if (!isatty(STDIN_FILENO))
150 return;
151
152 if (!arg_ask_password)
153 return;
715554e7
LP
154
155 if (arg_user)
156 return;
501fc174
LP
157
158 parent = getpid();
159
160 /* Spawns a temporary TTY agent, making sure it goes away when
161 * we go away */
162
c0f9c7da 163 if ((agent_pid = fork()) < 0)
501fc174
LP
164 return;
165
c0f9c7da 166 if (agent_pid == 0) {
501fc174 167 /* In the child */
501fc174 168
7f6d6135 169 int fd;
7fc01d33 170 bool stdout_is_tty, stderr_is_tty;
7f6d6135
LP
171
172 /* Make sure the agent goes away when the parent dies */
501fc174
LP
173 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
174 _exit(EXIT_FAILURE);
175
176 /* Check whether our parent died before we were able
177 * to set the death signal */
178 if (getppid() != parent)
179 _exit(EXIT_SUCCESS);
180
7f6d6135
LP
181 /* Don't leak fds to the agent */
182 close_all_fds(NULL, 0);
183
7fc01d33
LP
184 stdout_is_tty = isatty(STDOUT_FILENO);
185 stderr_is_tty = isatty(STDERR_FILENO);
186
187 if (!stdout_is_tty || !stderr_is_tty) {
060ed82e
LP
188 /* Detach from stdout/stderr. and reopen
189 * /dev/tty for them. This is important to
190 * ensure that when systemctl is started via
191 * popen() or a similar call that expects to
192 * read EOF we actually do generate EOF and
193 * not delay this indefinitely by because we
194 * keep an unused copy of stdin around. */
195 if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
196 log_error("Failed to open /dev/tty: %m");
197 _exit(EXIT_FAILURE);
198 }
199
7fc01d33 200 if (!stdout_is_tty)
060ed82e 201 dup2(fd, STDOUT_FILENO);
060ed82e 202
7fc01d33 203 if (!stderr_is_tty)
060ed82e 204 dup2(fd, STDERR_FILENO);
060ed82e
LP
205
206 if (fd > 2)
207 close(fd);
7f6d6135
LP
208 }
209
c0f9c7da
LP
210 execl(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
211
212 log_error("Unable to execute agent: %m");
501fc174
LP
213 _exit(EXIT_FAILURE);
214 }
215}
216
2ee68f72
LP
217static const char *ansi_highlight(bool b) {
218
219 if (!on_tty())
2cc59dbf
LP
220 return "";
221
222 return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
223}
224
2ee68f72
LP
225static const char *ansi_highlight_green(bool b) {
226
227 if (!on_tty())
228 return "";
229
230 return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
231}
232
f73e33d9 233static bool error_is_no_service(const DBusError *error) {
514f4ef5
LP
234 assert(error);
235
e4b61340
LP
236 if (!dbus_error_is_set(error))
237 return false;
238
239 if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
240 return true;
241
242 if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
243 return true;
244
245 return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
246}
7e4249b9 247
22f4096c
LP
248static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
249 assert(error);
250
251 if (!dbus_error_is_set(error))
252 return r;
253
254 if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
255 dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
256 dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
257 dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
258 return EXIT_NOPERMISSION;
259
260 if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
261 return EXIT_NOTINSTALLED;
262
263 if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
264 dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
265 return EXIT_NOTIMPLEMENTED;
266
267 if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
268 return EXIT_NOTCONFIGURED;
269
270 if (r != 0)
271 return r;
272
273 return EXIT_FAILURE;
274}
275
7e4249b9
LP
276static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
277
514f4ef5
LP
278 assert(iter);
279 assert(data);
280
7e4249b9
LP
281 if (dbus_message_iter_get_arg_type(iter) != type)
282 return -EIO;
283
284 dbus_message_iter_get_basic(iter, data);
285
286 if (!dbus_message_iter_next(iter) != !next)
287 return -EIO;
288
289 return 0;
290}
291
514f4ef5 292static void warn_wall(enum action action) {
ef2f1067 293 static const char *table[_ACTION_MAX] = {
514f4ef5
LP
294 [ACTION_HALT] = "The system is going down for system halt NOW!",
295 [ACTION_REBOOT] = "The system is going down for reboot NOW!",
296 [ACTION_POWEROFF] = "The system is going down for power-off NOW!",
20b09ca7 297 [ACTION_KEXEC] = "The system is going down for kexec reboot NOW!",
514f4ef5
LP
298 [ACTION_RESCUE] = "The system is going down to rescue mode NOW!",
299 [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
ef2f1067
LP
300 };
301
514f4ef5
LP
302 if (arg_no_wall)
303 return;
304
e4a9373f
LP
305 if (arg_wall) {
306 char *p;
307
308 if (!(p = strv_join(arg_wall, " "))) {
309 log_error("Failed to join strings.");
310 return;
311 }
312
313 if (*p) {
7af53310 314 utmp_wall(p, NULL);
e4a9373f
LP
315 free(p);
316 return;
317 }
318
319 free(p);
320 }
321
514f4ef5 322 if (!table[action])
ef2f1067
LP
323 return;
324
7af53310 325 utmp_wall(table[action], NULL);
ef2f1067
LP
326}
327
36c32ba2
LP
328struct unit_info {
329 const char *id;
330 const char *description;
331 const char *load_state;
332 const char *active_state;
333 const char *sub_state;
334 const char *following;
335 const char *unit_path;
336 uint32_t job_id;
337 const char *job_type;
338 const char *job_path;
339};
340
341static int compare_unit_info(const void *a, const void *b) {
342 const char *d1, *d2;
343 const struct unit_info *u = a, *v = b;
344
345 d1 = strrchr(u->id, '.');
346 d2 = strrchr(v->id, '.');
347
348 if (d1 && d2) {
349 int r;
350
a2a3a5b9 351 if ((r = strcasecmp(d1, d2)) != 0)
36c32ba2
LP
352 return r;
353 }
354
a2a3a5b9 355 return strcasecmp(u->id, v->id);
36c32ba2
LP
356}
357
30732560 358static bool output_show_unit(const struct unit_info *u) {
33330222 359 const char *dot;
b036fc00 360
30732560
LP
361 if (arg_failed)
362 return streq(u->active_state, "failed");
363
33330222
ZJS
364 return (!arg_type || ((dot = strrchr(u->id, '.')) &&
365 streq(dot+1, arg_type))) &&
366 (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
367}
368
eb68c413 369static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
688c6725 370 unsigned active_len, sub_len, job_len, n_shown = 0;
b036fc00 371 const struct unit_info *u;
33330222 372
b036fc00
LP
373 active_len = sizeof("ACTIVE")-1;
374 sub_len = sizeof("SUB")-1;
375 job_len = sizeof("JOB")-1;
376
377 for (u = unit_infos; u < unit_infos + c; u++) {
30732560 378 if (!output_show_unit(u))
b036fc00
LP
379 continue;
380
381 active_len = MAX(active_len, strlen(u->active_state));
382 sub_len = MAX(sub_len, strlen(u->sub_state));
383 if (u->job_id != 0)
384 job_len = MAX(job_len, strlen(u->job_type));
33330222
ZJS
385 }
386
eb68c413 387 if (on_tty()) {
33330222
ZJS
388 printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
389 active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
964d124e 390 if (columns() >= 80+12 || arg_full || !arg_no_pager)
33330222 391 printf(" %s\n", "DESCRIPTION");
eb68c413 392 else
33330222 393 printf("\n");
eb68c413
ZJS
394 }
395
b036fc00
LP
396 for (u = unit_infos; u < unit_infos + c; u++) {
397 char *e;
398 int a = 0, b = 0;
399 const char *on_loaded, *off_loaded;
400 const char *on_active, *off_active;
401
30732560 402 if (!output_show_unit(u))
b036fc00
LP
403 continue;
404
688c6725
LP
405 n_shown++;
406
00dc5d76
LP
407 if (!streq(u->load_state, "loaded") &&
408 !streq(u->load_state, "banned")) {
b036fc00
LP
409 on_loaded = ansi_highlight(true);
410 off_loaded = ansi_highlight(false);
411 } else
412 on_loaded = off_loaded = "";
413
414 if (streq(u->active_state, "failed")) {
415 on_active = ansi_highlight(true);
416 off_active = ansi_highlight(false);
417 } else
418 on_active = off_active = "";
eb68c413 419
b036fc00 420 e = arg_full ? NULL : ellipsize(u->id, 25, 33);
eb68c413 421
b036fc00
LP
422 printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
423 e ? e : u->id,
424 on_loaded, u->load_state, off_loaded,
425 on_active, active_len, u->active_state,
426 sub_len, u->sub_state, off_active,
427 &a);
eb68c413 428
b036fc00
LP
429 free(e);
430
431 a -= strlen(on_loaded) + strlen(off_loaded);
432 a -= strlen(on_active) + strlen(off_active);
433
434 if (u->job_id != 0)
435 printf(" %-*s", job_len, u->job_type);
436 else
437 b = 1 + job_len;
438
439 if (a + b + 1 < columns()) {
440 if (u->job_id == 0)
441 printf(" %-*s", job_len, "");
442
964d124e 443 if (arg_full || !arg_no_pager)
b036fc00
LP
444 printf(" %s", u->description);
445 else
446 printf(" %.*s", columns() - a - b - 1, u->description);
eb68c413 447 }
b036fc00
LP
448
449 fputs("\n", stdout);
eb68c413
ZJS
450 }
451
9b2fcafb 452 if (on_tty()) {
eb68c413
ZJS
453 printf("\nLOAD = Reflects whether the unit definition was properly loaded.\n"
454 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
455 "SUB = The low-level unit activation state, values depend on unit type.\n"
456 "JOB = Pending job for the unit.\n");
457
458 if (arg_all)
688c6725 459 printf("\n%u units listed.\n", n_shown);
eb68c413 460 else
688c6725 461 printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
eb68c413
ZJS
462 }
463}
464
7e4249b9
LP
465static int list_units(DBusConnection *bus, char **args, unsigned n) {
466 DBusMessage *m = NULL, *reply = NULL;
467 DBusError error;
468 int r;
469 DBusMessageIter iter, sub, sub2;
eb68c413 470 unsigned c = 0, n_units = 0;
36c32ba2 471 struct unit_info *unit_infos = NULL;
7e4249b9
LP
472
473 dbus_error_init(&error);
474
514f4ef5
LP
475 assert(bus);
476
ec14911e
LP
477 pager_open();
478
7e4249b9
LP
479 if (!(m = dbus_message_new_method_call(
480 "org.freedesktop.systemd1",
481 "/org/freedesktop/systemd1",
482 "org.freedesktop.systemd1.Manager",
483 "ListUnits"))) {
484 log_error("Could not allocate message.");
485 return -ENOMEM;
486 }
487
488 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 489 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
490 r = -EIO;
491 goto finish;
492 }
493
494 if (!dbus_message_iter_init(reply, &iter) ||
495 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
496 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
497 log_error("Failed to parse reply.");
498 r = -EIO;
499 goto finish;
500 }
501
502 dbus_message_iter_recurse(&iter, &sub);
503
7e4249b9 504 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
36c32ba2 505 struct unit_info *u;
7e4249b9
LP
506
507 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
508 log_error("Failed to parse reply.");
509 r = -EIO;
510 goto finish;
511 }
512
36c32ba2
LP
513 if (c >= n_units) {
514 struct unit_info *w;
515
516 n_units = MAX(2*c, 16);
517 w = realloc(unit_infos, sizeof(struct unit_info) * n_units);
518
519 if (!w) {
520 log_error("Failed to allocate unit array.");
521 r = -ENOMEM;
522 goto finish;
523 }
524
525 unit_infos = w;
526 }
527
528 u = unit_infos+c;
529
7e4249b9
LP
530 dbus_message_iter_recurse(&sub, &sub2);
531
36c32ba2
LP
532 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
533 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
534 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
535 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
536 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
537 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
538 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
539 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
540 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
541 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
7e4249b9
LP
542 log_error("Failed to parse reply.");
543 r = -EIO;
544 goto finish;
545 }
546
36c32ba2
LP
547 dbus_message_iter_next(&sub);
548 c++;
549 }
550
bd40a2d8
LP
551 if (c > 0) {
552 qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
553 output_units_list(unit_infos, c);
554 }
4445a875
LP
555
556 r = 0;
557
558finish:
559 if (m)
560 dbus_message_unref(m);
561
562 if (reply)
563 dbus_message_unref(reply);
564
36c32ba2
LP
565 free(unit_infos);
566
4445a875
LP
567 dbus_error_free(&error);
568
569 return r;
570}
571
572static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
573 static const char * const colors[] = {
574 "Requires", "[color=\"black\"]",
575 "RequiresOverridable", "[color=\"black\"]",
576 "Requisite", "[color=\"darkblue\"]",
577 "RequisiteOverridable", "[color=\"darkblue\"]",
578 "Wants", "[color=\"darkgrey\"]",
579 "Conflicts", "[color=\"red\"]",
69dd2852 580 "ConflictedBy", "[color=\"red\"]",
4445a875
LP
581 "After", "[color=\"green\"]"
582 };
583
584 const char *c = NULL;
585 unsigned i;
586
587 assert(name);
588 assert(prop);
589 assert(iter);
590
591 for (i = 0; i < ELEMENTSOF(colors); i += 2)
592 if (streq(colors[i], prop)) {
593 c = colors[i+1];
594 break;
595 }
596
597 if (!c)
598 return 0;
599
600 if (arg_dot != DOT_ALL)
601 if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
602 return 0;
603
604 switch (dbus_message_iter_get_arg_type(iter)) {
605
606 case DBUS_TYPE_ARRAY:
607
608 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
609 DBusMessageIter sub;
610
611 dbus_message_iter_recurse(iter, &sub);
612
613 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
614 const char *s;
615
616 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
617 dbus_message_iter_get_basic(&sub, &s);
618 printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);
619
620 dbus_message_iter_next(&sub);
621 }
622
623 return 0;
624 }
625 }
626
627 return 0;
628}
629
630static int dot_one(DBusConnection *bus, const char *name, const char *path) {
631 DBusMessage *m = NULL, *reply = NULL;
632 const char *interface = "org.freedesktop.systemd1.Unit";
633 int r;
634 DBusError error;
635 DBusMessageIter iter, sub, sub2, sub3;
636
637 assert(bus);
638 assert(path);
639
640 dbus_error_init(&error);
641
642 if (!(m = dbus_message_new_method_call(
643 "org.freedesktop.systemd1",
644 path,
645 "org.freedesktop.DBus.Properties",
646 "GetAll"))) {
647 log_error("Could not allocate message.");
648 r = -ENOMEM;
649 goto finish;
650 }
651
652 if (!dbus_message_append_args(m,
653 DBUS_TYPE_STRING, &interface,
654 DBUS_TYPE_INVALID)) {
655 log_error("Could not append arguments to message.");
656 r = -ENOMEM;
657 goto finish;
658 }
659
660 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 661 log_error("Failed to issue method call: %s", bus_error_message(&error));
4445a875
LP
662 r = -EIO;
663 goto finish;
664 }
665
666 if (!dbus_message_iter_init(reply, &iter) ||
667 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
668 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
669 log_error("Failed to parse reply.");
670 r = -EIO;
671 goto finish;
672 }
673
674 dbus_message_iter_recurse(&iter, &sub);
675
676 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
677 const char *prop;
678
679 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
680 log_error("Failed to parse reply.");
681 r = -EIO;
682 goto finish;
683 }
684
685 dbus_message_iter_recurse(&sub, &sub2);
686
687 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
688 log_error("Failed to parse reply.");
689 r = -EIO;
690 goto finish;
691 }
692
693 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
694 log_error("Failed to parse reply.");
695 r = -EIO;
696 goto finish;
697 }
698
699 dbus_message_iter_recurse(&sub2, &sub3);
700
701 if (dot_one_property(name, prop, &sub3)) {
702 log_error("Failed to parse reply.");
703 r = -EIO;
704 goto finish;
705 }
706
707 dbus_message_iter_next(&sub);
708 }
709
e364ad06
LP
710 r = 0;
711
4445a875
LP
712finish:
713 if (m)
714 dbus_message_unref(m);
715
716 if (reply)
717 dbus_message_unref(reply);
718
719 dbus_error_free(&error);
720
721 return r;
722}
723
724static int dot(DBusConnection *bus, char **args, unsigned n) {
725 DBusMessage *m = NULL, *reply = NULL;
726 DBusError error;
727 int r;
728 DBusMessageIter iter, sub, sub2;
729
730 dbus_error_init(&error);
731
732 assert(bus);
733
734 if (!(m = dbus_message_new_method_call(
735 "org.freedesktop.systemd1",
736 "/org/freedesktop/systemd1",
737 "org.freedesktop.systemd1.Manager",
738 "ListUnits"))) {
739 log_error("Could not allocate message.");
740 return -ENOMEM;
741 }
742
743 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 744 log_error("Failed to issue method call: %s", bus_error_message(&error));
4445a875
LP
745 r = -EIO;
746 goto finish;
747 }
748
749 if (!dbus_message_iter_init(reply, &iter) ||
750 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
751 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
752 log_error("Failed to parse reply.");
753 r = -EIO;
754 goto finish;
755 }
756
757 printf("digraph systemd {\n");
758
759 dbus_message_iter_recurse(&iter, &sub);
760 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
4a4d6b4b 761 const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
4445a875
LP
762
763 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
764 log_error("Failed to parse reply.");
765 r = -EIO;
766 goto finish;
767 }
768
769 dbus_message_iter_recurse(&sub, &sub2);
770
771 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
772 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
773 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
774 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
775 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
4a4d6b4b 776 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
4445a875
LP
777 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
778 log_error("Failed to parse reply.");
779 r = -EIO;
780 goto finish;
781 }
782
783 if ((r = dot_one(bus, id, unit_path)) < 0)
784 goto finish;
785
786 /* printf("\t\"%s\";\n", id); */
787 dbus_message_iter_next(&sub);
788 }
789
790 printf("}\n");
791
792 log_info(" Color legend: black = Requires\n"
793 " dark blue = Requisite\n"
794 " dark grey = Wants\n"
795 " red = Conflicts\n"
796 " green = After\n");
797
798 if (isatty(fileno(stdout)))
799 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
800 "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
7e4249b9
LP
801
802 r = 0;
803
804finish:
805 if (m)
806 dbus_message_unref(m);
807
808 if (reply)
809 dbus_message_unref(reply);
810
811 dbus_error_free(&error);
812
813 return r;
814}
815
816static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
817 DBusMessage *m = NULL, *reply = NULL;
818 DBusError error;
819 int r;
820 DBusMessageIter iter, sub, sub2;
821 unsigned k = 0;
822
823 dbus_error_init(&error);
824
514f4ef5
LP
825 assert(bus);
826
ec14911e
LP
827 pager_open();
828
7e4249b9
LP
829 if (!(m = dbus_message_new_method_call(
830 "org.freedesktop.systemd1",
831 "/org/freedesktop/systemd1",
832 "org.freedesktop.systemd1.Manager",
833 "ListJobs"))) {
834 log_error("Could not allocate message.");
835 return -ENOMEM;
836 }
837
838 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 839 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
840 r = -EIO;
841 goto finish;
842 }
843
844 if (!dbus_message_iter_init(reply, &iter) ||
845 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
846 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT) {
847 log_error("Failed to parse reply.");
848 r = -EIO;
849 goto finish;
850 }
851
852 dbus_message_iter_recurse(&iter, &sub);
853
f73e33d9
LP
854 if (isatty(STDOUT_FILENO))
855 printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
7e4249b9
LP
856
857 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
858 const char *name, *type, *state, *job_path, *unit_path;
859 uint32_t id;
8fe914ec 860 char *e;
7e4249b9
LP
861
862 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
863 log_error("Failed to parse reply.");
864 r = -EIO;
865 goto finish;
866 }
867
868 dbus_message_iter_recurse(&sub, &sub2);
869
870 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
871 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
872 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
873 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
874 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
875 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
876 log_error("Failed to parse reply.");
877 r = -EIO;
878 goto finish;
879 }
880
f73e33d9
LP
881 e = arg_full ? NULL : ellipsize(name, 25, 33);
882 printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
8fe914ec
LP
883 free(e);
884
7e4249b9
LP
885 k++;
886
887 dbus_message_iter_next(&sub);
888 }
889
f73e33d9
LP
890 if (isatty(STDOUT_FILENO))
891 printf("\n%u jobs listed.\n", k);
892
7e4249b9
LP
893 r = 0;
894
895finish:
896 if (m)
897 dbus_message_unref(m);
898
899 if (reply)
900 dbus_message_unref(reply);
901
902 dbus_error_free(&error);
903
904 return r;
905}
906
907static int load_unit(DBusConnection *bus, char **args, unsigned n) {
908 DBusMessage *m = NULL, *reply = NULL;
909 DBusError error;
910 int r;
911 unsigned i;
912
913 dbus_error_init(&error);
914
514f4ef5
LP
915 assert(bus);
916 assert(args);
917
7e4249b9
LP
918 for (i = 1; i < n; i++) {
919
920 if (!(m = dbus_message_new_method_call(
921 "org.freedesktop.systemd1",
922 "/org/freedesktop/systemd1",
923 "org.freedesktop.systemd1.Manager",
924 "LoadUnit"))) {
925 log_error("Could not allocate message.");
926 r = -ENOMEM;
927 goto finish;
928 }
929
930 if (!dbus_message_append_args(m,
931 DBUS_TYPE_STRING, &args[i],
932 DBUS_TYPE_INVALID)) {
933 log_error("Could not append arguments to message.");
934 r = -ENOMEM;
935 goto finish;
936 }
937
938 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 939 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
940 r = -EIO;
941 goto finish;
942 }
943
944 dbus_message_unref(m);
945 dbus_message_unref(reply);
946
947 m = reply = NULL;
948 }
949
950 r = 0;
951
952finish:
953 if (m)
954 dbus_message_unref(m);
955
956 if (reply)
957 dbus_message_unref(reply);
958
959 dbus_error_free(&error);
960
961 return r;
962}
963
964static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
965 DBusMessage *m = NULL, *reply = NULL;
966 DBusError error;
967 int r;
968 unsigned i;
969
970 dbus_error_init(&error);
971
514f4ef5
LP
972 assert(bus);
973 assert(args);
974
ee5762e3
LP
975 if (n <= 1)
976 return daemon_reload(bus, args, n);
977
7e4249b9
LP
978 for (i = 1; i < n; i++) {
979 unsigned id;
980 const char *path;
981
982 if (!(m = dbus_message_new_method_call(
983 "org.freedesktop.systemd1",
984 "/org/freedesktop/systemd1",
985 "org.freedesktop.systemd1.Manager",
986 "GetJob"))) {
987 log_error("Could not allocate message.");
988 r = -ENOMEM;
989 goto finish;
990 }
991
992 if ((r = safe_atou(args[i], &id)) < 0) {
993 log_error("Failed to parse job id: %s", strerror(-r));
994 goto finish;
995 }
996
997 assert_cc(sizeof(uint32_t) == sizeof(id));
998 if (!dbus_message_append_args(m,
999 DBUS_TYPE_UINT32, &id,
1000 DBUS_TYPE_INVALID)) {
1001 log_error("Could not append arguments to message.");
1002 r = -ENOMEM;
1003 goto finish;
1004 }
1005
1006 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 1007 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
1008 r = -EIO;
1009 goto finish;
1010 }
1011
1012 if (!dbus_message_get_args(reply, &error,
1013 DBUS_TYPE_OBJECT_PATH, &path,
1014 DBUS_TYPE_INVALID)) {
4cf5d675 1015 log_error("Failed to parse reply: %s", bus_error_message(&error));
7e4249b9
LP
1016 r = -EIO;
1017 goto finish;
1018 }
1019
1020 dbus_message_unref(m);
1021 if (!(m = dbus_message_new_method_call(
1022 "org.freedesktop.systemd1",
1023 path,
1024 "org.freedesktop.systemd1.Job",
1025 "Cancel"))) {
1026 log_error("Could not allocate message.");
1027 r = -ENOMEM;
1028 goto finish;
1029 }
1030
1031 dbus_message_unref(reply);
1032 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 1033 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
1034 r = -EIO;
1035 goto finish;
1036 }
1037
1038 dbus_message_unref(m);
1039 dbus_message_unref(reply);
1040 m = reply = NULL;
1041 }
1042
1043 r = 0;
1044
1045finish:
1046 if (m)
1047 dbus_message_unref(m);
1048
1049 if (reply)
1050 dbus_message_unref(reply);
1051
1052 dbus_error_free(&error);
1053
1054 return r;
1055}
1056
ee5762e3 1057static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
e364ad06 1058 DBusMessage *m = NULL, *reply = NULL;
45fb0699
LP
1059 dbus_bool_t b = FALSE;
1060 DBusMessageIter iter, sub;
1061 const char
1062 *interface = "org.freedesktop.systemd1.Unit",
1063 *property = "NeedDaemonReload",
1064 *path;
1065
1066 /* We ignore all errors here, since this is used to show a warning only */
1067
1068 if (!(m = dbus_message_new_method_call(
1069 "org.freedesktop.systemd1",
1070 "/org/freedesktop/systemd1",
1071 "org.freedesktop.systemd1.Manager",
1072 "GetUnit")))
1073 goto finish;
1074
1075 if (!dbus_message_append_args(m,
1076 DBUS_TYPE_STRING, &unit,
1077 DBUS_TYPE_INVALID))
1078 goto finish;
1079
1080 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1081 goto finish;
1082
1083 if (!dbus_message_get_args(reply, NULL,
1084 DBUS_TYPE_OBJECT_PATH, &path,
1085 DBUS_TYPE_INVALID))
1086 goto finish;
1087
1088 dbus_message_unref(m);
1089 if (!(m = dbus_message_new_method_call(
1090 "org.freedesktop.systemd1",
1091 path,
1092 "org.freedesktop.DBus.Properties",
1093 "Get")))
1094 goto finish;
1095
1096 if (!dbus_message_append_args(m,
1097 DBUS_TYPE_STRING, &interface,
1098 DBUS_TYPE_STRING, &property,
1099 DBUS_TYPE_INVALID)) {
1100 goto finish;
1101 }
1102
1103 dbus_message_unref(reply);
1104 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
1105 goto finish;
1106
1107 if (!dbus_message_iter_init(reply, &iter) ||
1108 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
1109 goto finish;
1110
1111 dbus_message_iter_recurse(&iter, &sub);
1112
1113 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
1114 goto finish;
1115
1116 dbus_message_iter_get_basic(&sub, &b);
1117
1118finish:
1119 if (m)
1120 dbus_message_unref(m);
1121
1122 if (reply)
1123 dbus_message_unref(reply);
1124
1125 return b;
1126}
1127
5e374895
LP
1128typedef struct WaitData {
1129 Set *set;
5d44db4a 1130 char *result;
5e374895
LP
1131} WaitData;
1132
7e4249b9
LP
1133static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
1134 DBusError error;
5e374895 1135 WaitData *d = data;
7e4249b9
LP
1136
1137 assert(connection);
1138 assert(message);
5e374895 1139 assert(d);
7e4249b9
LP
1140
1141 dbus_error_init(&error);
1142
54165a39
LP
1143 log_debug("Got D-Bus request: %s.%s() on %s",
1144 dbus_message_get_interface(message),
1145 dbus_message_get_member(message),
1146 dbus_message_get_path(message));
7e4249b9
LP
1147
1148 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
1149 log_error("Warning! D-Bus connection terminated.");
1150 dbus_connection_close(connection);
1151
1152 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
1153 uint32_t id;
5d44db4a 1154 const char *path, *result;
5e374895 1155 dbus_bool_t success = true;
7e4249b9 1156
5d44db4a
LP
1157 if (dbus_message_get_args(message, &error,
1158 DBUS_TYPE_UINT32, &id,
1159 DBUS_TYPE_OBJECT_PATH, &path,
1160 DBUS_TYPE_STRING, &result,
1161 DBUS_TYPE_INVALID)) {
7e4249b9
LP
1162 char *p;
1163
5d44db4a
LP
1164 if ((p = set_remove(d->set, (char*) path)))
1165 free(p);
1166
1167 if (*result)
1168 d->result = strdup(result);
1169
1170 goto finish;
1171 }
1172#ifndef LEGACY
1173 dbus_error_free(&error);
1174
1175 if (dbus_message_get_args(message, &error,
1176 DBUS_TYPE_UINT32, &id,
1177 DBUS_TYPE_OBJECT_PATH, &path,
1178 DBUS_TYPE_BOOLEAN, &success,
1179 DBUS_TYPE_INVALID)) {
1180 char *p;
1181
1182 /* Compatibility with older systemd versions <
1183 * 19 during upgrades. This should be dropped
1184 * one day */
1185
5e374895 1186 if ((p = set_remove(d->set, (char*) path)))
7e4249b9 1187 free(p);
5e374895
LP
1188
1189 if (!success)
5d44db4a
LP
1190 d->result = strdup("failed");
1191
1192 goto finish;
7e4249b9 1193 }
5d44db4a
LP
1194#endif
1195
1196 log_error("Failed to parse message: %s", bus_error_message(&error));
7e4249b9
LP
1197 }
1198
5d44db4a 1199finish:
7e4249b9
LP
1200 dbus_error_free(&error);
1201 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1202}
1203
479ef5d3 1204static int enable_wait_for_jobs(DBusConnection *bus) {
7e4249b9 1205 DBusError error;
7e4249b9
LP
1206
1207 assert(bus);
7e4249b9 1208
f4579ce7
LP
1209 if (private_bus)
1210 return 0;
1211
7e4249b9 1212 dbus_error_init(&error);
7e4249b9
LP
1213 dbus_bus_add_match(bus,
1214 "type='signal',"
1215 "sender='org.freedesktop.systemd1',"
1216 "interface='org.freedesktop.systemd1.Manager',"
1217 "member='JobRemoved',"
1218 "path='/org/freedesktop/systemd1'",
1219 &error);
1220
1221 if (dbus_error_is_set(&error)) {
4cf5d675 1222 log_error("Failed to add match: %s", bus_error_message(&error));
a567261a
LP
1223 dbus_error_free(&error);
1224 return -EIO;
7e4249b9
LP
1225 }
1226
479ef5d3 1227 /* This is slightly dirty, since we don't undo the match registrations. */
a567261a 1228 return 0;
7e4249b9
LP
1229}
1230
479ef5d3
LP
1231static int wait_for_jobs(DBusConnection *bus, Set *s) {
1232 int r;
5e374895 1233 WaitData d;
479ef5d3
LP
1234
1235 assert(bus);
1236 assert(s);
1237
5e374895
LP
1238 zero(d);
1239 d.set = s;
5e374895
LP
1240
1241 if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
479ef5d3
LP
1242 log_error("Failed to add filter.");
1243 r = -ENOMEM;
1244 goto finish;
1245 }
1246
1247 while (!set_isempty(s) &&
1248 dbus_connection_read_write_dispatch(bus, -1))
1249 ;
1250
5d44db4a
LP
1251 if (!arg_quiet && d.result) {
1252 if (streq(d.result, "timeout"))
1253 log_error("Job timed out.");
1254 else if (streq(d.result, "canceled"))
1255 log_error("Job canceled.");
1256 else if (streq(d.result, "dependency"))
1257 log_error("A dependency job failed. See system logs for details.");
d68201e9 1258 else if (!streq(d.result, "done") && !streq(d.result, "skipped"))
5d44db4a
LP
1259 log_error("Job failed. See system logs and 'systemctl status' for details.");
1260 }
5e374895 1261
8e20e31a
LP
1262 if (streq_ptr(d.result, "timeout"))
1263 r = -ETIME;
1264 else if (streq_ptr(d.result, "canceled"))
1265 r = -ECANCELED;
d68201e9 1266 else if (!streq_ptr(d.result, "done") && !streq_ptr(d.result, "skipped"))
8e20e31a
LP
1267 r = -EIO;
1268 else
1269 r = 0;
1270
5d44db4a 1271 free(d.result);
479ef5d3
LP
1272
1273finish:
1274 /* This is slightly dirty, since we don't undo the filter registration. */
1275
1276 return r;
1277}
1278
e4b61340
LP
1279static int start_unit_one(
1280 DBusConnection *bus,
1281 const char *method,
1282 const char *name,
1283 const char *mode,
22f4096c 1284 DBusError *error,
e4b61340 1285 Set *s) {
7e4249b9 1286
7e4249b9 1287 DBusMessage *m = NULL, *reply = NULL;
45fb0699 1288 const char *path;
7e4249b9 1289 int r;
7e4249b9 1290
e4b61340
LP
1291 assert(bus);
1292 assert(method);
1293 assert(name);
1294 assert(mode);
22f4096c 1295 assert(error);
6e905d93 1296 assert(arg_no_block || s);
7e4249b9
LP
1297
1298 if (!(m = dbus_message_new_method_call(
1299 "org.freedesktop.systemd1",
1300 "/org/freedesktop/systemd1",
1301 "org.freedesktop.systemd1.Manager",
e4b61340 1302 method))) {
7e4249b9
LP
1303 log_error("Could not allocate message.");
1304 r = -ENOMEM;
1305 goto finish;
1306 }
1307
1308 if (!dbus_message_append_args(m,
e4b61340 1309 DBUS_TYPE_STRING, &name,
7e4249b9
LP
1310 DBUS_TYPE_STRING, &mode,
1311 DBUS_TYPE_INVALID)) {
1312 log_error("Could not append arguments to message.");
1313 r = -ENOMEM;
1314 goto finish;
1315 }
1316
22f4096c 1317 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error))) {
e4b61340 1318
22f4096c 1319 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(error)) {
e4b61340
LP
1320 /* There's always a fallback possible for
1321 * legacy actions. */
706900b7 1322 r = -EADDRNOTAVAIL;
e4b61340
LP
1323 goto finish;
1324 }
1325
22f4096c 1326 log_error("Failed to issue method call: %s", bus_error_message(error));
7e4249b9
LP
1327 r = -EIO;
1328 goto finish;
1329 }
1330
22f4096c 1331 if (!dbus_message_get_args(reply, error,
45fb0699
LP
1332 DBUS_TYPE_OBJECT_PATH, &path,
1333 DBUS_TYPE_INVALID)) {
22f4096c 1334 log_error("Failed to parse reply: %s", bus_error_message(error));
45fb0699
LP
1335 r = -EIO;
1336 goto finish;
1337 }
1338
ee5762e3 1339 if (need_daemon_reload(bus, name))
45fb0699 1340 log_warning("Unit file of created job changed on disk, 'systemctl %s daemon-reload' recommended.",
af2d49f7 1341 arg_user ? "--user" : "--system");
45fb0699 1342
6e905d93 1343 if (!arg_no_block) {
e4b61340 1344 char *p;
7e4249b9 1345
7e4249b9
LP
1346 if (!(p = strdup(path))) {
1347 log_error("Failed to duplicate path.");
1348 r = -ENOMEM;
1349 goto finish;
1350 }
1351
1352 if ((r = set_put(s, p)) < 0) {
e4b61340 1353 free(p);
7e4249b9
LP
1354 log_error("Failed to add path to set.");
1355 goto finish;
1356 }
e4b61340 1357 }
7e4249b9 1358
706900b7 1359 r = 0;
22f4096c 1360
7e4249b9 1361finish:
7e4249b9
LP
1362 if (m)
1363 dbus_message_unref(m);
1364
1365 if (reply)
1366 dbus_message_unref(reply);
1367
7e4249b9
LP
1368 return r;
1369}
1370
514f4ef5
LP
1371static enum action verb_to_action(const char *verb) {
1372 if (streq(verb, "halt"))
1373 return ACTION_HALT;
1374 else if (streq(verb, "poweroff"))
1375 return ACTION_POWEROFF;
1376 else if (streq(verb, "reboot"))
1377 return ACTION_REBOOT;
20b09ca7
LP
1378 else if (streq(verb, "kexec"))
1379 return ACTION_KEXEC;
514f4ef5
LP
1380 else if (streq(verb, "rescue"))
1381 return ACTION_RESCUE;
1382 else if (streq(verb, "emergency"))
1383 return ACTION_EMERGENCY;
1384 else if (streq(verb, "default"))
1385 return ACTION_DEFAULT;
20b09ca7
LP
1386 else if (streq(verb, "exit"))
1387 return ACTION_EXIT;
514f4ef5
LP
1388 else
1389 return ACTION_INVALID;
1390}
1391
e4b61340
LP
1392static int start_unit(DBusConnection *bus, char **args, unsigned n) {
1393
1394 static const char * const table[_ACTION_MAX] = {
514f4ef5
LP
1395 [ACTION_HALT] = SPECIAL_HALT_TARGET,
1396 [ACTION_POWEROFF] = SPECIAL_POWEROFF_TARGET,
1397 [ACTION_REBOOT] = SPECIAL_REBOOT_TARGET,
20b09ca7 1398 [ACTION_KEXEC] = SPECIAL_KEXEC_TARGET,
514f4ef5
LP
1399 [ACTION_RUNLEVEL2] = SPECIAL_RUNLEVEL2_TARGET,
1400 [ACTION_RUNLEVEL3] = SPECIAL_RUNLEVEL3_TARGET,
1401 [ACTION_RUNLEVEL4] = SPECIAL_RUNLEVEL4_TARGET,
1402 [ACTION_RUNLEVEL5] = SPECIAL_RUNLEVEL5_TARGET,
1403 [ACTION_RESCUE] = SPECIAL_RESCUE_TARGET,
f057408c 1404 [ACTION_EMERGENCY] = SPECIAL_EMERGENCY_TARGET,
20b09ca7
LP
1405 [ACTION_DEFAULT] = SPECIAL_DEFAULT_TARGET,
1406 [ACTION_EXIT] = SPECIAL_EXIT_TARGET
e4b61340
LP
1407 };
1408
22f4096c 1409 int r, ret = 0;
e4b61340 1410 unsigned i;
514f4ef5 1411 const char *method, *mode, *one_name;
e4b61340 1412 Set *s = NULL;
22f4096c
LP
1413 DBusError error;
1414
1415 dbus_error_init(&error);
e4b61340 1416
514f4ef5
LP
1417 assert(bus);
1418
501fc174
LP
1419 spawn_ask_password_agent();
1420
e4b61340
LP
1421 if (arg_action == ACTION_SYSTEMCTL) {
1422 method =
a76f7be2
LP
1423 streq(args[0], "stop") ||
1424 streq(args[0], "condstop") ? "StopUnit" :
6f28c033
LP
1425 streq(args[0], "reload") ? "ReloadUnit" :
1426 streq(args[0], "restart") ? "RestartUnit" :
d68201e9 1427
aa5939a3
MS
1428 streq(args[0], "try-restart") ||
1429 streq(args[0], "condrestart") ? "TryRestartUnit" :
d68201e9 1430
6f28c033 1431 streq(args[0], "reload-or-restart") ? "ReloadOrRestartUnit" :
d68201e9 1432
9d8a57ff 1433 streq(args[0], "reload-or-try-restart") ||
64e5f1b7 1434 streq(args[0], "condreload") ||
d68201e9 1435
aa5939a3 1436 streq(args[0], "force-reload") ? "ReloadOrTryRestartUnit" :
6f28c033 1437 "StartUnit";
e4b61340
LP
1438
1439 mode =
514f4ef5
LP
1440 (streq(args[0], "isolate") ||
1441 streq(args[0], "rescue") ||
e67c3609 1442 streq(args[0], "emergency")) ? "isolate" : arg_job_mode;
e4b61340 1443
514f4ef5 1444 one_name = table[verb_to_action(args[0])];
e4b61340 1445
e4b61340
LP
1446 } else {
1447 assert(arg_action < ELEMENTSOF(table));
1448 assert(table[arg_action]);
1449
1450 method = "StartUnit";
514f4ef5
LP
1451
1452 mode = (arg_action == ACTION_EMERGENCY ||
6f0d624e
LP
1453 arg_action == ACTION_RESCUE ||
1454 arg_action == ACTION_RUNLEVEL2 ||
1455 arg_action == ACTION_RUNLEVEL3 ||
1456 arg_action == ACTION_RUNLEVEL4 ||
1457 arg_action == ACTION_RUNLEVEL5) ? "isolate" : "replace";
514f4ef5
LP
1458
1459 one_name = table[arg_action];
1460 }
1461
6e905d93 1462 if (!arg_no_block) {
22f4096c
LP
1463 if ((ret = enable_wait_for_jobs(bus)) < 0) {
1464 log_error("Could not watch jobs: %s", strerror(-ret));
514f4ef5
LP
1465 goto finish;
1466 }
1467
1468 if (!(s = set_new(string_hash_func, string_compare_func))) {
1469 log_error("Failed to allocate set.");
22f4096c 1470 ret = -ENOMEM;
514f4ef5
LP
1471 goto finish;
1472 }
e4b61340
LP
1473 }
1474
514f4ef5 1475 if (one_name) {
22f4096c 1476 if ((ret = start_unit_one(bus, method, one_name, mode, &error, s)) <= 0)
514f4ef5
LP
1477 goto finish;
1478 } else {
e4b61340 1479 for (i = 1; i < n; i++)
22f4096c 1480 if ((r = start_unit_one(bus, method, args[i], mode, &error, s)) != 0) {
706900b7 1481 ret = translate_bus_error_to_exit_status(r, &error);
22f4096c
LP
1482 dbus_error_free(&error);
1483 }
e4b61340
LP
1484 }
1485
6e905d93 1486 if (!arg_no_block)
22f4096c
LP
1487 if ((r = wait_for_jobs(bus, s)) < 0) {
1488 ret = r;
fbc43921 1489 goto finish;
22f4096c 1490 }
514f4ef5 1491
e4b61340
LP
1492finish:
1493 if (s)
1494 set_free_free(s);
1495
22f4096c
LP
1496 dbus_error_free(&error);
1497
1498 return ret;
e4b61340
LP
1499}
1500
514f4ef5 1501static int start_special(DBusConnection *bus, char **args, unsigned n) {
983d9c90
LP
1502 int r;
1503
514f4ef5
LP
1504 assert(bus);
1505 assert(args);
1506
20b09ca7
LP
1507 if (arg_force &&
1508 (streq(args[0], "halt") ||
1509 streq(args[0], "poweroff") ||
1510 streq(args[0], "reboot") ||
1511 streq(args[0], "kexec") ||
1512 streq(args[0], "exit")))
1513 return daemon_reload(bus, args, n);
1514
983d9c90
LP
1515 r = start_unit(bus, args, n);
1516
1517 if (r >= 0)
1518 warn_wall(verb_to_action(args[0]));
514f4ef5 1519
983d9c90 1520 return r;
514f4ef5
LP
1521}
1522
0183528f
LP
1523static int check_unit(DBusConnection *bus, char **args, unsigned n) {
1524 DBusMessage *m = NULL, *reply = NULL;
1525 const char
1526 *interface = "org.freedesktop.systemd1.Unit",
1527 *property = "ActiveState";
22f4096c 1528 int r = 3; /* According to LSB: "program is not running" */
0183528f
LP
1529 DBusError error;
1530 unsigned i;
1531
1532 assert(bus);
1533 assert(args);
1534
1535 dbus_error_init(&error);
1536
1537 for (i = 1; i < n; i++) {
1538 const char *path = NULL;
1539 const char *state;
1540 DBusMessageIter iter, sub;
1541
1542 if (!(m = dbus_message_new_method_call(
1543 "org.freedesktop.systemd1",
1544 "/org/freedesktop/systemd1",
1545 "org.freedesktop.systemd1.Manager",
1546 "GetUnit"))) {
1547 log_error("Could not allocate message.");
1548 r = -ENOMEM;
1549 goto finish;
1550 }
1551
1552 if (!dbus_message_append_args(m,
1553 DBUS_TYPE_STRING, &args[i],
1554 DBUS_TYPE_INVALID)) {
1555 log_error("Could not append arguments to message.");
1556 r = -ENOMEM;
1557 goto finish;
1558 }
1559
1560 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1561
1562 /* Hmm, cannot figure out anything about this unit... */
1563 if (!arg_quiet)
1564 puts("unknown");
1565
ed2d7a44 1566 dbus_error_free(&error);
8a0867d6 1567 dbus_message_unref(m);
78e39b43 1568 m = NULL;
0183528f
LP
1569 continue;
1570 }
1571
1572 if (!dbus_message_get_args(reply, &error,
1573 DBUS_TYPE_OBJECT_PATH, &path,
1574 DBUS_TYPE_INVALID)) {
4cf5d675 1575 log_error("Failed to parse reply: %s", bus_error_message(&error));
0183528f
LP
1576 r = -EIO;
1577 goto finish;
1578 }
1579
1580 dbus_message_unref(m);
1581 if (!(m = dbus_message_new_method_call(
1582 "org.freedesktop.systemd1",
1583 path,
1584 "org.freedesktop.DBus.Properties",
1585 "Get"))) {
1586 log_error("Could not allocate message.");
1587 r = -ENOMEM;
1588 goto finish;
1589 }
1590
1591 if (!dbus_message_append_args(m,
1592 DBUS_TYPE_STRING, &interface,
1593 DBUS_TYPE_STRING, &property,
1594 DBUS_TYPE_INVALID)) {
1595 log_error("Could not append arguments to message.");
1596 r = -ENOMEM;
1597 goto finish;
1598 }
1599
1600 dbus_message_unref(reply);
1601 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 1602 log_error("Failed to issue method call: %s", bus_error_message(&error));
0183528f
LP
1603 r = -EIO;
1604 goto finish;
1605 }
1606
1607 if (!dbus_message_iter_init(reply, &iter) ||
1608 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
1609 log_error("Failed to parse reply.");
1610 r = -EIO;
1611 goto finish;
1612 }
1613
1614 dbus_message_iter_recurse(&iter, &sub);
1615
1616 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
1617 log_error("Failed to parse reply.");
1618 r = -EIO;
1619 goto finish;
1620 }
1621
1622 dbus_message_iter_get_basic(&sub, &state);
1623
1624 if (!arg_quiet)
1625 puts(state);
1626
f1e36d67 1627 if (streq(state, "active") || streq(state, "reloading"))
0183528f
LP
1628 r = 0;
1629
1630 dbus_message_unref(m);
1631 dbus_message_unref(reply);
1632 m = reply = NULL;
1633 }
1634
1635finish:
1636 if (m)
1637 dbus_message_unref(m);
1638
1639 if (reply)
1640 dbus_message_unref(reply);
1641
1642 dbus_error_free(&error);
1643
1644 return r;
48220598
LP
1645}
1646
8a0867d6
LP
1647static int kill_unit(DBusConnection *bus, char **args, unsigned n) {
1648 DBusMessage *m = NULL, *reply = NULL;
1649 int r = 0;
1650 DBusError error;
1651 unsigned i;
1652
1653 assert(bus);
1654 assert(args);
1655
1656 dbus_error_init(&error);
1657
1658 if (!arg_kill_who)
1659 arg_kill_who = "all";
1660
1661 if (!arg_kill_mode)
1662 arg_kill_mode = streq(arg_kill_who, "all") ? "control-group" : "process";
1663
1664 for (i = 1; i < n; i++) {
1665
1666 if (!(m = dbus_message_new_method_call(
1667 "org.freedesktop.systemd1",
1668 "/org/freedesktop/systemd1",
1669 "org.freedesktop.systemd1.Manager",
1670 "KillUnit"))) {
1671 log_error("Could not allocate message.");
1672 r = -ENOMEM;
1673 goto finish;
1674 }
1675
1676 if (!dbus_message_append_args(m,
1677 DBUS_TYPE_STRING, &args[i],
1678 DBUS_TYPE_STRING, &arg_kill_who,
1679 DBUS_TYPE_STRING, &arg_kill_mode,
1680 DBUS_TYPE_INT32, &arg_signal,
1681 DBUS_TYPE_INVALID)) {
1682 log_error("Could not append arguments to message.");
1683 r = -ENOMEM;
1684 goto finish;
1685 }
1686
1687 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1688 log_error("Failed to issue method call: %s", bus_error_message(&error));
1689 dbus_error_free(&error);
1690 r = -EIO;
1691 }
1692
1693 dbus_message_unref(m);
1694
1695 if (reply)
1696 dbus_message_unref(reply);
1697 m = reply = NULL;
1698 }
1699
1700finish:
1701 if (m)
1702 dbus_message_unref(m);
1703
1704 if (reply)
1705 dbus_message_unref(reply);
1706
1707 dbus_error_free(&error);
1708
1709 return r;
1710}
1711
582a507f 1712typedef struct ExecStatusInfo {
0129173a
LP
1713 char *name;
1714
582a507f
LP
1715 char *path;
1716 char **argv;
1717
b708e7ce
LP
1718 bool ignore;
1719
582a507f
LP
1720 usec_t start_timestamp;
1721 usec_t exit_timestamp;
1722 pid_t pid;
1723 int code;
1724 int status;
1725
1726 LIST_FIELDS(struct ExecStatusInfo, exec);
1727} ExecStatusInfo;
1728
1729static void exec_status_info_free(ExecStatusInfo *i) {
1730 assert(i);
1731
0129173a 1732 free(i->name);
582a507f
LP
1733 free(i->path);
1734 strv_free(i->argv);
1735 free(i);
1736}
1737
1738static int exec_status_info_deserialize(DBusMessageIter *sub, ExecStatusInfo *i) {
b21a0ef8 1739 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
582a507f
LP
1740 DBusMessageIter sub2, sub3;
1741 const char*path;
1742 unsigned n;
1743 uint32_t pid;
1744 int32_t code, status;
b708e7ce 1745 dbus_bool_t ignore;
582a507f
LP
1746
1747 assert(i);
1748 assert(i);
1749
1750 if (dbus_message_iter_get_arg_type(sub) != DBUS_TYPE_STRUCT)
1751 return -EIO;
1752
1753 dbus_message_iter_recurse(sub, &sub2);
1754
1755 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) < 0)
1756 return -EIO;
1757
1758 if (!(i->path = strdup(path)))
1759 return -ENOMEM;
1760
1761 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_ARRAY ||
1762 dbus_message_iter_get_element_type(&sub2) != DBUS_TYPE_STRING)
1763 return -EIO;
1764
1765 n = 0;
1766 dbus_message_iter_recurse(&sub2, &sub3);
1767 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1768 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1769 dbus_message_iter_next(&sub3);
1770 n++;
1771 }
1772
1773
1774 if (!(i->argv = new0(char*, n+1)))
1775 return -ENOMEM;
1776
1777 n = 0;
1778 dbus_message_iter_recurse(&sub2, &sub3);
1779 while (dbus_message_iter_get_arg_type(&sub3) != DBUS_TYPE_INVALID) {
1780 const char *s;
1781
1782 assert(dbus_message_iter_get_arg_type(&sub3) == DBUS_TYPE_STRING);
1783 dbus_message_iter_get_basic(&sub3, &s);
1784 dbus_message_iter_next(&sub3);
1785
1786 if (!(i->argv[n++] = strdup(s)))
1787 return -ENOMEM;
1788 }
1789
1790 if (!dbus_message_iter_next(&sub2) ||
b708e7ce 1791 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, true) < 0 ||
582a507f 1792 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp, true) < 0 ||
b21a0ef8 1793 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &start_timestamp_monotonic, true) < 0 ||
582a507f 1794 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp, true) < 0 ||
b21a0ef8 1795 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &exit_timestamp_monotonic, true) < 0 ||
582a507f
LP
1796 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &pid, true) < 0 ||
1797 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &code, true) < 0 ||
1798 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_INT32, &status, false) < 0)
1799 return -EIO;
1800
b708e7ce 1801 i->ignore = ignore;
582a507f
LP
1802 i->start_timestamp = (usec_t) start_timestamp;
1803 i->exit_timestamp = (usec_t) exit_timestamp;
1804 i->pid = (pid_t) pid;
1805 i->code = code;
1806 i->status = status;
1807
1808 return 0;
1809}
1810
61cbdc4b
LP
1811typedef struct UnitStatusInfo {
1812 const char *id;
1813 const char *load_state;
1814 const char *active_state;
1815 const char *sub_state;
1816
1817 const char *description;
4a9e2fff 1818 const char *following;
61cbdc4b 1819
c31b4423 1820 const char *path;
61cbdc4b
LP
1821 const char *default_control_group;
1822
584be568
LP
1823 usec_t inactive_exit_timestamp;
1824 usec_t active_enter_timestamp;
1825 usec_t active_exit_timestamp;
1826 usec_t inactive_enter_timestamp;
1827
45fb0699
LP
1828 bool need_daemon_reload;
1829
61cbdc4b
LP
1830 /* Service */
1831 pid_t main_pid;
1832 pid_t control_pid;
1833 const char *status_text;
d06dacd0 1834 bool running:1;
07459bb6 1835#ifdef HAVE_SYSV_COMPAT
d06dacd0 1836 bool is_sysv:1;
07459bb6 1837#endif
61cbdc4b
LP
1838
1839 usec_t start_timestamp;
1840 usec_t exit_timestamp;
1841
1842 int exit_code, exit_status;
1843
90bbc946
LP
1844 usec_t condition_timestamp;
1845 bool condition_result;
1846
61cbdc4b
LP
1847 /* Socket */
1848 unsigned n_accepted;
1849 unsigned n_connections;
b8131a87 1850 bool accept;
61cbdc4b
LP
1851
1852 /* Device */
1853 const char *sysfs_path;
1854
1855 /* Mount, Automount */
1856 const char *where;
1857
1858 /* Swap */
1859 const char *what;
582a507f
LP
1860
1861 LIST_HEAD(ExecStatusInfo, exec);
61cbdc4b
LP
1862} UnitStatusInfo;
1863
1864static void print_status_info(UnitStatusInfo *i) {
582a507f 1865 ExecStatusInfo *p;
2ee68f72 1866 const char *on, *off, *ss;
584be568
LP
1867 usec_t timestamp;
1868 char since1[FORMAT_TIMESTAMP_PRETTY_MAX], *s1;
1869 char since2[FORMAT_TIMESTAMP_MAX], *s2;
582a507f 1870
61cbdc4b
LP
1871 assert(i);
1872
1873 /* This shows pretty information about a unit. See
1874 * print_property() for a low-level property printer */
1875
1876 printf("%s", strna(i->id));
1877
1878 if (i->description && !streq_ptr(i->id, i->description))
1879 printf(" - %s", i->description);
1880
1881 printf("\n");
1882
4a9e2fff
LP
1883 if (i->following)
1884 printf("\t Follow: unit currently follows state of %s\n", i->following);
1885
00dc5d76
LP
1886 if (streq_ptr(i->load_state, "failed") ||
1887 streq_ptr(i->load_state, "banned")) {
c31b4423
LP
1888 on = ansi_highlight(true);
1889 off = ansi_highlight(false);
1890 } else
1891 on = off = "";
1892
1893 if (i->path)
1894 printf("\t Loaded: %s%s%s (%s)\n", on, strna(i->load_state), off, i->path);
61cbdc4b 1895 else
c31b4423 1896 printf("\t Loaded: %s%s%s\n", on, strna(i->load_state), off);
61cbdc4b 1897
2ee68f72
LP
1898 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
1899
fdf20a31 1900 if (streq_ptr(i->active_state, "failed")) {
2ee68f72
LP
1901 on = ansi_highlight(true);
1902 off = ansi_highlight(false);
1903 } else if (streq_ptr(i->active_state, "active") || streq_ptr(i->active_state, "reloading")) {
1904 on = ansi_highlight_green(true);
1905 off = ansi_highlight_green(false);
1906 } else
1907 on = off = "";
1908
1909 if (ss)
584be568 1910 printf("\t Active: %s%s (%s)%s",
2ee68f72
LP
1911 on,
1912 strna(i->active_state),
1913 ss,
1914 off);
1915 else
584be568 1916 printf("\t Active: %s%s%s",
2ee68f72
LP
1917 on,
1918 strna(i->active_state),
1919 off);
61cbdc4b 1920
584be568
LP
1921 timestamp = (streq_ptr(i->active_state, "active") ||
1922 streq_ptr(i->active_state, "reloading")) ? i->active_enter_timestamp :
1923 (streq_ptr(i->active_state, "inactive") ||
fdf20a31 1924 streq_ptr(i->active_state, "failed")) ? i->inactive_enter_timestamp :
584be568
LP
1925 streq_ptr(i->active_state, "activating") ? i->inactive_exit_timestamp :
1926 i->active_exit_timestamp;
1927
1928 s1 = format_timestamp_pretty(since1, sizeof(since1), timestamp);
1929 s2 = format_timestamp(since2, sizeof(since2), timestamp);
1930
1931 if (s1)
538da63d 1932 printf(" since %s; %s\n", s2, s1);
584be568 1933 else if (s2)
538da63d 1934 printf(" since %s\n", s2);
584be568
LP
1935 else
1936 printf("\n");
1937
90bbc946
LP
1938 if (!i->condition_result && i->condition_timestamp > 0) {
1939 s1 = format_timestamp_pretty(since1, sizeof(since1), i->condition_timestamp);
1940 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
1941
1942 if (s1)
1943 printf("\t start condition failed at %s; %s\n", s2, s1);
1944 else if (s2)
1945 printf("\t start condition failed at %s\n", s2);
1946 }
1947
61cbdc4b
LP
1948 if (i->sysfs_path)
1949 printf("\t Device: %s\n", i->sysfs_path);
9feeba4b 1950 if (i->where)
61cbdc4b 1951 printf("\t Where: %s\n", i->where);
9feeba4b 1952 if (i->what)
61cbdc4b
LP
1953 printf("\t What: %s\n", i->what);
1954
b8131a87 1955 if (i->accept)
61cbdc4b
LP
1956 printf("\tAccepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
1957
582a507f
LP
1958 LIST_FOREACH(exec, p, i->exec) {
1959 char *t;
9a57c629 1960 bool good;
582a507f
LP
1961
1962 /* Only show exited processes here */
1963 if (p->code == 0)
1964 continue;
1965
1966 t = strv_join(p->argv, " ");
9a57c629 1967 printf("\t Process: %u %s=%s ", p->pid, p->name, strna(t));
582a507f
LP
1968 free(t);
1969
9a57c629
LP
1970#ifdef HAVE_SYSV_COMPAT
1971 if (i->is_sysv)
1972 good = is_clean_exit_lsb(p->code, p->status);
1973 else
1974#endif
1975 good = is_clean_exit(p->code, p->status);
1976
1977 if (!good) {
1978 on = ansi_highlight(true);
1979 off = ansi_highlight(false);
1980 } else
1981 on = off = "";
1982
1983 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
1984
d06dacd0
LP
1985 if (p->code == CLD_EXITED) {
1986 const char *c;
1987
582a507f 1988 printf("status=%i", p->status);
d06dacd0 1989
07459bb6 1990#ifdef HAVE_SYSV_COMPAT
d06dacd0 1991 if ((c = exit_status_to_string(p->status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
07459bb6
FF
1992#else
1993 if ((c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD)))
1994#endif
d06dacd0
LP
1995 printf("/%s", c);
1996
1997 } else
582a507f 1998 printf("signal=%s", signal_to_string(p->status));
9a57c629
LP
1999
2000 printf(")%s\n", off);
2001
2002 on = off = NULL;
582a507f
LP
2003
2004 if (i->main_pid == p->pid &&
2005 i->start_timestamp == p->start_timestamp &&
2006 i->exit_timestamp == p->start_timestamp)
2007 /* Let's not show this twice */
2008 i->main_pid = 0;
2009
2010 if (p->pid == i->control_pid)
2011 i->control_pid = 0;
2012 }
2013
61cbdc4b
LP
2014 if (i->main_pid > 0 || i->control_pid > 0) {
2015 printf("\t");
2016
2017 if (i->main_pid > 0) {
f3d41013 2018 printf("Main PID: %u", (unsigned) i->main_pid);
61cbdc4b
LP
2019
2020 if (i->running) {
2021 char *t = NULL;
2022 get_process_name(i->main_pid, &t);
2023 if (t) {
2024 printf(" (%s)", t);
2025 free(t);
2026 }
6d4fc029 2027 } else if (i->exit_code > 0) {
61cbdc4b
LP
2028 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
2029
d06dacd0
LP
2030 if (i->exit_code == CLD_EXITED) {
2031 const char *c;
2032
61cbdc4b 2033 printf("status=%i", i->exit_status);
d06dacd0 2034
07459bb6 2035#ifdef HAVE_SYSV_COMPAT
d06dacd0 2036 if ((c = exit_status_to_string(i->exit_status, i->is_sysv ? EXIT_STATUS_LSB : EXIT_STATUS_SYSTEMD)))
07459bb6
FF
2037#else
2038 if ((c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD)))
2039#endif
d06dacd0
LP
2040 printf("/%s", c);
2041
2042 } else
582a507f 2043 printf("signal=%s", signal_to_string(i->exit_status));
6d4fc029
LP
2044 printf(")");
2045 }
61cbdc4b
LP
2046 }
2047
2048 if (i->main_pid > 0 && i->control_pid > 0)
2049 printf(";");
2050
2051 if (i->control_pid > 0) {
2052 char *t = NULL;
2053
2054 printf(" Control: %u", (unsigned) i->control_pid);
2055
2056 get_process_name(i->control_pid, &t);
2057 if (t) {
2058 printf(" (%s)", t);
2059 free(t);
2060 }
2061 }
2062
2063 printf("\n");
2064 }
2065
17bb7382
LP
2066 if (i->status_text)
2067 printf("\t Status: \"%s\"\n", i->status_text);
2068
c59760ee 2069 if (i->default_control_group) {
ab35fb1b
LP
2070 unsigned c;
2071
61cbdc4b 2072 printf("\t CGroup: %s\n", i->default_control_group);
ab35fb1b 2073
a8f11321
LP
2074 if (arg_transport != TRANSPORT_SSH) {
2075 if ((c = columns()) > 18)
2076 c -= 18;
2077 else
2078 c = 0;
ab35fb1b 2079
a8f11321
LP
2080 show_cgroup_by_path(i->default_control_group, "\t\t ", c);
2081 }
c59760ee 2082 }
45fb0699
LP
2083
2084 if (i->need_daemon_reload)
2cc59dbf
LP
2085 printf("\n%sWarning:%s Unit file changed on disk, 'systemctl %s daemon-reload' recommended.\n",
2086 ansi_highlight(true),
2087 ansi_highlight(false),
af2d49f7 2088 arg_user ? "--user" : "--system");
61cbdc4b
LP
2089}
2090
2091static int status_property(const char *name, DBusMessageIter *iter, UnitStatusInfo *i) {
2092
2093 switch (dbus_message_iter_get_arg_type(iter)) {
2094
2095 case DBUS_TYPE_STRING: {
2096 const char *s;
2097
2098 dbus_message_iter_get_basic(iter, &s);
2099
2100 if (s[0]) {
2101 if (streq(name, "Id"))
2102 i->id = s;
2103 else if (streq(name, "LoadState"))
2104 i->load_state = s;
2105 else if (streq(name, "ActiveState"))
2106 i->active_state = s;
2107 else if (streq(name, "SubState"))
2108 i->sub_state = s;
2109 else if (streq(name, "Description"))
2110 i->description = s;
2111 else if (streq(name, "FragmentPath"))
c31b4423 2112 i->path = s;
07459bb6 2113#ifdef HAVE_SYSV_COMPAT
d06dacd0
LP
2114 else if (streq(name, "SysVPath")) {
2115 i->is_sysv = true;
c31b4423 2116 i->path = s;
07459bb6
FF
2117 }
2118#endif
2119 else if (streq(name, "DefaultControlGroup"))
61cbdc4b
LP
2120 i->default_control_group = s;
2121 else if (streq(name, "StatusText"))
2122 i->status_text = s;
2123 else if (streq(name, "SysFSPath"))
2124 i->sysfs_path = s;
2125 else if (streq(name, "Where"))
2126 i->where = s;
2127 else if (streq(name, "What"))
2128 i->what = s;
4a9e2fff
LP
2129 else if (streq(name, "Following"))
2130 i->following = s;
61cbdc4b
LP
2131 }
2132
2133 break;
2134 }
2135
b8131a87
LP
2136 case DBUS_TYPE_BOOLEAN: {
2137 dbus_bool_t b;
2138
2139 dbus_message_iter_get_basic(iter, &b);
2140
2141 if (streq(name, "Accept"))
2142 i->accept = b;
45fb0699
LP
2143 else if (streq(name, "NeedDaemonReload"))
2144 i->need_daemon_reload = b;
90bbc946
LP
2145 else if (streq(name, "ConditionResult"))
2146 i->condition_result = b;
b8131a87
LP
2147
2148 break;
2149 }
2150
61cbdc4b
LP
2151 case DBUS_TYPE_UINT32: {
2152 uint32_t u;
2153
2154 dbus_message_iter_get_basic(iter, &u);
2155
2156 if (streq(name, "MainPID")) {
2157 if (u > 0) {
2158 i->main_pid = (pid_t) u;
2159 i->running = true;
2160 }
2161 } else if (streq(name, "ControlPID"))
2162 i->control_pid = (pid_t) u;
2163 else if (streq(name, "ExecMainPID")) {
2164 if (u > 0)
2165 i->main_pid = (pid_t) u;
2166 } else if (streq(name, "NAccepted"))
2167 i->n_accepted = u;
2168 else if (streq(name, "NConnections"))
2169 i->n_connections = u;
2170
2171 break;
2172 }
2173
2174 case DBUS_TYPE_INT32: {
2175 int32_t j;
2176
2177 dbus_message_iter_get_basic(iter, &j);
2178
2179 if (streq(name, "ExecMainCode"))
2180 i->exit_code = (int) j;
2181 else if (streq(name, "ExecMainStatus"))
2182 i->exit_status = (int) j;
2183
2184 break;
2185 }
2186
2187 case DBUS_TYPE_UINT64: {
2188 uint64_t u;
2189
2190 dbus_message_iter_get_basic(iter, &u);
2191
2192 if (streq(name, "ExecMainStartTimestamp"))
2193 i->start_timestamp = (usec_t) u;
2194 else if (streq(name, "ExecMainExitTimestamp"))
2195 i->exit_timestamp = (usec_t) u;
584be568
LP
2196 else if (streq(name, "ActiveEnterTimestamp"))
2197 i->active_enter_timestamp = (usec_t) u;
2198 else if (streq(name, "InactiveEnterTimestamp"))
2199 i->inactive_enter_timestamp = (usec_t) u;
2200 else if (streq(name, "InactiveExitTimestamp"))
2201 i->inactive_exit_timestamp = (usec_t) u;
2202 else if (streq(name, "ActiveExitTimestamp"))
2203 i->active_exit_timestamp = (usec_t) u;
90bbc946
LP
2204 else if (streq(name, "ConditionTimestamp"))
2205 i->condition_timestamp = (usec_t) u;
61cbdc4b
LP
2206
2207 break;
2208 }
582a507f
LP
2209
2210 case DBUS_TYPE_ARRAY: {
2211
2212 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT &&
2213 startswith(name, "Exec")) {
2214 DBusMessageIter sub;
2215
2216 dbus_message_iter_recurse(iter, &sub);
2217 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2218 ExecStatusInfo *info;
2219 int r;
2220
2221 if (!(info = new0(ExecStatusInfo, 1)))
2222 return -ENOMEM;
2223
0129173a
LP
2224 if (!(info->name = strdup(name))) {
2225 free(info);
2226 return -ENOMEM;
2227 }
2228
582a507f
LP
2229 if ((r = exec_status_info_deserialize(&sub, info)) < 0) {
2230 free(info);
2231 return r;
2232 }
2233
2234 LIST_PREPEND(ExecStatusInfo, exec, i->exec, info);
2235
2236 dbus_message_iter_next(&sub);
2237 }
2238 }
2239
2240 break;
2241 }
61cbdc4b
LP
2242 }
2243
2244 return 0;
2245}
2246
48220598
LP
2247static int print_property(const char *name, DBusMessageIter *iter) {
2248 assert(name);
2249 assert(iter);
2250
61cbdc4b
LP
2251 /* This is a low-level property printer, see
2252 * print_status_info() for the nicer output */
2253
ea4a240d 2254 if (arg_property && !strv_find(arg_property, name))
48220598
LP
2255 return 0;
2256
2257 switch (dbus_message_iter_get_arg_type(iter)) {
2258
2259 case DBUS_TYPE_STRING: {
2260 const char *s;
2261 dbus_message_iter_get_basic(iter, &s);
2262
2263 if (arg_all || s[0])
2264 printf("%s=%s\n", name, s);
2265
2266 return 0;
2267 }
2268
2269 case DBUS_TYPE_BOOLEAN: {
2270 dbus_bool_t b;
2271 dbus_message_iter_get_basic(iter, &b);
2272 printf("%s=%s\n", name, yes_no(b));
2273
2274 return 0;
2275 }
2276
2277 case DBUS_TYPE_UINT64: {
2278 uint64_t u;
2279 dbus_message_iter_get_basic(iter, &u);
2280
2281 /* Yes, heuristics! But we can change this check
2282 * should it turn out to not be sufficient */
2283
b21a0ef8 2284 if (endswith(name, "Timestamp")) {
48220598
LP
2285 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
2286
2287 if ((t = format_timestamp(timestamp, sizeof(timestamp), u)) || arg_all)
2288 printf("%s=%s\n", name, strempty(t));
552e4331
LP
2289 } else if (strstr(name, "USec")) {
2290 char timespan[FORMAT_TIMESPAN_MAX];
2291
2292 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
48220598
LP
2293 } else
2294 printf("%s=%llu\n", name, (unsigned long long) u);
2295
2296 return 0;
2297 }
2298
2299 case DBUS_TYPE_UINT32: {
2300 uint32_t u;
2301 dbus_message_iter_get_basic(iter, &u);
2302
5bd07073 2303 if (strstr(name, "UMask") || strstr(name, "Mode"))
48220598
LP
2304 printf("%s=%04o\n", name, u);
2305 else
2306 printf("%s=%u\n", name, (unsigned) u);
2307
2308 return 0;
2309 }
2310
2311 case DBUS_TYPE_INT32: {
2312 int32_t i;
2313 dbus_message_iter_get_basic(iter, &i);
2314
2315 printf("%s=%i\n", name, (int) i);
2316 return 0;
2317 }
2318
05d6a3b6
LP
2319 case DBUS_TYPE_DOUBLE: {
2320 double d;
2321 dbus_message_iter_get_basic(iter, &d);
2322
2323 printf("%s=%g\n", name, d);
2324 return 0;
2325 }
2326
48220598
LP
2327 case DBUS_TYPE_STRUCT: {
2328 DBusMessageIter sub;
2329 dbus_message_iter_recurse(iter, &sub);
2330
ebf57b80 2331 if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_UINT32 && streq(name, "Job")) {
48220598
LP
2332 uint32_t u;
2333
2334 dbus_message_iter_get_basic(&sub, &u);
2335
2336 if (u)
2337 printf("%s=%u\n", name, (unsigned) u);
2338 else if (arg_all)
2339 printf("%s=\n", name);
2340
2341 return 0;
ebf57b80 2342 } else if (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING && streq(name, "Unit")) {
48220598
LP
2343 const char *s;
2344
2345 dbus_message_iter_get_basic(&sub, &s);
2346
2347 if (arg_all || s[0])
2348 printf("%s=%s\n", name, s);
2349
2350 return 0;
2351 }
2352
2353 break;
2354 }
2355
2356 case DBUS_TYPE_ARRAY:
2357
2358 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
2359 DBusMessageIter sub;
2360 bool space = false;
2361
2362 dbus_message_iter_recurse(iter, &sub);
48220598
LP
2363 if (arg_all ||
2364 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2365 printf("%s=", name);
2366
2367 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2368 const char *s;
2369
2370 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
2371 dbus_message_iter_get_basic(&sub, &s);
2372 printf("%s%s", space ? " " : "", s);
2373
2374 space = true;
2375 dbus_message_iter_next(&sub);
2376 }
2377
2378 puts("");
2379 }
2380
ebf57b80 2381 return 0;
582a507f 2382
82c121a4
LP
2383 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
2384 DBusMessageIter sub;
2385
2386 dbus_message_iter_recurse(iter, &sub);
82c121a4
LP
2387 if (arg_all ||
2388 dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2389 printf("%s=", name);
2390
2391 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2392 uint8_t u;
ebf57b80 2393
82c121a4
LP
2394 assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
2395 dbus_message_iter_get_basic(&sub, &u);
2396 printf("%02x", u);
2397
2398 dbus_message_iter_next(&sub);
2399 }
2400
2401 puts("");
2402 }
2403
2404 return 0;
582a507f 2405
8c7be95e
LP
2406 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "EnvironmentFiles")) {
2407 DBusMessageIter sub, sub2;
2408
2409 dbus_message_iter_recurse(iter, &sub);
2410 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2411 const char *path;
2412 dbus_bool_t ignore;
2413
2414 dbus_message_iter_recurse(&sub, &sub2);
2415
2416 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, true) >= 0 &&
2417 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_BOOLEAN, &ignore, false) >= 0)
2418 printf("EnvironmentFile=%s (ignore=%s)\n", path, yes_no(ignore));
2419
2420 dbus_message_iter_next(&sub);
2421 }
2422
2423 return 0;
2424
ebf57b80
LP
2425 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Paths")) {
2426 DBusMessageIter sub, sub2;
2427
2428 dbus_message_iter_recurse(iter, &sub);
ebf57b80
LP
2429 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2430 const char *type, *path;
2431
2432 dbus_message_iter_recurse(&sub, &sub2);
2433
2434 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) >= 0 &&
2435 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &path, false) >= 0)
2436 printf("%s=%s\n", type, path);
2437
2438 dbus_message_iter_next(&sub);
2439 }
2440
707e5e52 2441 return 0;
582a507f 2442
707e5e52
LP
2443 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && streq(name, "Timers")) {
2444 DBusMessageIter sub, sub2;
2445
2446 dbus_message_iter_recurse(iter, &sub);
707e5e52
LP
2447 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
2448 const char *base;
2449 uint64_t value, next_elapse;
2450
2451 dbus_message_iter_recurse(&sub, &sub2);
2452
2453 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &base, true) >= 0 &&
2454 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &value, true) >= 0 &&
552e4331
LP
2455 bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT64, &next_elapse, false) >= 0) {
2456 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
2457
2458 printf("%s={ value=%s ; next_elapse=%s }\n",
fe68089d 2459 base,
552e4331
LP
2460 format_timespan(timespan1, sizeof(timespan1), value),
2461 format_timespan(timespan2, sizeof(timespan2), next_elapse));
2462 }
fe68089d
LP
2463
2464 dbus_message_iter_next(&sub);
2465 }
2466
2467 return 0;
fe68089d 2468
582a507f
LP
2469 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRUCT && startswith(name, "Exec")) {
2470 DBusMessageIter sub;
fe68089d
LP
2471
2472 dbus_message_iter_recurse(iter, &sub);
fe68089d 2473 while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRUCT) {
582a507f 2474 ExecStatusInfo info;
fe68089d 2475
582a507f
LP
2476 zero(info);
2477 if (exec_status_info_deserialize(&sub, &info) >= 0) {
fe68089d 2478 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
582a507f
LP
2479 char *t;
2480
2481 t = strv_join(info.argv, " ");
2482
b708e7ce 2483 printf("%s={ path=%s ; argv[]=%s ; ignore=%s ; start_time=[%s] ; stop_time=[%s] ; pid=%u ; code=%s ; status=%i%s%s }\n",
582a507f
LP
2484 name,
2485 strna(info.path),
2486 strna(t),
b708e7ce 2487 yes_no(info.ignore),
582a507f
LP
2488 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
2489 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
2490 (unsigned) info. pid,
2491 sigchld_code_to_string(info.code),
2492 info.status,
2493 info.code == CLD_EXITED ? "" : "/",
2494 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
fe68089d 2495
582a507f 2496 free(t);
fe68089d
LP
2497 }
2498
582a507f
LP
2499 free(info.path);
2500 strv_free(info.argv);
707e5e52
LP
2501
2502 dbus_message_iter_next(&sub);
2503 }
2504
48220598
LP
2505 return 0;
2506 }
2507
2508 break;
2509 }
2510
2511 if (arg_all)
2512 printf("%s=[unprintable]\n", name);
2513
2514 return 0;
2515}
2516
be8088a2 2517static int show_one(const char *verb, DBusConnection *bus, const char *path, bool show_properties, bool *new_line) {
48220598
LP
2518 DBusMessage *m = NULL, *reply = NULL;
2519 const char *interface = "";
2520 int r;
2521 DBusError error;
2522 DBusMessageIter iter, sub, sub2, sub3;
61cbdc4b 2523 UnitStatusInfo info;
582a507f 2524 ExecStatusInfo *p;
48220598
LP
2525
2526 assert(bus);
2527 assert(path);
61cbdc4b 2528 assert(new_line);
48220598 2529
61cbdc4b 2530 zero(info);
48220598
LP
2531 dbus_error_init(&error);
2532
2533 if (!(m = dbus_message_new_method_call(
2534 "org.freedesktop.systemd1",
2535 path,
2536 "org.freedesktop.DBus.Properties",
2537 "GetAll"))) {
2538 log_error("Could not allocate message.");
2539 r = -ENOMEM;
2540 goto finish;
2541 }
2542
2543 if (!dbus_message_append_args(m,
2544 DBUS_TYPE_STRING, &interface,
2545 DBUS_TYPE_INVALID)) {
2546 log_error("Could not append arguments to message.");
2547 r = -ENOMEM;
2548 goto finish;
2549 }
2550
2551 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 2552 log_error("Failed to issue method call: %s", bus_error_message(&error));
48220598
LP
2553 r = -EIO;
2554 goto finish;
2555 }
2556
2557 if (!dbus_message_iter_init(reply, &iter) ||
2558 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
2559 dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY) {
2560 log_error("Failed to parse reply.");
2561 r = -EIO;
2562 goto finish;
2563 }
2564
2565 dbus_message_iter_recurse(&iter, &sub);
2566
61cbdc4b
LP
2567 if (*new_line)
2568 printf("\n");
2569
2570 *new_line = true;
2571
48220598
LP
2572 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
2573 const char *name;
2574
2575 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
2576 log_error("Failed to parse reply.");
2577 r = -EIO;
2578 goto finish;
2579 }
2580
2581 dbus_message_iter_recurse(&sub, &sub2);
0183528f 2582
48220598
LP
2583 if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0) {
2584 log_error("Failed to parse reply.");
2585 r = -EIO;
2586 goto finish;
2587 }
2588
2589 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT) {
2590 log_error("Failed to parse reply.");
2591 r = -EIO;
2592 goto finish;
2593 }
2594
2595 dbus_message_iter_recurse(&sub2, &sub3);
2596
61cbdc4b
LP
2597 if (show_properties)
2598 r = print_property(name, &sub3);
2599 else
2600 r = status_property(name, &sub3, &info);
2601
2602 if (r < 0) {
48220598
LP
2603 log_error("Failed to parse reply.");
2604 r = -EIO;
2605 goto finish;
2606 }
2607
2608 dbus_message_iter_next(&sub);
2609 }
2610
f1e36d67
LP
2611 r = 0;
2612
22f4096c
LP
2613 if (!show_properties)
2614 print_status_info(&info);
f1e36d67 2615
22f4096c 2616 if (!streq_ptr(info.active_state, "active") &&
be8088a2
LP
2617 !streq_ptr(info.active_state, "reloading") &&
2618 streq(verb, "status"))
22f4096c
LP
2619 /* According to LSB: "program not running" */
2620 r = 3;
61cbdc4b 2621
582a507f
LP
2622 while ((p = info.exec)) {
2623 LIST_REMOVE(ExecStatusInfo, exec, info.exec, p);
2624 exec_status_info_free(p);
2625 }
2626
48220598
LP
2627finish:
2628 if (m)
2629 dbus_message_unref(m);
2630
2631 if (reply)
2632 dbus_message_unref(reply);
2633
2634 dbus_error_free(&error);
2635
2636 return r;
2637}
2638
2639static int show(DBusConnection *bus, char **args, unsigned n) {
2640 DBusMessage *m = NULL, *reply = NULL;
22f4096c 2641 int r, ret = 0;
48220598
LP
2642 DBusError error;
2643 unsigned i;
61cbdc4b 2644 bool show_properties, new_line = false;
48220598
LP
2645
2646 assert(bus);
2647 assert(args);
2648
2649 dbus_error_init(&error);
2650
61cbdc4b
LP
2651 show_properties = !streq(args[0], "status");
2652
ec14911e
LP
2653 if (show_properties)
2654 pager_open();
2655
61cbdc4b 2656 if (show_properties && n <= 1) {
48220598
LP
2657 /* If not argument is specified inspect the manager
2658 * itself */
2659
be8088a2 2660 ret = show_one(args[0], bus, "/org/freedesktop/systemd1", show_properties, &new_line);
48220598
LP
2661 goto finish;
2662 }
2663
2664 for (i = 1; i < n; i++) {
2665 const char *path = NULL;
2666 uint32_t id;
2667
598b557b
LP
2668 if (safe_atou32(args[i], &id) < 0) {
2669
2670 /* Interpret as unit name */
48220598
LP
2671
2672 if (!(m = dbus_message_new_method_call(
2673 "org.freedesktop.systemd1",
2674 "/org/freedesktop/systemd1",
2675 "org.freedesktop.systemd1.Manager",
e87d1818 2676 "LoadUnit"))) {
48220598 2677 log_error("Could not allocate message.");
22f4096c 2678 ret = -ENOMEM;
48220598
LP
2679 goto finish;
2680 }
2681
2682 if (!dbus_message_append_args(m,
2683 DBUS_TYPE_STRING, &args[i],
2684 DBUS_TYPE_INVALID)) {
2685 log_error("Could not append arguments to message.");
22f4096c 2686 ret = -ENOMEM;
48220598
LP
2687 goto finish;
2688 }
2689
ed2d7a44
LP
2690 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
2691
2692 if (!dbus_error_has_name(&error, DBUS_ERROR_ACCESS_DENIED)) {
4cf5d675 2693 log_error("Failed to issue method call: %s", bus_error_message(&error));
22f4096c 2694 ret = -EIO;
ed2d7a44
LP
2695 goto finish;
2696 }
2697
2698 dbus_error_free(&error);
2699
2700 dbus_message_unref(m);
2701 if (!(m = dbus_message_new_method_call(
2702 "org.freedesktop.systemd1",
2703 "/org/freedesktop/systemd1",
2704 "org.freedesktop.systemd1.Manager",
2705 "GetUnit"))) {
2706 log_error("Could not allocate message.");
22f4096c 2707 ret = -ENOMEM;
ed2d7a44
LP
2708 goto finish;
2709 }
2710
2711 if (!dbus_message_append_args(m,
2712 DBUS_TYPE_STRING, &args[i],
2713 DBUS_TYPE_INVALID)) {
2714 log_error("Could not append arguments to message.");
22f4096c 2715 ret = -ENOMEM;
ed2d7a44
LP
2716 goto finish;
2717 }
2718
2719 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 2720 log_error("Failed to issue method call: %s", bus_error_message(&error));
22f4096c
LP
2721
2722 if (dbus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT))
2723 ret = 4; /* According to LSB: "program or service status is unknown" */
2724 else
2725 ret = -EIO;
ed2d7a44
LP
2726 goto finish;
2727 }
2728 }
2729
598b557b
LP
2730 } else if (show_properties) {
2731
2732 /* Interpret as job id */
48220598
LP
2733
2734 if (!(m = dbus_message_new_method_call(
2735 "org.freedesktop.systemd1",
2736 "/org/freedesktop/systemd1",
2737 "org.freedesktop.systemd1.Manager",
2738 "GetJob"))) {
2739 log_error("Could not allocate message.");
22f4096c 2740 ret = -ENOMEM;
48220598
LP
2741 goto finish;
2742 }
2743
2744 if (!dbus_message_append_args(m,
2745 DBUS_TYPE_UINT32, &id,
2746 DBUS_TYPE_INVALID)) {
2747 log_error("Could not append arguments to message.");
22f4096c 2748 ret = -ENOMEM;
48220598
LP
2749 goto finish;
2750 }
48220598 2751
598b557b 2752 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 2753 log_error("Failed to issue method call: %s", bus_error_message(&error));
22f4096c 2754 ret = -EIO;
598b557b
LP
2755 goto finish;
2756 }
2757 } else {
2758
2759 /* Interpret as PID */
2760
2761 if (!(m = dbus_message_new_method_call(
2762 "org.freedesktop.systemd1",
2763 "/org/freedesktop/systemd1",
2764 "org.freedesktop.systemd1.Manager",
2765 "GetUnitByPID"))) {
2766 log_error("Could not allocate message.");
22f4096c 2767 ret = -ENOMEM;
598b557b
LP
2768 goto finish;
2769 }
2770
2771 if (!dbus_message_append_args(m,
2772 DBUS_TYPE_UINT32, &id,
2773 DBUS_TYPE_INVALID)) {
2774 log_error("Could not append arguments to message.");
22f4096c 2775 ret = -ENOMEM;
598b557b
LP
2776 goto finish;
2777 }
2778
ed2d7a44 2779 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 2780 log_error("Failed to issue method call: %s", bus_error_message(&error));
22f4096c 2781 ret = -EIO;
ed2d7a44
LP
2782 goto finish;
2783 }
48220598
LP
2784 }
2785
2786 if (!dbus_message_get_args(reply, &error,
2787 DBUS_TYPE_OBJECT_PATH, &path,
2788 DBUS_TYPE_INVALID)) {
4cf5d675 2789 log_error("Failed to parse reply: %s", bus_error_message(&error));
22f4096c 2790 ret = -EIO;
48220598
LP
2791 goto finish;
2792 }
2793
be8088a2 2794 if ((r = show_one(args[0], bus, path, show_properties, &new_line)) != 0)
22f4096c 2795 ret = r;
48220598
LP
2796
2797 dbus_message_unref(m);
2798 dbus_message_unref(reply);
2799 m = reply = NULL;
2800 }
2801
48220598
LP
2802finish:
2803 if (m)
2804 dbus_message_unref(m);
2805
2806 if (reply)
2807 dbus_message_unref(reply);
2808
2809 dbus_error_free(&error);
2810
22f4096c 2811 return ret;
0183528f
LP
2812}
2813
7e4249b9
LP
2814static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
2815 DBusError error;
2816 DBusMessage *m = NULL, *reply = NULL;
2817
2818 assert(connection);
2819 assert(message);
2820
2821 dbus_error_init(&error);
2822
54165a39
LP
2823 log_debug("Got D-Bus request: %s.%s() on %s",
2824 dbus_message_get_interface(message),
2825 dbus_message_get_member(message),
2826 dbus_message_get_path(message));
7e4249b9
LP
2827
2828 if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
2829 log_error("Warning! D-Bus connection terminated.");
2830 dbus_connection_close(connection);
2831
2832 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitNew") ||
2833 dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "UnitRemoved")) {
2834 const char *id, *path;
2835
2836 if (!dbus_message_get_args(message, &error,
2837 DBUS_TYPE_STRING, &id,
2838 DBUS_TYPE_OBJECT_PATH, &path,
2839 DBUS_TYPE_INVALID))
4cf5d675 2840 log_error("Failed to parse message: %s", bus_error_message(&error));
7e4249b9
LP
2841 else if (streq(dbus_message_get_member(message), "UnitNew"))
2842 printf("Unit %s added.\n", id);
2843 else
2844 printf("Unit %s removed.\n", id);
2845
017803e2
LP
2846 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobNew")) {
2847 uint32_t id;
2848 const char *path;
2849
2850 if (!dbus_message_get_args(message, &error,
2851 DBUS_TYPE_UINT32, &id,
2852 DBUS_TYPE_OBJECT_PATH, &path,
2853 DBUS_TYPE_INVALID))
2854 log_error("Failed to parse message: %s", bus_error_message(&error));
2855 else
2856 printf("Job %u added.\n", id);
2857
2858
2859 } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
7e4249b9 2860 uint32_t id;
5d44db4a 2861 const char *path, *result;
7e4249b9
LP
2862
2863 if (!dbus_message_get_args(message, &error,
2864 DBUS_TYPE_UINT32, &id,
2865 DBUS_TYPE_OBJECT_PATH, &path,
5d44db4a 2866 DBUS_TYPE_STRING, &result,
7e4249b9 2867 DBUS_TYPE_INVALID))
4cf5d675 2868 log_error("Failed to parse message: %s", bus_error_message(&error));
7e4249b9 2869 else
017803e2 2870 printf("Job %u removed (result=%s).\n", id, result);
7e4249b9
LP
2871
2872
c4e2ceae 2873 } else if (dbus_message_is_signal(message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
7e4249b9
LP
2874
2875 const char *path, *interface, *property = "Id";
2876 DBusMessageIter iter, sub;
2877
2878 path = dbus_message_get_path(message);
c4e2ceae
LP
2879
2880 if (!dbus_message_get_args(message, &error,
2881 DBUS_TYPE_STRING, &interface,
2882 DBUS_TYPE_INVALID)) {
4cf5d675 2883 log_error("Failed to parse message: %s", bus_error_message(&error));
c4e2ceae
LP
2884 goto finish;
2885 }
2886
2887 if (!streq(interface, "org.freedesktop.systemd1.Job") &&
2888 !streq(interface, "org.freedesktop.systemd1.Unit"))
2889 goto finish;
7e4249b9
LP
2890
2891 if (!(m = dbus_message_new_method_call(
2892 "org.freedesktop.systemd1",
2893 path,
2894 "org.freedesktop.DBus.Properties",
2895 "Get"))) {
2896 log_error("Could not allocate message.");
2897 goto oom;
2898 }
2899
2900 if (!dbus_message_append_args(m,
2901 DBUS_TYPE_STRING, &interface,
2902 DBUS_TYPE_STRING, &property,
2903 DBUS_TYPE_INVALID)) {
2904 log_error("Could not append arguments to message.");
2905 goto finish;
2906 }
2907
2908 if (!(reply = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) {
4cf5d675 2909 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
2910 goto finish;
2911 }
2912
2913 if (!dbus_message_iter_init(reply, &iter) ||
2914 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
2915 log_error("Failed to parse reply.");
2916 goto finish;
2917 }
2918
2919 dbus_message_iter_recurse(&iter, &sub);
2920
2921 if (streq(interface, "org.freedesktop.systemd1.Unit")) {
2922 const char *id;
2923
2924 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
2925 log_error("Failed to parse reply.");
2926 goto finish;
2927 }
2928
2929 dbus_message_iter_get_basic(&sub, &id);
2930 printf("Unit %s changed.\n", id);
2931 } else {
2932 uint32_t id;
2933
2934 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32) {
2935 log_error("Failed to parse reply.");
2936 goto finish;
2937 }
2938
2939 dbus_message_iter_get_basic(&sub, &id);
2940 printf("Job %u changed.\n", id);
2941 }
2942 }
2943
2944finish:
2945 if (m)
2946 dbus_message_unref(m);
2947
2948 if (reply)
2949 dbus_message_unref(reply);
2950
2951 dbus_error_free(&error);
2952 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2953
2954oom:
2955 if (m)
2956 dbus_message_unref(m);
2957
2958 if (reply)
2959 dbus_message_unref(reply);
2960
2961 dbus_error_free(&error);
2962 return DBUS_HANDLER_RESULT_NEED_MEMORY;
2963}
2964
2965static int monitor(DBusConnection *bus, char **args, unsigned n) {
2966 DBusMessage *m = NULL, *reply = NULL;
2967 DBusError error;
2968 int r;
2969
2970 dbus_error_init(&error);
2971
f4579ce7
LP
2972 if (!private_bus) {
2973 dbus_bus_add_match(bus,
2974 "type='signal',"
2975 "sender='org.freedesktop.systemd1',"
2976 "interface='org.freedesktop.systemd1.Manager',"
2977 "path='/org/freedesktop/systemd1'",
2978 &error);
7e4249b9 2979
f4579ce7 2980 if (dbus_error_is_set(&error)) {
4cf5d675 2981 log_error("Failed to add match: %s", bus_error_message(&error));
f4579ce7
LP
2982 r = -EIO;
2983 goto finish;
2984 }
7e4249b9 2985
f4579ce7
LP
2986 dbus_bus_add_match(bus,
2987 "type='signal',"
2988 "sender='org.freedesktop.systemd1',"
c4e2ceae
LP
2989 "interface='org.freedesktop.DBus.Properties',"
2990 "member='PropertiesChanged'",
f4579ce7 2991 &error);
7e4249b9 2992
f4579ce7 2993 if (dbus_error_is_set(&error)) {
4cf5d675 2994 log_error("Failed to add match: %s", bus_error_message(&error));
f4579ce7
LP
2995 r = -EIO;
2996 goto finish;
2997 }
7e4249b9
LP
2998 }
2999
3000 if (!dbus_connection_add_filter(bus, monitor_filter, NULL, NULL)) {
3001 log_error("Failed to add filter.");
3002 r = -ENOMEM;
3003 goto finish;
3004 }
3005
3006 if (!(m = dbus_message_new_method_call(
3007 "org.freedesktop.systemd1",
3008 "/org/freedesktop/systemd1",
3009 "org.freedesktop.systemd1.Manager",
3010 "Subscribe"))) {
3011 log_error("Could not allocate message.");
3012 r = -ENOMEM;
3013 goto finish;
3014 }
3015
3016 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3017 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
3018 r = -EIO;
3019 goto finish;
3020 }
3021
3022 while (dbus_connection_read_write_dispatch(bus, -1))
3023 ;
3024
3025 r = 0;
3026
3027finish:
3028
3029 /* This is slightly dirty, since we don't undo the filter or the matches. */
3030
3031 if (m)
3032 dbus_message_unref(m);
3033
3034 if (reply)
3035 dbus_message_unref(reply);
3036
3037 dbus_error_free(&error);
3038
3039 return r;
3040}
3041
3042static int dump(DBusConnection *bus, char **args, unsigned n) {
3043 DBusMessage *m = NULL, *reply = NULL;
3044 DBusError error;
3045 int r;
3046 const char *text;
3047
3048 dbus_error_init(&error);
3049
ec14911e
LP
3050 pager_open();
3051
7e4249b9
LP
3052 if (!(m = dbus_message_new_method_call(
3053 "org.freedesktop.systemd1",
3054 "/org/freedesktop/systemd1",
3055 "org.freedesktop.systemd1.Manager",
3056 "Dump"))) {
3057 log_error("Could not allocate message.");
3058 return -ENOMEM;
3059 }
3060
3061 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3062 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
3063 r = -EIO;
3064 goto finish;
3065 }
3066
3067 if (!dbus_message_get_args(reply, &error,
3068 DBUS_TYPE_STRING, &text,
3069 DBUS_TYPE_INVALID)) {
4cf5d675 3070 log_error("Failed to parse reply: %s", bus_error_message(&error));
7e4249b9
LP
3071 r = -EIO;
3072 goto finish;
3073 }
3074
3075 fputs(text, stdout);
3076
3077 r = 0;
3078
3079finish:
3080 if (m)
3081 dbus_message_unref(m);
3082
3083 if (reply)
3084 dbus_message_unref(reply);
3085
3086 dbus_error_free(&error);
3087
3088 return r;
3089}
3090
3091static int snapshot(DBusConnection *bus, char **args, unsigned n) {
3092 DBusMessage *m = NULL, *reply = NULL;
3093 DBusError error;
3094 int r;
3095 const char *name = "", *path, *id;
3096 dbus_bool_t cleanup = FALSE;
3097 DBusMessageIter iter, sub;
3098 const char
3099 *interface = "org.freedesktop.systemd1.Unit",
3100 *property = "Id";
3101
3102 dbus_error_init(&error);
3103
3104 if (!(m = dbus_message_new_method_call(
3105 "org.freedesktop.systemd1",
3106 "/org/freedesktop/systemd1",
3107 "org.freedesktop.systemd1.Manager",
3108 "CreateSnapshot"))) {
3109 log_error("Could not allocate message.");
3110 return -ENOMEM;
3111 }
3112
3113 if (n > 1)
3114 name = args[1];
3115
3116 if (!dbus_message_append_args(m,
3117 DBUS_TYPE_STRING, &name,
3118 DBUS_TYPE_BOOLEAN, &cleanup,
3119 DBUS_TYPE_INVALID)) {
3120 log_error("Could not append arguments to message.");
3121 r = -ENOMEM;
3122 goto finish;
3123 }
3124
3125 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3126 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
3127 r = -EIO;
3128 goto finish;
3129 }
3130
3131 if (!dbus_message_get_args(reply, &error,
3132 DBUS_TYPE_OBJECT_PATH, &path,
3133 DBUS_TYPE_INVALID)) {
4cf5d675 3134 log_error("Failed to parse reply: %s", bus_error_message(&error));
7e4249b9
LP
3135 r = -EIO;
3136 goto finish;
3137 }
3138
3139 dbus_message_unref(m);
3140 if (!(m = dbus_message_new_method_call(
3141 "org.freedesktop.systemd1",
3142 path,
3143 "org.freedesktop.DBus.Properties",
3144 "Get"))) {
3145 log_error("Could not allocate message.");
3146 return -ENOMEM;
3147 }
3148
3149 if (!dbus_message_append_args(m,
3150 DBUS_TYPE_STRING, &interface,
3151 DBUS_TYPE_STRING, &property,
3152 DBUS_TYPE_INVALID)) {
3153 log_error("Could not append arguments to message.");
3154 r = -ENOMEM;
3155 goto finish;
3156 }
3157
3158 dbus_message_unref(reply);
3159 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3160 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
3161 r = -EIO;
3162 goto finish;
3163 }
3164
3165 if (!dbus_message_iter_init(reply, &iter) ||
3166 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3167 log_error("Failed to parse reply.");
3168 r = -EIO;
3169 goto finish;
3170 }
3171
3172 dbus_message_iter_recurse(&iter, &sub);
3173
3174 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING) {
3175 log_error("Failed to parse reply.");
3176 r = -EIO;
3177 goto finish;
3178 }
3179
3180 dbus_message_iter_get_basic(&sub, &id);
0183528f
LP
3181
3182 if (!arg_quiet)
3183 puts(id);
7e4249b9
LP
3184 r = 0;
3185
3186finish:
3187 if (m)
3188 dbus_message_unref(m);
3189
3190 if (reply)
3191 dbus_message_unref(reply);
3192
3193 dbus_error_free(&error);
3194
3195 return r;
3196}
3197
6759e7a7
LP
3198static int delete_snapshot(DBusConnection *bus, char **args, unsigned n) {
3199 DBusMessage *m = NULL, *reply = NULL;
3200 int r;
3201 DBusError error;
3202 unsigned i;
3203
3204 assert(bus);
3205 assert(args);
3206
3207 dbus_error_init(&error);
3208
3209 for (i = 1; i < n; i++) {
3210 const char *path = NULL;
3211
3212 if (!(m = dbus_message_new_method_call(
3213 "org.freedesktop.systemd1",
3214 "/org/freedesktop/systemd1",
3215 "org.freedesktop.systemd1.Manager",
3216 "GetUnit"))) {
3217 log_error("Could not allocate message.");
3218 r = -ENOMEM;
3219 goto finish;
3220 }
3221
3222 if (!dbus_message_append_args(m,
3223 DBUS_TYPE_STRING, &args[i],
3224 DBUS_TYPE_INVALID)) {
3225 log_error("Could not append arguments to message.");
3226 r = -ENOMEM;
3227 goto finish;
3228 }
3229
3230 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3231 log_error("Failed to issue method call: %s", bus_error_message(&error));
6759e7a7
LP
3232 r = -EIO;
3233 goto finish;
3234 }
3235
3236 if (!dbus_message_get_args(reply, &error,
3237 DBUS_TYPE_OBJECT_PATH, &path,
3238 DBUS_TYPE_INVALID)) {
4cf5d675 3239 log_error("Failed to parse reply: %s", bus_error_message(&error));
6759e7a7
LP
3240 r = -EIO;
3241 goto finish;
3242 }
3243
3244 dbus_message_unref(m);
3245 if (!(m = dbus_message_new_method_call(
3246 "org.freedesktop.systemd1",
3247 path,
3248 "org.freedesktop.systemd1.Snapshot",
3249 "Remove"))) {
3250 log_error("Could not allocate message.");
3251 r = -ENOMEM;
3252 goto finish;
3253 }
3254
3255 dbus_message_unref(reply);
3256 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3257 log_error("Failed to issue method call: %s", bus_error_message(&error));
6759e7a7
LP
3258 r = -EIO;
3259 goto finish;
3260 }
3261
3262 dbus_message_unref(m);
3263 dbus_message_unref(reply);
3264 m = reply = NULL;
3265 }
3266
3267 r = 0;
3268
3269finish:
3270 if (m)
3271 dbus_message_unref(m);
3272
3273 if (reply)
3274 dbus_message_unref(reply);
3275
3276 dbus_error_free(&error);
3277
3278 return r;
3279}
3280
ee5762e3 3281static int daemon_reload(DBusConnection *bus, char **args, unsigned n) {
7e4249b9
LP
3282 DBusMessage *m = NULL, *reply = NULL;
3283 DBusError error;
3284 int r;
3285 const char *method;
3286
3287 dbus_error_init(&error);
3288
e4b61340
LP
3289 if (arg_action == ACTION_RELOAD)
3290 method = "Reload";
3291 else if (arg_action == ACTION_REEXEC)
3292 method = "Reexecute";
3293 else {
3294 assert(arg_action == ACTION_SYSTEMCTL);
3295
3296 method =
20b09ca7
LP
3297 streq(args[0], "clear-jobs") ||
3298 streq(args[0], "cancel") ? "ClearJobs" :
3299 streq(args[0], "daemon-reexec") ? "Reexecute" :
3300 streq(args[0], "reset-failed") ? "ResetFailed" :
3301 streq(args[0], "halt") ? "Halt" :
3302 streq(args[0], "poweroff") ? "PowerOff" :
3303 streq(args[0], "reboot") ? "Reboot" :
3304 streq(args[0], "kexec") ? "KExec" :
3305 streq(args[0], "exit") ? "Exit" :
3306 /* "daemon-reload" */ "Reload";
e4b61340 3307 }
7e4249b9
LP
3308
3309 if (!(m = dbus_message_new_method_call(
3310 "org.freedesktop.systemd1",
3311 "/org/freedesktop/systemd1",
3312 "org.freedesktop.systemd1.Manager",
3313 method))) {
3314 log_error("Could not allocate message.");
3315 return -ENOMEM;
3316 }
3317
3318 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
e4b61340
LP
3319
3320 if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
3321 /* There's always a fallback possible for
3322 * legacy actions. */
aabd9b11 3323 r = -EADDRNOTAVAIL;
e4b61340
LP
3324 goto finish;
3325 }
3326
b23de6af
LP
3327 if (streq(method, "Reexecute") && dbus_error_has_name(&error, DBUS_ERROR_NO_REPLY)) {
3328 /* On reexecution, we expect a disconnect, not
3329 * a reply */
3330 r = 0;
3331 goto finish;
3332 }
3333
4cf5d675 3334 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
3335 r = -EIO;
3336 goto finish;
3337 }
3338
aabd9b11 3339 r = 0;
7e4249b9
LP
3340
3341finish:
3342 if (m)
3343 dbus_message_unref(m);
3344
3345 if (reply)
3346 dbus_message_unref(reply);
3347
3348 dbus_error_free(&error);
3349
3350 return r;
3351}
3352
fdf20a31 3353static int reset_failed(DBusConnection *bus, char **args, unsigned n) {
5632e374
LP
3354 DBusMessage *m = NULL, *reply = NULL;
3355 unsigned i;
3356 int r;
3357 DBusError error;
3358
3359 assert(bus);
3360 dbus_error_init(&error);
3361
3362 if (n <= 1)
ee5762e3 3363 return daemon_reload(bus, args, n);
5632e374
LP
3364
3365 for (i = 1; i < n; i++) {
3366
3367 if (!(m = dbus_message_new_method_call(
3368 "org.freedesktop.systemd1",
3369 "/org/freedesktop/systemd1",
3370 "org.freedesktop.systemd1.Manager",
fdf20a31 3371 "ResetFailedUnit"))) {
5632e374
LP
3372 log_error("Could not allocate message.");
3373 r = -ENOMEM;
3374 goto finish;
3375 }
3376
3377 if (!dbus_message_append_args(m,
3378 DBUS_TYPE_STRING, args + i,
3379 DBUS_TYPE_INVALID)) {
3380 log_error("Could not append arguments to message.");
3381 r = -ENOMEM;
3382 goto finish;
3383 }
3384
3385 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3386 log_error("Failed to issue method call: %s", bus_error_message(&error));
5632e374
LP
3387 r = -EIO;
3388 goto finish;
3389 }
3390
3391 dbus_message_unref(m);
3392 dbus_message_unref(reply);
3393 m = reply = NULL;
3394 }
3395
3396 r = 0;
3397
3398finish:
3399 if (m)
3400 dbus_message_unref(m);
3401
3402 if (reply)
3403 dbus_message_unref(reply);
3404
3405 dbus_error_free(&error);
3406
3407 return r;
3408}
3409
7e4249b9
LP
3410static int show_enviroment(DBusConnection *bus, char **args, unsigned n) {
3411 DBusMessage *m = NULL, *reply = NULL;
3412 DBusError error;
3413 DBusMessageIter iter, sub, sub2;
3414 int r;
3415 const char
3416 *interface = "org.freedesktop.systemd1.Manager",
3417 *property = "Environment";
3418
3419 dbus_error_init(&error);
3420
ec14911e
LP
3421 pager_open();
3422
7e4249b9
LP
3423 if (!(m = dbus_message_new_method_call(
3424 "org.freedesktop.systemd1",
3425 "/org/freedesktop/systemd1",
3426 "org.freedesktop.DBus.Properties",
3427 "Get"))) {
3428 log_error("Could not allocate message.");
3429 return -ENOMEM;
3430 }
3431
3432 if (!dbus_message_append_args(m,
3433 DBUS_TYPE_STRING, &interface,
3434 DBUS_TYPE_STRING, &property,
3435 DBUS_TYPE_INVALID)) {
3436 log_error("Could not append arguments to message.");
3437 r = -ENOMEM;
3438 goto finish;
3439 }
3440
3441 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3442 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
3443 r = -EIO;
3444 goto finish;
3445 }
3446
3447 if (!dbus_message_iter_init(reply, &iter) ||
3448 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
3449 log_error("Failed to parse reply.");
3450 r = -EIO;
3451 goto finish;
3452 }
3453
3454 dbus_message_iter_recurse(&iter, &sub);
3455
3456 if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_ARRAY ||
3457 dbus_message_iter_get_element_type(&sub) != DBUS_TYPE_STRING) {
3458 log_error("Failed to parse reply.");
3459 r = -EIO;
3460 goto finish;
3461 }
3462
3463 dbus_message_iter_recurse(&sub, &sub2);
3464
3465 while (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_INVALID) {
3466 const char *text;
3467
3468 if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_STRING) {
3469 log_error("Failed to parse reply.");
3470 r = -EIO;
3471 goto finish;
3472 }
3473
3474 dbus_message_iter_get_basic(&sub2, &text);
3475 printf("%s\n", text);
3476
3477 dbus_message_iter_next(&sub2);
3478 }
3479
3480 r = 0;
3481
3482finish:
3483 if (m)
3484 dbus_message_unref(m);
3485
3486 if (reply)
3487 dbus_message_unref(reply);
3488
3489 dbus_error_free(&error);
3490
3491 return r;
3492}
3493
3494static int set_environment(DBusConnection *bus, char **args, unsigned n) {
3495 DBusMessage *m = NULL, *reply = NULL;
3496 DBusError error;
3497 int r;
3498 const char *method;
3499 DBusMessageIter iter, sub;
3500 unsigned i;
3501
3502 dbus_error_init(&error);
3503
3504 method = streq(args[0], "set-environment")
3505 ? "SetEnvironment"
3506 : "UnsetEnvironment";
3507
3508 if (!(m = dbus_message_new_method_call(
3509 "org.freedesktop.systemd1",
3510 "/org/freedesktop/systemd1",
3511 "org.freedesktop.systemd1.Manager",
3512 method))) {
3513
3514 log_error("Could not allocate message.");
3515 return -ENOMEM;
3516 }
3517
3518 dbus_message_iter_init_append(m, &iter);
3519
3520 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
3521 log_error("Could not append arguments to message.");
3522 r = -ENOMEM;
3523 goto finish;
3524 }
3525
3526 for (i = 1; i < n; i++)
3527 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &args[i])) {
3528 log_error("Could not append arguments to message.");
3529 r = -ENOMEM;
3530 goto finish;
3531 }
3532
3533 if (!dbus_message_iter_close_container(&iter, &sub)) {
3534 log_error("Could not append arguments to message.");
3535 r = -ENOMEM;
3536 goto finish;
3537 }
3538
3539 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
4cf5d675 3540 log_error("Failed to issue method call: %s", bus_error_message(&error));
7e4249b9
LP
3541 r = -EIO;
3542 goto finish;
3543 }
3544
3545 r = 0;
3546
3547finish:
3548 if (m)
3549 dbus_message_unref(m);
3550
3551 if (reply)
3552 dbus_message_unref(reply);
3553
3554 dbus_error_free(&error);
3555
3556 return r;
3557}
3558
ee5762e3
LP
3559typedef struct {
3560 char *name;
3561 char *path;
3562
3563 char **aliases;
3564 char **wanted_by;
3565} InstallInfo;
3566
3567static Hashmap *will_install = NULL, *have_installed = NULL;
3568static Set *remove_symlinks_to = NULL;
560d8f23 3569static unsigned n_symlinks = 0;
ee5762e3
LP
3570
3571static void install_info_free(InstallInfo *i) {
3572 assert(i);
3573
3574 free(i->name);
3575 free(i->path);
3576 strv_free(i->aliases);
3577 strv_free(i->wanted_by);
3578 free(i);
3579}
3580
3581static void install_info_hashmap_free(Hashmap *m) {
3582 InstallInfo *i;
3583
3584 while ((i = hashmap_steal_first(m)))
3585 install_info_free(i);
3586
3587 hashmap_free(m);
3588}
3589
ee5762e3
LP
3590static int install_info_add(const char *name) {
3591 InstallInfo *i;
3592 int r;
3593
3594 assert(will_install);
3595
b9c0d441 3596 if (!unit_name_is_valid_no_type(name, true)) {
71fad675 3597 log_warning("Unit name %s is not a valid unit name.", name);
ee5762e3 3598 return -EINVAL;
71fad675 3599 }
ee5762e3
LP
3600
3601 if (hashmap_get(have_installed, name) ||
3602 hashmap_get(will_install, name))
3603 return 0;
3604
3605 if (!(i = new0(InstallInfo, 1))) {
3606 r = -ENOMEM;
3607 goto fail;
3608 }
3609
3610 if (!(i->name = strdup(name))) {
3611 r = -ENOMEM;
3612 goto fail;
3613 }
3614
3615 if ((r = hashmap_put(will_install, i->name, i)) < 0)
3616 goto fail;
3617
3618 return 0;
3619
3620fail:
3621 if (i)
3622 install_info_free(i);
3623
3624 return r;
3625}
3626
3627static int config_parse_also(
3628 const char *filename,
3629 unsigned line,
3630 const char *section,
3631 const char *lvalue,
3731f1ea 3632 int ltype,
ee5762e3
LP
3633 const char *rvalue,
3634 void *data,
3635 void *userdata) {
3636
3637 char *w;
3638 size_t l;
3639 char *state;
3640
3641 assert(filename);
3642 assert(lvalue);
3643 assert(rvalue);
3644
3645 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
3646 char *n;
3647 int r;
3648
3649 if (!(n = strndup(w, l)))
3650 return -ENOMEM;
3651
71fad675
LP
3652 if ((r = install_info_add(n)) < 0) {
3653 log_warning("Cannot install unit %s: %s", n, strerror(-r));
3654 free(n);
ee5762e3 3655 return r;
71fad675
LP
3656 }
3657
3658 free(n);
ee5762e3
LP
3659 }
3660
3661 return 0;
3662}
3663
3664static int mark_symlink_for_removal(const char *p) {
3665 char *n;
3666 int r;
3667
3668 assert(p);
3669 assert(path_is_absolute(p));
3670
3671 if (!remove_symlinks_to)
3672 return 0;
3673
3674 if (!(n = strdup(p)))
3675 return -ENOMEM;
3676
3677 path_kill_slashes(n);
3678
3679 if ((r = set_put(remove_symlinks_to, n)) < 0) {
3680 free(n);
3681 return r == -EEXIST ? 0 : r;
3682 }
3683
3684 return 0;
3685}
3686
3687static int remove_marked_symlinks_fd(int fd, const char *config_path, const char *root, bool *deleted) {
3688 int r = 0;
3689 DIR *d;
3690 struct dirent *de;
3691
3692 assert(fd >= 0);
3693 assert(root);
3694 assert(deleted);
3695
3696 if (!(d = fdopendir(fd))) {
3697 close_nointr_nofail(fd);
3698 return -errno;
3699 }
3700
3701 rewinddir(d);
3702
3703 while ((de = readdir(d))) {
3704 bool is_dir = false, is_link = false;
3705
3706 if (ignore_file(de->d_name))
3707 continue;
3708
3709 if (de->d_type == DT_LNK)
3710 is_link = true;
3711 else if (de->d_type == DT_DIR)
3712 is_dir = true;
3713 else if (de->d_type == DT_UNKNOWN) {
3714 struct stat st;
3715
3716 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3717 log_error("Failed to stat %s/%s: %m", root, de->d_name);
3718
3719 if (r == 0)
3720 r = -errno;
3721 continue;
3722 }
3723
3724 is_link = S_ISLNK(st.st_mode);
3725 is_dir = S_ISDIR(st.st_mode);
3726 } else
3727 continue;
3728
3729 if (is_dir) {
3730 int nfd, q;
3731 char *p;
3732
3733 if ((nfd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0) {
3734 log_error("Failed to open %s/%s: %m", root, de->d_name);
3735
3736 if (r == 0)
3737 r = -errno;
3738 continue;
3739 }
3740
3741 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3742 log_error("Failed to allocate directory string.");
3743 close_nointr_nofail(nfd);
3744 r = -ENOMEM;
3745 break;
3746 }
3747
3748 /* This will close nfd, regardless whether it succeeds or not */
3749 q = remove_marked_symlinks_fd(nfd, config_path, p, deleted);
3750 free(p);
3751
3752 if (r == 0)
e364ad06 3753 r = q;
ee5762e3
LP
3754
3755 } else if (is_link) {
3756 char *p, *dest, *c;
3757 int q;
3758
3759 if (asprintf(&p, "%s/%s", root, de->d_name) < 0) {
3760 log_error("Failed to allocate symlink string.");
3761 r = -ENOMEM;
3762 break;
3763 }
3764
3765 if ((q = readlink_and_make_absolute(p, &dest)) < 0) {
3766 log_error("Cannot read symlink %s: %s", p, strerror(-q));
3767 free(p);
3768
3769 if (r == 0)
3770 r = q;
3771 continue;
3772 }
3773
3774 if ((c = canonicalize_file_name(dest))) {
3775 /* This might fail if the destination
3776 * is already removed */
3777
3778 free(dest);
3779 dest = c;
3780 }
3781
3782 path_kill_slashes(dest);
3783 if (set_get(remove_symlinks_to, dest)) {
3784
3785 if (!arg_quiet)
3786 log_info("rm '%s'", p);
3787
3788 if (unlink(p) < 0) {
3789 log_error("Cannot unlink symlink %s: %m", p);
3790
3791 if (r == 0)
3792 r = -errno;
3793 } else {
3794 rmdir_parents(p, config_path);
3795 path_kill_slashes(p);
3796
3797 if (!set_get(remove_symlinks_to, p)) {
3798
3799 if ((r = mark_symlink_for_removal(p)) < 0) {
3800 if (r == 0)
3801 r = q;
3802 } else
3803 *deleted = true;
3804 }
3805 }
3806 }
3807
3808 free(p);
3809 free(dest);
3810 }
3811 }
3812
3813 closedir(d);
3814
3815 return r;
3816}
3817
3818static int remove_marked_symlinks(const char *config_path) {
3819 int fd, r = 0;
3820 bool deleted;
3821
3822 assert(config_path);
3823
3824 if (set_size(remove_symlinks_to) <= 0)
3825 return 0;
3826
3827 if ((fd = open(config_path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW)) < 0)
3828 return -errno;
3829
3830 do {
3831 int q, cfd;
3832 deleted = false;
3833
3834 if ((cfd = dup(fd)) < 0) {
3835 r = -errno;
3836 break;
3837 }
3838
3839 /* This takes possession of cfd and closes it */
3840 if ((q = remove_marked_symlinks_fd(cfd, config_path, config_path, &deleted)) < 0) {
3841 if (r == 0)
3842 r = q;
3843 }
3844 } while (deleted);
3845
3846 close_nointr_nofail(fd);
3847
3848 return r;
3849}
3850
3851static int create_symlink(const char *verb, const char *old_path, const char *new_path) {
3852 int r;
3853
3854 assert(old_path);
3855 assert(new_path);
3856 assert(verb);
3857
3858 if (streq(verb, "enable")) {
3859 char *dest;
3860
3861 mkdir_parents(new_path, 0755);
3862
3863 if (symlink(old_path, new_path) >= 0) {
3864
3865 if (!arg_quiet)
3866 log_info("ln -s '%s' '%s'", old_path, new_path);
3867
3868 return 0;
3869 }
3870
3871 if (errno != EEXIST) {
3872 log_error("Cannot link %s to %s: %m", old_path, new_path);
3873 return -errno;
3874 }
3875
3876 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3877
3878 if (errno == EINVAL) {
3879 log_error("Cannot link %s to %s, file exists already and is not a symlink.", old_path, new_path);
3880 return -EEXIST;
3881 }
3882
3883 log_error("readlink() failed: %s", strerror(-r));
3884 return r;
3885 }
3886
3887 if (streq(dest, old_path)) {
3888 free(dest);
3889 return 0;
3890 }
3891
3892 if (!arg_force) {
3893 log_error("Cannot link %s to %s, symlink exists already and points to %s.", old_path, new_path, dest);
3894 free(dest);
3895 return -EEXIST;
3896 }
3897
3898 free(dest);
3899 unlink(new_path);
3900
3901 if (!arg_quiet)
3902 log_info("ln -s '%s' '%s'", old_path, new_path);
3903
3904 if (symlink(old_path, new_path) >= 0)
3905 return 0;
3906
3907 log_error("Cannot link %s to %s: %m", old_path, new_path);
3908 return -errno;
3909
3910 } else if (streq(verb, "disable")) {
3911 char *dest;
3912
3913 if ((r = mark_symlink_for_removal(old_path)) < 0)
3914 return r;
3915
3916 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3917 if (errno == ENOENT)
3918 return 0;
3919
3920 if (errno == EINVAL) {
3921 log_warning("File %s not a symlink, ignoring.", old_path);
3922 return 0;
3923 }
3924
3925 log_error("readlink() failed: %s", strerror(-r));
3926 return r;
3927 }
3928
3929 if (!streq(dest, old_path)) {
3930 log_warning("File %s not a symlink to %s but points to %s, ignoring.", new_path, old_path, dest);
3931 free(dest);
3932 return 0;
3933 }
3934
3935 free(dest);
3936
3937 if ((r = mark_symlink_for_removal(new_path)) < 0)
3938 return r;
3939
3940 if (!arg_quiet)
3941 log_info("rm '%s'", new_path);
3942
3943 if (unlink(new_path) >= 0)
3944 return 0;
3945
3946 log_error("Cannot unlink %s: %m", new_path);
3947 return -errno;
3948
3949 } else if (streq(verb, "is-enabled")) {
3950 char *dest;
3951
3952 if ((r = readlink_and_make_absolute(new_path, &dest)) < 0) {
3953
3954 if (errno == ENOENT || errno == EINVAL)
3955 return 0;
3956
3957 log_error("readlink() failed: %s", strerror(-r));
3958 return r;
3959 }
3960
3961 if (streq(dest, old_path)) {
3962 free(dest);
3963 return 1;
3964 }
3965
23b2a330 3966 free(dest);
ee5762e3
LP
3967 return 0;
3968 }
3969
3970 assert_not_reached("Unknown action.");
3971}
3972
3973static int install_info_symlink_alias(const char *verb, InstallInfo *i, const char *config_path) {
3974 char **s;
3975 char *alias_path = NULL;
3976 int r;
3977
3978 assert(verb);
3979 assert(i);
3980 assert(config_path);
3981
3982 STRV_FOREACH(s, i->aliases) {
3983
ee5762e3
LP
3984 free(alias_path);
3985 if (!(alias_path = path_make_absolute(*s, config_path))) {
3986 log_error("Out of memory");
3987 r = -ENOMEM;
3988 goto finish;
3989 }
3990
3991 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
3992 goto finish;
3993
3994 if (streq(verb, "disable"))
3995 rmdir_parents(alias_path, config_path);
3996 }
ee5762e3
LP
3997 r = 0;
3998
3999finish:
4000 free(alias_path);
4001
4002 return r;
4003}
4004
4005static int install_info_symlink_wants(const char *verb, InstallInfo *i, const char *config_path) {
4006 char **s;
4007 char *alias_path = NULL;
4008 int r;
4009
4010 assert(verb);
4011 assert(i);
4012 assert(config_path);
4013
4014 STRV_FOREACH(s, i->wanted_by) {
b9c0d441 4015 if (!unit_name_is_valid_no_type(*s, true)) {
ee5762e3
LP
4016 log_error("Invalid name %s.", *s);
4017 r = -EINVAL;
4018 goto finish;
4019 }
4020
4021 free(alias_path);
4022 alias_path = NULL;
4023
4024 if (asprintf(&alias_path, "%s/%s.wants/%s", config_path, *s, i->name) < 0) {
4025 log_error("Out of memory");
4026 r = -ENOMEM;
4027 goto finish;
4028 }
4029
4030 if ((r = create_symlink(verb, i->path, alias_path)) != 0)
4031 goto finish;
4032
4033 if (streq(verb, "disable"))
4034 rmdir_parents(alias_path, config_path);
4035 }
4036
4037 r = 0;
4038
4039finish:
4040 free(alias_path);
4041
4042 return r;
4043}
4044
4045static int install_info_apply(const char *verb, LookupPaths *paths, InstallInfo *i, const char *config_path) {
4046
4047 const ConfigItem items[] = {
2b583ce6
KS
4048 { "Alias", config_parse_strv, 0, &i->aliases, "Install" },
4049 { "WantedBy", config_parse_strv, 0, &i->wanted_by, "Install" },
4050 { "Also", config_parse_also, 0, NULL, "Install" },
ee5762e3 4051
2b583ce6 4052 { NULL, NULL, 0, NULL, NULL }
ee5762e3
LP
4053 };
4054
4055 char **p;
4056 char *filename = NULL;
4057 FILE *f = NULL;
4058 int r;
4059
4060 assert(paths);
4061 assert(i);
4062
4063 STRV_FOREACH(p, paths->unit_path) {
4064 int fd;
4065
4066 if (!(filename = path_make_absolute(i->name, *p))) {
4067 log_error("Out of memory");
4068 return -ENOMEM;
4069 }
4070
4071 /* Ensure that we don't follow symlinks */
4072 if ((fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOCTTY)) >= 0)
4073 if ((f = fdopen(fd, "re")))
4074 break;
4075
4076 if (errno == ELOOP) {
4077 log_error("Refusing to operate on symlinks, please pass unit names or absolute paths to unit files.");
4078 free(filename);
4079 return -errno;
4080 }
4081
4082 if (errno != ENOENT) {
4083 log_error("Failed to open %s: %m", filename);
4084 free(filename);
4085 return -errno;
4086 }
4087
4088 free(filename);
4089 filename = NULL;
4090 }
4091
4092 if (!f) {
d9eaa2d5 4093#if (defined(TARGET_FEDORA) || defined(TARGET_MANDRIVA) || defined(TARGET_SUSE) || defined(TARGET_MEEGO) || defined(TARGET_ALTLINUX)) && defined (HAVE_SYSV_COMPAT)
c8b2e52c
LP
4094
4095 if (endswith(i->name, ".service")) {
4096 char *sysv;
4097 bool exists;
4098
4099 if (asprintf(&sysv, SYSTEM_SYSVINIT_PATH "/%s", i->name) < 0) {
4100 log_error("Out of memory");
4101 return -ENOMEM;
4102 }
4103
4104 sysv[strlen(sysv) - sizeof(".service") + 1] = 0;
4105 exists = access(sysv, F_OK) >= 0;
4106
4107 if (exists) {
4108 pid_t pid;
4109 siginfo_t status;
4110
4111 const char *argv[] = {
4112 "/sbin/chkconfig",
4113 NULL,
4114 NULL,
4115 NULL
4116 };
4117
4118 log_info("%s is not a native service, redirecting to /sbin/chkconfig.", i->name);
4119
4120 argv[1] = file_name_from_path(sysv);
4121 argv[2] =
4122 streq(verb, "enable") ? "on" :
b74949bc 4123 streq(verb, "disable") ? "off" : "--level=5";
c8b2e52c
LP
4124
4125 log_info("Executing %s %s %s", argv[0], argv[1], strempty(argv[2]));
4126
4127 if ((pid = fork()) < 0) {
4128 log_error("Failed to fork: %m");
4129 free(sysv);
4130 return -errno;
4131 } else if (pid == 0) {
4132 execv(argv[0], (char**) argv);
4133 _exit(EXIT_FAILURE);
4134 }
4135
4136 free(sysv);
4137
4138 if ((r = wait_for_terminate(pid, &status)) < 0)
4139 return r;
4140
4141 if (status.si_code == CLD_EXITED) {
63a723f3
LP
4142
4143 if (streq(verb, "is-enabled"))
4144 return status.si_status == 0 ? 1 : 0;
4145
4146 if (status.si_status == 0)
c8b2e52c
LP
4147 n_symlinks ++;
4148
4149 return status.si_status == 0 ? 0 : -EINVAL;
63a723f3 4150
c8b2e52c
LP
4151 } else
4152 return -EPROTO;
4153 }
4154
4155 free(sysv);
4156 }
4157
4158#endif
4159
ee5762e3
LP
4160 log_error("Couldn't find %s.", i->name);
4161 return -ENOENT;
4162 }
4163
b77398f7
MS
4164 i->path = filename;
4165
4166 if ((r = config_parse(filename, f, NULL, items, true, i)) < 0) {
4167 fclose(f);
4168 return r;
4169 }
4170
3d3961f2
LP
4171 /* Consider unit files stored in /lib and /usr always enabled
4172 * if they have no [Install] data. */
4173 if (streq(verb, "is-enabled") &&
4174 strv_isempty(i->aliases) &&
4175 strv_isempty(i->wanted_by) &&
b647f10d
MS
4176 !path_startswith(filename, "/etc")) {
4177 fclose(f);
3d3961f2 4178 return 1;
b647f10d 4179 }
3d3961f2 4180
560d8f23
LP
4181 n_symlinks += strv_length(i->aliases);
4182 n_symlinks += strv_length(i->wanted_by);
4183
ee5762e3
LP
4184 fclose(f);
4185
4186 if ((r = install_info_symlink_alias(verb, i, config_path)) != 0)
4187 return r;
4188
4189 if ((r = install_info_symlink_wants(verb, i, config_path)) != 0)
4190 return r;
4191
4192 if ((r = mark_symlink_for_removal(filename)) < 0)
4193 return r;
4194
4195 if ((r = remove_marked_symlinks(config_path)) < 0)
4196 return r;
4197
4198 return 0;
4199}
4200
4201static char *get_config_path(void) {
4202
af2d49f7
LP
4203 if (arg_user && arg_global)
4204 return strdup(USER_CONFIG_UNIT_PATH);
ee5762e3 4205
af2d49f7 4206 if (arg_user) {
ee5762e3
LP
4207 char *p;
4208
af2d49f7 4209 if (user_config_home(&p) < 0)
ee5762e3
LP
4210 return NULL;
4211
4212 return p;
4213 }
4214
4215 return strdup(SYSTEM_CONFIG_UNIT_PATH);
4216}
4217
4218static int enable_unit(DBusConnection *bus, char **args, unsigned n) {
4219 DBusError error;
4220 int r;
4221 LookupPaths paths;
4222 char *config_path = NULL;
4223 unsigned j;
4224 InstallInfo *i;
4225 const char *verb = args[0];
4226
4227 dbus_error_init(&error);
4228
4229 zero(paths);
af2d49f7 4230 if ((r = lookup_paths_init(&paths, arg_user ? MANAGER_USER : MANAGER_SYSTEM)) < 0) {
ee5762e3
LP
4231 log_error("Failed to determine lookup paths: %s", strerror(-r));
4232 goto finish;
4233 }
4234
4235 if (!(config_path = get_config_path())) {
4236 log_error("Failed to determine config path");
4237 r = -ENOMEM;
4238 goto finish;
4239 }
4240
4241 will_install = hashmap_new(string_hash_func, string_compare_func);
4242 have_installed = hashmap_new(string_hash_func, string_compare_func);
4243
4244 if (!will_install || !have_installed) {
4245 log_error("Failed to allocate unit sets.");
4246 r = -ENOMEM;
4247 goto finish;
4248 }
4249
4250 if (!arg_defaults && streq(verb, "disable"))
4251 if (!(remove_symlinks_to = set_new(string_hash_func, string_compare_func))) {
4252 log_error("Failed to allocate symlink sets.");
4253 r = -ENOMEM;
4254 goto finish;
4255 }
4256
4257 for (j = 1; j < n; j++)
71fad675
LP
4258 if ((r = install_info_add(args[j])) < 0) {
4259 log_warning("Cannot install unit %s: %s", args[j], strerror(-r));
ee5762e3 4260 goto finish;
71fad675 4261 }
ee5762e3 4262
63a723f3
LP
4263 r = 0;
4264
ee5762e3
LP
4265 while ((i = hashmap_first(will_install))) {
4266 int q;
4267
4268 assert_se(hashmap_move_one(have_installed, will_install, i->name) == 0);
4269
4270 if ((q = install_info_apply(verb, &paths, i, config_path)) != 0) {
4271
4272 if (q < 0) {
4273 if (r == 0)
4274 r = q;
4275 goto finish;
4276 }
4277
4278 /* In test mode and found something */
4279 r = 1;
4280 break;
4281 }
4282 }
4283
4284 if (streq(verb, "is-enabled"))
4285 r = r > 0 ? 0 : -ENOENT;
560d8f23
LP
4286 else {
4287 if (n_symlinks <= 0)
4288 log_warning("Unit files contain no applicable installation information. Ignoring.");
4289
4290 if (bus &&
4291 /* Don't try to reload anything if the user asked us to not do this */
4292 !arg_no_reload &&
4293 /* Don't try to reload anything when updating a unit globally */
4294 !arg_global &&
4295 /* Don't try to reload anything if we are called for system changes but the system wasn't booted with systemd */
af2d49f7 4296 (arg_user || sd_booted() > 0) &&
560d8f23 4297 /* Don't try to reload anything if we are running in a chroot environment */
af2d49f7 4298 (arg_user || running_in_chroot() <= 0) ) {
560d8f23 4299 int q;
ee5762e3 4300
560d8f23
LP
4301 if ((q = daemon_reload(bus, args, n)) < 0)
4302 r = q;
4303 }
ee5762e3
LP
4304 }
4305
4306finish:
4307 install_info_hashmap_free(will_install);
4308 install_info_hashmap_free(have_installed);
4309
4310 set_free_free(remove_symlinks_to);
4311
4312 lookup_paths_free(&paths);
4313
4314 free(config_path);
4315
4316 return r;
4317}
4318
e4b61340 4319static int systemctl_help(void) {
7e4249b9 4320
2e33c433 4321 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
5632e374 4322 "Send control commands to or query the systemd manager.\n\n"
8a0867d6
LP
4323 " -h --help Show this help\n"
4324 " --version Show package version\n"
4325 " -t --type=TYPE List only units of a particular type\n"
4326 " -p --property=NAME Show only properties by this name\n"
4327 " -a --all Show all units/properties, including dead/empty ones\n"
30732560 4328 " --failed Show only failed units\n"
8a0867d6
LP
4329 " --full Don't ellipsize unit names on output\n"
4330 " --fail When queueing a new job, fail if conflicting jobs are\n"
4331 " pending\n"
e67c3609
LP
4332 " --ignore-dependencies\n"
4333 " When queueing a new job, ignore all its dependencies\n"
a8f11321
LP
4334 " --kill-mode=MODE How to send signal\n"
4335 " --kill-who=WHO Who to send signal to\n"
4336 " -s --signal=SIGNAL Which signal to send\n"
4337 " -H --host=[user@]host\n"
4338 " Show information for remote host\n"
4339 " -P --privileged Acquire privileges before execution\n"
8a0867d6
LP
4340 " -q --quiet Suppress output\n"
4341 " --no-block Do not wait until operation finished\n"
8a0867d6 4342 " --no-wall Don't send wall message before halt/power-off/reboot\n"
8a0867d6
LP
4343 " --no-reload When enabling/disabling unit files, don't reload daemon\n"
4344 " configuration\n"
a8f11321 4345 " --no-pager Do not pipe output into a pager.\n"
501fc174
LP
4346 " --no-ask-password\n"
4347 " Do not ask for system passwords\n"
a8f11321
LP
4348 " --order When generating graph for dot, show only order\n"
4349 " --require When generating graph for dot, show only requirement\n"
4350 " --system Connect to system manager\n"
4351 " --user Connect to user service manager\n"
4352 " --global Enable/disable unit files globally\n"
8a0867d6
LP
4353 " -f --force When enabling unit files, override existing symlinks\n"
4354 " When shutting down, execute action immediately\n"
4355 " --defaults When disabling unit files, remove default symlinks only\n\n"
7e4249b9
LP
4356 "Commands:\n"
4357 " list-units List units\n"
ee5762e3
LP
4358 " start [NAME...] Start (activate) one or more units\n"
4359 " stop [NAME...] Stop (deactivate) one or more units\n"
7e4249b9 4360 " reload [NAME...] Reload one or more units\n"
6f28c033
LP
4361 " restart [NAME...] Start or restart one or more units\n"
4362 " try-restart [NAME...] Restart one or more units if active\n"
4363 " reload-or-restart [NAME...] Reload one or more units is possible,\n"
4364 " otherwise start or restart\n"
4365 " reload-or-try-restart [NAME...] Reload one or more units is possible,\n"
4366 " otherwise restart if active\n"
7e4249b9 4367 " isolate [NAME] Start one unit and stop all others\n"
8a0867d6 4368 " kill [NAME...] Send signal to processes of a unit\n"
ee5762e3 4369 " is-active [NAME...] Check whether units are active\n"
75676b72 4370 " status [NAME...|PID...] Show runtime status of one or more units\n"
6f28c033 4371 " show [NAME...|JOB...] Show properties of one or more\n"
ee5762e3 4372 " units/jobs or the manager\n"
fdf20a31
MM
4373 " reset-failed [NAME...] Reset failed state for all, one, or more\n"
4374 " units\n"
ee5762e3
LP
4375 " enable [NAME...] Enable one or more unit files\n"
4376 " disable [NAME...] Disable one or more unit files\n"
4377 " is-enabled [NAME...] Check whether unit files are enabled\n"
48220598
LP
4378 " load [NAME...] Load one or more units\n"
4379 " list-jobs List jobs\n"
ee5762e3 4380 " cancel [JOB...] Cancel all, one, or more jobs\n"
7e4249b9
LP
4381 " monitor Monitor unit/job changes\n"
4382 " dump Dump server status\n"
4445a875 4383 " dot Dump dependency graph for dot(1)\n"
7e4249b9 4384 " snapshot [NAME] Create a snapshot\n"
6759e7a7 4385 " delete [NAME...] Remove one or more snapshots\n"
5ec7ed4e
LP
4386 " daemon-reload Reload systemd manager configuration\n"
4387 " daemon-reexec Reexecute systemd manager\n"
7e4249b9
LP
4388 " show-environment Dump environment\n"
4389 " set-environment [NAME=VALUE...] Set one or more environment variables\n"
514f4ef5 4390 " unset-environment [NAME...] Unset one or more environment variables\n"
20b09ca7
LP
4391 " default Enter system default mode\n"
4392 " rescue Enter system rescue mode\n"
4393 " emergency Enter system emergency mode\n"
514f4ef5 4394 " halt Shut down and halt the system\n"
2e33c433 4395 " poweroff Shut down and power-off the system\n"
514f4ef5 4396 " reboot Shut down and reboot the system\n"
20b09ca7 4397 " kexec Shut down and reboot the system with kexec\n"
af2d49f7 4398 " exit Ask for user instance termination\n",
5b6319dc 4399 program_invocation_short_name);
7e4249b9
LP
4400
4401 return 0;
4402}
4403
e4b61340
LP
4404static int halt_help(void) {
4405
2e33c433 4406 printf("%s [OPTIONS...]\n\n"
e4b61340
LP
4407 "%s the system.\n\n"
4408 " --help Show this help\n"
4409 " --halt Halt the machine\n"
4410 " -p --poweroff Switch off the machine\n"
4411 " --reboot Reboot the machine\n"
2e33c433
LP
4412 " -f --force Force immediate halt/power-off/reboot\n"
4413 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
e4b61340 4414 " -d --no-wtmp Don't write wtmp record\n"
2e33c433
LP
4415 " -n --no-sync Don't sync before halt/power-off/reboot\n"
4416 " --no-wall Don't send wall message before halt/power-off/reboot\n",
e4b61340
LP
4417 program_invocation_short_name,
4418 arg_action == ACTION_REBOOT ? "Reboot" :
4419 arg_action == ACTION_POWEROFF ? "Power off" :
4420 "Halt");
4421
4422 return 0;
4423}
4424
4425static int shutdown_help(void) {
4426
08e4b1c5 4427 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
e4b61340
LP
4428 "Shut down the system.\n\n"
4429 " --help Show this help\n"
4430 " -H --halt Halt the machine\n"
4431 " -P --poweroff Power-off the machine\n"
4432 " -r --reboot Reboot the machine\n"
4433 " -h Equivalent to --poweroff, overriden by --halt\n"
2e33c433 4434 " -k Don't halt/power-off/reboot, just send warnings\n"
f6144808 4435 " --no-wall Don't send wall message before halt/power-off/reboot\n"
f6144808 4436 " -c Cancel a pending shutdown\n",
e4b61340
LP
4437 program_invocation_short_name);
4438
4439 return 0;
4440}
4441
4442static int telinit_help(void) {
4443
2e33c433 4444 printf("%s [OPTIONS...] {COMMAND}\n\n"
514f4ef5
LP
4445 "Send control commands to the init daemon.\n\n"
4446 " --help Show this help\n"
2e33c433 4447 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
e4b61340
LP
4448 "Commands:\n"
4449 " 0 Power-off the machine\n"
4450 " 6 Reboot the machine\n"
514f4ef5
LP
4451 " 2, 3, 4, 5 Start runlevelX.target unit\n"
4452 " 1, s, S Enter rescue mode\n"
4453 " q, Q Reload init daemon configuration\n"
4454 " u, U Reexecute init daemon\n",
e4b61340
LP
4455 program_invocation_short_name);
4456
4457 return 0;
4458}
4459
4460static int runlevel_help(void) {
4461
2e33c433 4462 printf("%s [OPTIONS...]\n\n"
e4b61340
LP
4463 "Prints the previous and current runlevel of the init system.\n\n"
4464 " --help Show this help\n",
4465 program_invocation_short_name);
4466
4467 return 0;
4468}
4469
4470static int systemctl_parse_argv(int argc, char *argv[]) {
7e4249b9
LP
4471
4472 enum {
90d473a1 4473 ARG_FAIL = 0x100,
e67c3609 4474 ARG_IGNORE_DEPENDENCIES,
35df8f27 4475 ARG_VERSION,
af2d49f7 4476 ARG_USER,
7e4249b9 4477 ARG_SYSTEM,
ee5762e3 4478 ARG_GLOBAL,
6e905d93 4479 ARG_NO_BLOCK,
611efaac 4480 ARG_NO_PAGER,
4445a875
LP
4481 ARG_NO_WALL,
4482 ARG_ORDER,
8fe914ec 4483 ARG_REQUIRE,
ee5762e3 4484 ARG_FULL,
ee5762e3 4485 ARG_NO_RELOAD,
8a0867d6
LP
4486 ARG_DEFAULTS,
4487 ARG_KILL_MODE,
501fc174 4488 ARG_KILL_WHO,
30732560
LP
4489 ARG_NO_ASK_PASSWORD,
4490 ARG_FAILED
7e4249b9
LP
4491 };
4492
4493 static const struct option options[] = {
ee5762e3 4494 { "help", no_argument, NULL, 'h' },
35df8f27 4495 { "version", no_argument, NULL, ARG_VERSION },
ee5762e3
LP
4496 { "type", required_argument, NULL, 't' },
4497 { "property", required_argument, NULL, 'p' },
4498 { "all", no_argument, NULL, 'a' },
30732560 4499 { "failed", no_argument, NULL, ARG_FAILED },
ee5762e3
LP
4500 { "full", no_argument, NULL, ARG_FULL },
4501 { "fail", no_argument, NULL, ARG_FAIL },
e67c3609 4502 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES },
af2d49f7 4503 { "user", no_argument, NULL, ARG_USER },
ee5762e3
LP
4504 { "system", no_argument, NULL, ARG_SYSTEM },
4505 { "global", no_argument, NULL, ARG_GLOBAL },
4506 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
0736af98 4507 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
ee5762e3
LP
4508 { "no-wall", no_argument, NULL, ARG_NO_WALL },
4509 { "quiet", no_argument, NULL, 'q' },
4510 { "order", no_argument, NULL, ARG_ORDER },
4511 { "require", no_argument, NULL, ARG_REQUIRE },
b4f27ccc 4512 { "force", no_argument, NULL, 'f' },
ee5762e3 4513 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
f1e36d67 4514 { "defaults", no_argument, NULL, ARG_DEFAULTS },
8a0867d6
LP
4515 { "kill-mode", required_argument, NULL, ARG_KILL_MODE },
4516 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
4517 { "signal", required_argument, NULL, 's' },
501fc174 4518 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
a8f11321
LP
4519 { "host", required_argument, NULL, 'H' },
4520 { "privileged",no_argument, NULL, 'P' },
ee5762e3 4521 { NULL, 0, NULL, 0 }
7e4249b9
LP
4522 };
4523
4524 int c;
4525
e4b61340 4526 assert(argc >= 0);
7e4249b9
LP
4527 assert(argv);
4528
501fc174
LP
4529 /* Only when running as systemctl we ask for passwords */
4530 arg_ask_password = true;
4531
a8f11321 4532 while ((c = getopt_long(argc, argv, "ht:p:aqfs:H:P", options, NULL)) >= 0) {
7e4249b9
LP
4533
4534 switch (c) {
4535
4536 case 'h':
e4b61340 4537 systemctl_help();
7e4249b9 4538 return 0;
35df8f27
LP
4539
4540 case ARG_VERSION:
4541 puts(PACKAGE_STRING);
7d568925
LP
4542 puts(DISTRIBUTION);
4543 puts(SYSTEMD_FEATURES);
35df8f27 4544 return 0;
7e4249b9
LP
4545
4546 case 't':
4547 arg_type = optarg;
4548 break;
4549
ea4a240d
LP
4550 case 'p': {
4551 char **l;
4552
4553 if (!(l = strv_append(arg_property, optarg)))
4554 return -ENOMEM;
4555
4556 strv_free(arg_property);
4557 arg_property = l;
48220598
LP
4558
4559 /* If the user asked for a particular
4560 * property, show it to him, even if it is
4561 * empty. */
4562 arg_all = true;
4563 break;
ea4a240d 4564 }
48220598 4565
7e4249b9
LP
4566 case 'a':
4567 arg_all = true;
4568 break;
4569
90d473a1 4570 case ARG_FAIL:
e67c3609
LP
4571 arg_job_mode = "fail";
4572 break;
4573
4574 case ARG_IGNORE_DEPENDENCIES:
4575 arg_job_mode = "ignore-dependencies";
7e4249b9
LP
4576 break;
4577
af2d49f7
LP
4578 case ARG_USER:
4579 arg_user = true;
7e4249b9
LP
4580 break;
4581
4582 case ARG_SYSTEM:
af2d49f7 4583 arg_user = false;
7e4249b9
LP
4584 break;
4585
6e905d93
LP
4586 case ARG_NO_BLOCK:
4587 arg_no_block = true;
7e4249b9
LP
4588 break;
4589
611efaac
LP
4590 case ARG_NO_PAGER:
4591 arg_no_pager = true;
4592 break;
0736af98 4593
514f4ef5
LP
4594 case ARG_NO_WALL:
4595 arg_no_wall = true;
4596 break;
4597
4445a875
LP
4598 case ARG_ORDER:
4599 arg_dot = DOT_ORDER;
4600 break;
4601
4602 case ARG_REQUIRE:
4603 arg_dot = DOT_REQUIRE;
4604 break;
4605
8fe914ec
LP
4606 case ARG_FULL:
4607 arg_full = true;
4608 break;
4609
30732560
LP
4610 case ARG_FAILED:
4611 arg_failed = true;
4612 break;
4613
0183528f
LP
4614 case 'q':
4615 arg_quiet = true;
4616 break;
4617
b4f27ccc 4618 case 'f':
ee5762e3
LP
4619 arg_force = true;
4620 break;
4621
4622 case ARG_NO_RELOAD:
4623 arg_no_reload = true;
4624 break;
4625
4626 case ARG_GLOBAL:
4627 arg_global = true;
af2d49f7 4628 arg_user = true;
ee5762e3
LP
4629 break;
4630
4631 case ARG_DEFAULTS:
4632 arg_defaults = true;
4633 break;
4634
8a0867d6
LP
4635 case ARG_KILL_WHO:
4636 arg_kill_who = optarg;
4637 break;
4638
4639 case ARG_KILL_MODE:
4640 arg_kill_mode = optarg;
4641 break;
4642
4643 case 's':
4644 if ((arg_signal = signal_from_string_try_harder(optarg)) < 0) {
4645 log_error("Failed to parse signal string %s.", optarg);
4646 return -EINVAL;
4647 }
4648 break;
4649
501fc174
LP
4650 case ARG_NO_ASK_PASSWORD:
4651 arg_ask_password = false;
4652 break;
4653
a8f11321
LP
4654 case 'P':
4655 arg_transport = TRANSPORT_POLKIT;
4656 break;
4657
4658 case 'H':
4659 arg_transport = TRANSPORT_SSH;
4660 arg_host = optarg;
4661 break;
4662
7e4249b9
LP
4663 case '?':
4664 return -EINVAL;
4665
4666 default:
4667 log_error("Unknown option code %c", c);
4668 return -EINVAL;
4669 }
4670 }
4671
a8f11321
LP
4672 if (arg_transport != TRANSPORT_NORMAL && arg_user) {
4673 log_error("Cannot access user instance remotely.");
4674 return -EINVAL;
4675 }
4676
7e4249b9
LP
4677 return 1;
4678}
4679
e4b61340
LP
4680static int halt_parse_argv(int argc, char *argv[]) {
4681
4682 enum {
4683 ARG_HELP = 0x100,
4684 ARG_HALT,
514f4ef5
LP
4685 ARG_REBOOT,
4686 ARG_NO_WALL
e4b61340
LP
4687 };
4688
4689 static const struct option options[] = {
4690 { "help", no_argument, NULL, ARG_HELP },
4691 { "halt", no_argument, NULL, ARG_HALT },
4692 { "poweroff", no_argument, NULL, 'p' },
4693 { "reboot", no_argument, NULL, ARG_REBOOT },
4694 { "force", no_argument, NULL, 'f' },
4695 { "wtmp-only", no_argument, NULL, 'w' },
4696 { "no-wtmp", no_argument, NULL, 'd' },
4697 { "no-sync", no_argument, NULL, 'n' },
514f4ef5 4698 { "no-wall", no_argument, NULL, ARG_NO_WALL },
e4b61340
LP
4699 { NULL, 0, NULL, 0 }
4700 };
4701
4702 int c, runlevel;
4703
4704 assert(argc >= 0);
4705 assert(argv);
4706
4707 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4708 if (runlevel == '0' || runlevel == '6')
4709 arg_immediate = true;
4710
4711 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
4712 switch (c) {
4713
4714 case ARG_HELP:
4715 halt_help();
4716 return 0;
4717
4718 case ARG_HALT:
4719 arg_action = ACTION_HALT;
4720 break;
4721
4722 case 'p':
a042efad
MS
4723 if (arg_action != ACTION_REBOOT)
4724 arg_action = ACTION_POWEROFF;
e4b61340
LP
4725 break;
4726
4727 case ARG_REBOOT:
4728 arg_action = ACTION_REBOOT;
4729 break;
4730
4731 case 'f':
4732 arg_immediate = true;
4733 break;
4734
4735 case 'w':
4736 arg_dry = true;
4737 break;
4738
4739 case 'd':
4740 arg_no_wtmp = true;
4741 break;
4742
4743 case 'n':
4744 arg_no_sync = true;
4745 break;
4746
514f4ef5
LP
4747 case ARG_NO_WALL:
4748 arg_no_wall = true;
4749 break;
4750
e4b61340
LP
4751 case 'i':
4752 case 'h':
4753 /* Compatibility nops */
4754 break;
4755
4756 case '?':
4757 return -EINVAL;
4758
4759 default:
4760 log_error("Unknown option code %c", c);
4761 return -EINVAL;
4762 }
4763 }
4764
4765 if (optind < argc) {
4766 log_error("Too many arguments.");
4767 return -EINVAL;
4768 }
4769
4770 return 1;
4771}
4772
f6144808
LP
4773static int parse_time_spec(const char *t, usec_t *_u) {
4774 assert(t);
4775 assert(_u);
4776
4777 if (streq(t, "now"))
4778 *_u = 0;
4779 else if (t[0] == '+') {
4780 uint64_t u;
4781
4782 if (safe_atou64(t + 1, &u) < 0)
4783 return -EINVAL;
4784
4785 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
4786 } else {
4787 char *e = NULL;
4788 long hour, minute;
4789 struct tm tm;
4790 time_t s;
4791 usec_t n;
4792
4793 errno = 0;
4794 hour = strtol(t, &e, 10);
4795 if (errno != 0 || *e != ':' || hour < 0 || hour > 23)
4796 return -EINVAL;
4797
4798 minute = strtol(e+1, &e, 10);
4799 if (errno != 0 || *e != 0 || minute < 0 || minute > 59)
4800 return -EINVAL;
4801
4802 n = now(CLOCK_REALTIME);
08e4b1c5
LP
4803 s = (time_t) (n / USEC_PER_SEC);
4804
4805 zero(tm);
f6144808
LP
4806 assert_se(localtime_r(&s, &tm));
4807
4808 tm.tm_hour = (int) hour;
4809 tm.tm_min = (int) minute;
08e4b1c5 4810 tm.tm_sec = 0;
f6144808
LP
4811
4812 assert_se(s = mktime(&tm));
4813
4814 *_u = (usec_t) s * USEC_PER_SEC;
4815
4816 while (*_u <= n)
4817 *_u += USEC_PER_DAY;
4818 }
4819
4820 return 0;
4821}
4822
5622dde3
KS
4823static bool kexec_loaded(void) {
4824 bool loaded = false;
4825 char *s;
4826
4827 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4828 if (s[0] == '1')
4829 loaded = true;
4830 free(s);
4831 }
4832 return loaded;
4833}
4834
e4b61340
LP
4835static int shutdown_parse_argv(int argc, char *argv[]) {
4836
4837 enum {
4838 ARG_HELP = 0x100,
514f4ef5 4839 ARG_NO_WALL
e4b61340
LP
4840 };
4841
4842 static const struct option options[] = {
4843 { "help", no_argument, NULL, ARG_HELP },
4844 { "halt", no_argument, NULL, 'H' },
4845 { "poweroff", no_argument, NULL, 'P' },
4846 { "reboot", no_argument, NULL, 'r' },
514f4ef5 4847 { "no-wall", no_argument, NULL, ARG_NO_WALL },
e4b61340
LP
4848 { NULL, 0, NULL, 0 }
4849 };
4850
f6144808 4851 int c, r;
e4b61340
LP
4852
4853 assert(argc >= 0);
4854 assert(argv);
4855
f6144808 4856 while ((c = getopt_long(argc, argv, "HPrhkt:afFc", options, NULL)) >= 0) {
e4b61340
LP
4857 switch (c) {
4858
4859 case ARG_HELP:
4860 shutdown_help();
4861 return 0;
4862
4863 case 'H':
4864 arg_action = ACTION_HALT;
4865 break;
4866
4867 case 'P':
4868 arg_action = ACTION_POWEROFF;
4869 break;
4870
4871 case 'r':
5622dde3
KS
4872 if (kexec_loaded())
4873 arg_action = ACTION_KEXEC;
4874 else
4875 arg_action = ACTION_REBOOT;
e4b61340
LP
4876 break;
4877
4878 case 'h':
4879 if (arg_action != ACTION_HALT)
4880 arg_action = ACTION_POWEROFF;
4881 break;
4882
4883 case 'k':
4884 arg_dry = true;
4885 break;
4886
514f4ef5
LP
4887 case ARG_NO_WALL:
4888 arg_no_wall = true;
4889 break;
4890
e4b61340
LP
4891 case 't':
4892 case 'a':
4893 /* Compatibility nops */
4894 break;
4895
f6144808
LP
4896 case 'c':
4897 arg_action = ACTION_CANCEL_SHUTDOWN;
4898 break;
4899
e4b61340
LP
4900 case '?':
4901 return -EINVAL;
4902
4903 default:
4904 log_error("Unknown option code %c", c);
4905 return -EINVAL;
4906 }
4907 }
4908
6b5ad000 4909 if (argc > optind) {
f6144808
LP
4910 if ((r = parse_time_spec(argv[optind], &arg_when)) < 0) {
4911 log_error("Failed to parse time specification: %s", argv[optind]);
4912 return r;
4913 }
6b5ad000 4914 } else
08e4b1c5 4915 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
442b9094 4916
f6144808 4917 /* We skip the time argument */
e4b61340
LP
4918 if (argc > optind + 1)
4919 arg_wall = argv + optind + 1;
4920
4921 optind = argc;
4922
4923 return 1;
e4b61340
LP
4924}
4925
4926static int telinit_parse_argv(int argc, char *argv[]) {
4927
4928 enum {
4929 ARG_HELP = 0x100,
514f4ef5 4930 ARG_NO_WALL
e4b61340
LP
4931 };
4932
4933 static const struct option options[] = {
4934 { "help", no_argument, NULL, ARG_HELP },
514f4ef5 4935 { "no-wall", no_argument, NULL, ARG_NO_WALL },
e4b61340
LP
4936 { NULL, 0, NULL, 0 }
4937 };
4938
4939 static const struct {
4940 char from;
4941 enum action to;
4942 } table[] = {
4943 { '0', ACTION_POWEROFF },
4944 { '6', ACTION_REBOOT },
ef2f1067 4945 { '1', ACTION_RESCUE },
e4b61340
LP
4946 { '2', ACTION_RUNLEVEL2 },
4947 { '3', ACTION_RUNLEVEL3 },
4948 { '4', ACTION_RUNLEVEL4 },
4949 { '5', ACTION_RUNLEVEL5 },
4950 { 's', ACTION_RESCUE },
4951 { 'S', ACTION_RESCUE },
4952 { 'q', ACTION_RELOAD },
4953 { 'Q', ACTION_RELOAD },
4954 { 'u', ACTION_REEXEC },
4955 { 'U', ACTION_REEXEC }
4956 };
4957
4958 unsigned i;
4959 int c;
4960
4961 assert(argc >= 0);
4962 assert(argv);
4963
4964 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
4965 switch (c) {
4966
4967 case ARG_HELP:
4968 telinit_help();
4969 return 0;
4970
514f4ef5
LP
4971 case ARG_NO_WALL:
4972 arg_no_wall = true;
4973 break;
4974
e4b61340
LP
4975 case '?':
4976 return -EINVAL;
4977
4978 default:
4979 log_error("Unknown option code %c", c);
4980 return -EINVAL;
4981 }
4982 }
4983
4984 if (optind >= argc) {
2f02ce40 4985 telinit_help();
e4b61340
LP
4986 return -EINVAL;
4987 }
4988
4989 if (optind + 1 < argc) {
4990 log_error("Too many arguments.");
4991 return -EINVAL;
4992 }
4993
4994 if (strlen(argv[optind]) != 1) {
4995 log_error("Expected single character argument.");
4996 return -EINVAL;
4997 }
4998
4999 for (i = 0; i < ELEMENTSOF(table); i++)
5000 if (table[i].from == argv[optind][0])
5001 break;
5002
5003 if (i >= ELEMENTSOF(table)) {
5004 log_error("Unknown command %s.", argv[optind]);
5005 return -EINVAL;
5006 }
5007
5008 arg_action = table[i].to;
5009
5010 optind ++;
5011
5012 return 1;
5013}
5014
5015static int runlevel_parse_argv(int argc, char *argv[]) {
5016
5017 enum {
5018 ARG_HELP = 0x100,
5019 };
5020
5021 static const struct option options[] = {
5022 { "help", no_argument, NULL, ARG_HELP },
5023 { NULL, 0, NULL, 0 }
5024 };
5025
5026 int c;
5027
5028 assert(argc >= 0);
5029 assert(argv);
5030
5031 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
5032 switch (c) {
5033
5034 case ARG_HELP:
5035 runlevel_help();
5036 return 0;
5037
5038 case '?':
5039 return -EINVAL;
5040
5041 default:
5042 log_error("Unknown option code %c", c);
5043 return -EINVAL;
5044 }
5045 }
5046
5047 if (optind < argc) {
5048 log_error("Too many arguments.");
5049 return -EINVAL;
5050 }
5051
5052 return 1;
5053}
5054
5055static int parse_argv(int argc, char *argv[]) {
5056 assert(argc >= 0);
5057 assert(argv);
5058
5059 if (program_invocation_short_name) {
5060
5061 if (strstr(program_invocation_short_name, "halt")) {
5062 arg_action = ACTION_HALT;
5063 return halt_parse_argv(argc, argv);
5064 } else if (strstr(program_invocation_short_name, "poweroff")) {
5065 arg_action = ACTION_POWEROFF;
5066 return halt_parse_argv(argc, argv);
5067 } else if (strstr(program_invocation_short_name, "reboot")) {
5622dde3
KS
5068 if (kexec_loaded())
5069 arg_action = ACTION_KEXEC;
5070 else
5071 arg_action = ACTION_REBOOT;
e4b61340
LP
5072 return halt_parse_argv(argc, argv);
5073 } else if (strstr(program_invocation_short_name, "shutdown")) {
5074 arg_action = ACTION_POWEROFF;
5075 return shutdown_parse_argv(argc, argv);
5076 } else if (strstr(program_invocation_short_name, "init")) {
d5ca5f11
LP
5077
5078 if (sd_booted() > 0) {
5079 arg_action = ACTION_INVALID;
5080 return telinit_parse_argv(argc, argv);
5081 } else {
5082 /* Hmm, so some other init system is
5083 * running, we need to forward this
5084 * request to it. For now we simply
5085 * guess that it is Upstart. */
5086
5087 execv("/lib/upstart/telinit", argv);
5088
5089 log_error("Couldn't find an alternative telinit implementation to spawn.");
5090 return -EIO;
5091 }
5092
e4b61340
LP
5093 } else if (strstr(program_invocation_short_name, "runlevel")) {
5094 arg_action = ACTION_RUNLEVEL;
5095 return runlevel_parse_argv(argc, argv);
5096 }
5097 }
5098
5099 arg_action = ACTION_SYSTEMCTL;
5100 return systemctl_parse_argv(argc, argv);
5101}
5102
d55ae9e6 5103static int action_to_runlevel(void) {
eb22ac37
LP
5104
5105 static const char table[_ACTION_MAX] = {
5106 [ACTION_HALT] = '0',
5107 [ACTION_POWEROFF] = '0',
5108 [ACTION_REBOOT] = '6',
5109 [ACTION_RUNLEVEL2] = '2',
5110 [ACTION_RUNLEVEL3] = '3',
5111 [ACTION_RUNLEVEL4] = '4',
5112 [ACTION_RUNLEVEL5] = '5',
5113 [ACTION_RESCUE] = '1'
5114 };
5115
d55ae9e6
LP
5116 assert(arg_action < _ACTION_MAX);
5117
5118 return table[arg_action];
5119}
5120
f1c5860b 5121static int talk_upstart(void) {
d55ae9e6
LP
5122 DBusMessage *m = NULL, *reply = NULL;
5123 DBusError error;
5124 int previous, rl, r;
5125 char
5126 env1_buf[] = "RUNLEVEL=X",
5127 env2_buf[] = "PREVLEVEL=X";
5128 char *env1 = env1_buf, *env2 = env2_buf;
5129 const char *emit = "runlevel";
5130 dbus_bool_t b_false = FALSE;
5131 DBusMessageIter iter, sub;
f1c5860b 5132 DBusConnection *bus;
d55ae9e6
LP
5133
5134 dbus_error_init(&error);
5135
5136 if (!(rl = action_to_runlevel()))
5137 return 0;
5138
5139 if (utmp_get_runlevel(&previous, NULL) < 0)
5140 previous = 'N';
5141
b574246b 5142 if (!(bus = dbus_connection_open_private("unix:abstract=/com/ubuntu/upstart", &error))) {
f1c5860b
LP
5143 if (dbus_error_has_name(&error, DBUS_ERROR_NO_SERVER)) {
5144 r = 0;
5145 goto finish;
5146 }
5147
4cf5d675 5148 log_error("Failed to connect to Upstart bus: %s", bus_error_message(&error));
f1c5860b
LP
5149 r = -EIO;
5150 goto finish;
5151 }
5152
5153 if ((r = bus_check_peercred(bus)) < 0) {
5154 log_error("Failed to verify owner of bus.");
5155 goto finish;
5156 }
5157
d55ae9e6
LP
5158 if (!(m = dbus_message_new_method_call(
5159 "com.ubuntu.Upstart",
5160 "/com/ubuntu/Upstart",
5161 "com.ubuntu.Upstart0_6",
5162 "EmitEvent"))) {
5163
5164 log_error("Could not allocate message.");
f1c5860b
LP
5165 r = -ENOMEM;
5166 goto finish;
d55ae9e6
LP
5167 }
5168
5169 dbus_message_iter_init_append(m, &iter);
5170
5171 env1_buf[sizeof(env1_buf)-2] = rl;
5172 env2_buf[sizeof(env2_buf)-2] = previous;
5173
5174 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &emit) ||
5175 !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub) ||
5176 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env1) ||
5177 !dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &env2) ||
5178 !dbus_message_iter_close_container(&iter, &sub) ||
5179 !dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &b_false)) {
5180 log_error("Could not append arguments to message.");
5181 r = -ENOMEM;
5182 goto finish;
5183 }
5184
5185 if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
5186
5187 if (error_is_no_service(&error)) {
aabd9b11 5188 r = -EADDRNOTAVAIL;
d55ae9e6
LP
5189 goto finish;
5190 }
5191
4cf5d675 5192 log_error("Failed to issue method call: %s", bus_error_message(&error));
d55ae9e6
LP
5193 r = -EIO;
5194 goto finish;
5195 }
5196
aabd9b11 5197 r = 0;
d55ae9e6
LP
5198
5199finish:
5200 if (m)
5201 dbus_message_unref(m);
5202
5203 if (reply)
5204 dbus_message_unref(reply);
5205
b574246b 5206 if (bus) {
5d452f9c 5207 dbus_connection_flush(bus);
b574246b 5208 dbus_connection_close(bus);
f1c5860b 5209 dbus_connection_unref(bus);
b574246b 5210 }
f1c5860b 5211
d55ae9e6
LP
5212 dbus_error_free(&error);
5213
5214 return r;
5215}
5216
5217static int talk_initctl(void) {
eb22ac37
LP
5218 struct init_request request;
5219 int r, fd;
d55ae9e6 5220 char rl;
eb22ac37 5221
d55ae9e6 5222 if (!(rl = action_to_runlevel()))
eb22ac37
LP
5223 return 0;
5224
5225 zero(request);
5226 request.magic = INIT_MAGIC;
5227 request.sleeptime = 0;
5228 request.cmd = INIT_CMD_RUNLVL;
d55ae9e6
LP
5229 request.runlevel = rl;
5230
5231 if ((fd = open(INIT_FIFO, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) {
5232
5233 if (errno == ENOENT)
5234 return 0;
eb22ac37 5235
d55ae9e6 5236 log_error("Failed to open "INIT_FIFO": %m");
eb22ac37 5237 return -errno;
d55ae9e6 5238 }
eb22ac37 5239
d55ae9e6 5240 errno = 0;
eb22ac37
LP
5241 r = loop_write(fd, &request, sizeof(request), false) != sizeof(request);
5242 close_nointr_nofail(fd);
5243
d55ae9e6
LP
5244 if (r < 0) {
5245 log_error("Failed to write to "INIT_FIFO": %m");
eb22ac37 5246 return errno ? -errno : -EIO;
d55ae9e6 5247 }
eb22ac37
LP
5248
5249 return 1;
e4b61340
LP
5250}
5251
ee5762e3 5252static int systemctl_main(DBusConnection *bus, int argc, char *argv[], DBusError *error) {
7e4249b9 5253
7e4249b9
LP
5254 static const struct {
5255 const char* verb;
5256 const enum {
5257 MORE,
5258 LESS,
5259 EQUAL
5260 } argc_cmp;
5261 const int argc;
5262 int (* const dispatch)(DBusConnection *bus, char **args, unsigned n);
5263 } verbs[] = {
ee5762e3
LP
5264 { "list-units", LESS, 1, list_units },
5265 { "list-jobs", EQUAL, 1, list_jobs },
5266 { "clear-jobs", EQUAL, 1, daemon_reload },
5267 { "load", MORE, 2, load_unit },
5268 { "cancel", MORE, 2, cancel_job },
5269 { "start", MORE, 2, start_unit },
5270 { "stop", MORE, 2, start_unit },
a76f7be2 5271 { "condstop", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
ee5762e3
LP
5272 { "reload", MORE, 2, start_unit },
5273 { "restart", MORE, 2, start_unit },
5274 { "try-restart", MORE, 2, start_unit },
5275 { "reload-or-restart", MORE, 2, start_unit },
5276 { "reload-or-try-restart", MORE, 2, start_unit },
5277 { "force-reload", MORE, 2, start_unit }, /* For compatibility with SysV */
64e5f1b7 5278 { "condreload", MORE, 2, start_unit }, /* For compatibility with ALTLinux */
ee5762e3
LP
5279 { "condrestart", MORE, 2, start_unit }, /* For compatibility with RH */
5280 { "isolate", EQUAL, 2, start_unit },
8a0867d6 5281 { "kill", MORE, 2, kill_unit },
ee5762e3
LP
5282 { "is-active", MORE, 2, check_unit },
5283 { "check", MORE, 2, check_unit },
5284 { "show", MORE, 1, show },
5285 { "status", MORE, 2, show },
5286 { "monitor", EQUAL, 1, monitor },
5287 { "dump", EQUAL, 1, dump },
5288 { "dot", EQUAL, 1, dot },
5289 { "snapshot", LESS, 2, snapshot },
5290 { "delete", MORE, 2, delete_snapshot },
5291 { "daemon-reload", EQUAL, 1, daemon_reload },
5292 { "daemon-reexec", EQUAL, 1, daemon_reload },
ee5762e3
LP
5293 { "show-environment", EQUAL, 1, show_enviroment },
5294 { "set-environment", MORE, 2, set_environment },
5295 { "unset-environment", MORE, 2, set_environment },
5296 { "halt", EQUAL, 1, start_special },
5297 { "poweroff", EQUAL, 1, start_special },
5298 { "reboot", EQUAL, 1, start_special },
20b09ca7 5299 { "kexec", EQUAL, 1, start_special },
ee5762e3
LP
5300 { "default", EQUAL, 1, start_special },
5301 { "rescue", EQUAL, 1, start_special },
5302 { "emergency", EQUAL, 1, start_special },
20b09ca7 5303 { "exit", EQUAL, 1, start_special },
fdf20a31 5304 { "reset-failed", MORE, 1, reset_failed },
ee5762e3
LP
5305 { "enable", MORE, 2, enable_unit },
5306 { "disable", MORE, 2, enable_unit },
5307 { "is-enabled", MORE, 2, enable_unit }
7e4249b9
LP
5308 };
5309
e4b61340 5310 int left;
7e4249b9 5311 unsigned i;
7e4249b9 5312
e4b61340
LP
5313 assert(argc >= 0);
5314 assert(argv);
ee5762e3 5315 assert(error);
7e4249b9
LP
5316
5317 left = argc - optind;
5318
5319 if (left <= 0)
5320 /* Special rule: no arguments means "list-units" */
5321 i = 0;
5322 else {
0183528f
LP
5323 if (streq(argv[optind], "help")) {
5324 systemctl_help();
5325 return 0;
5326 }
5327
7e4249b9
LP
5328 for (i = 0; i < ELEMENTSOF(verbs); i++)
5329 if (streq(argv[optind], verbs[i].verb))
5330 break;
5331
5332 if (i >= ELEMENTSOF(verbs)) {
5333 log_error("Unknown operation %s", argv[optind]);
e4b61340 5334 return -EINVAL;
7e4249b9
LP
5335 }
5336 }
5337
5338 switch (verbs[i].argc_cmp) {
5339
5340 case EQUAL:
5341 if (left != verbs[i].argc) {
5342 log_error("Invalid number of arguments.");
e4b61340 5343 return -EINVAL;
7e4249b9
LP
5344 }
5345
5346 break;
5347
5348 case MORE:
5349 if (left < verbs[i].argc) {
5350 log_error("Too few arguments.");
e4b61340 5351 return -EINVAL;
7e4249b9
LP
5352 }
5353
5354 break;
5355
5356 case LESS:
5357 if (left > verbs[i].argc) {
5358 log_error("Too many arguments.");
e4b61340 5359 return -EINVAL;
7e4249b9
LP
5360 }
5361
5362 break;
5363
5364 default:
5365 assert_not_reached("Unknown comparison operator.");
5366 }
5367
ee5762e3
LP
5368 /* Require a bus connection for all operations but
5369 * enable/disable */
82e23ddd
LP
5370 if (!streq(verbs[i].verb, "enable") && !streq(verbs[i].verb, "disable")) {
5371
5372 if (running_in_chroot() > 0) {
5373 log_info("Running in chroot, ignoring request.");
5374 return 0;
5375 }
5376
5377 if (!bus) {
5378 log_error("Failed to get D-Bus connection: %s", error->message);
5379 return -EIO;
5380 }
ee5762e3
LP
5381 }
5382
e4b61340
LP
5383 return verbs[i].dispatch(bus, argv + optind, left);
5384}
5385
9be9828c 5386static int send_shutdownd(usec_t t, char mode, bool warn, const char *message) {
f6144808
LP
5387 int fd = -1;
5388 struct msghdr msghdr;
5389 struct iovec iovec;
5390 union sockaddr_union sockaddr;
f6144808
LP
5391 struct shutdownd_command c;
5392
5393 zero(c);
5394 c.elapse = t;
5395 c.mode = mode;
9be9828c
LP
5396 c.warn_wall = warn;
5397
5398 if (message)
5399 strncpy(c.wall_message, message, sizeof(c.wall_message));
f6144808
LP
5400
5401 if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0)
5402 return -errno;
5403
5404 zero(sockaddr);
5405 sockaddr.sa.sa_family = AF_UNIX;
5406 sockaddr.un.sun_path[0] = 0;
2b583ce6 5407 strncpy(sockaddr.un.sun_path, "/run/systemd/shutdownd", sizeof(sockaddr.un.sun_path));
f6144808
LP
5408
5409 zero(iovec);
5410 iovec.iov_base = (char*) &c;
5411 iovec.iov_len = sizeof(c);
5412
f6144808
LP
5413 zero(msghdr);
5414 msghdr.msg_name = &sockaddr;
2b583ce6 5415 msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/systemd/shutdownd") - 1;
f6144808
LP
5416
5417 msghdr.msg_iov = &iovec;
5418 msghdr.msg_iovlen = 1;
f6144808
LP
5419
5420 if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
5421 close_nointr_nofail(fd);
5422 return -errno;
5423 }
5424
5425 close_nointr_nofail(fd);
5426 return 0;
5427}
5428
e4b61340 5429static int reload_with_fallback(DBusConnection *bus) {
e4b61340
LP
5430
5431 if (bus) {
5432 /* First, try systemd via D-Bus. */
e364ad06 5433 if (daemon_reload(bus, NULL, 0) > 0)
e4b61340
LP
5434 return 0;
5435 }
5436
5437 /* Nothing else worked, so let's try signals */
5438 assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
5439
5440 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
5441 log_error("kill() failed: %m");
5442 return -errno;
5443 }
5444
5445 return 0;
5446}
5447
5448static int start_with_fallback(DBusConnection *bus) {
e4b61340
LP
5449
5450 if (bus) {
5451 /* First, try systemd via D-Bus. */
706900b7 5452 if (start_unit(bus, NULL, 0) >= 0)
983d9c90 5453 goto done;
e4b61340
LP
5454 }
5455
ec7f7f20
LP
5456 /* Hmm, talking to systemd via D-Bus didn't work. Then
5457 * let's try to talk to Upstart via D-Bus. */
e364ad06 5458 if (talk_upstart() > 0)
ec7f7f20
LP
5459 goto done;
5460
e4b61340
LP
5461 /* Nothing else worked, so let's try
5462 * /dev/initctl */
fbc43921 5463 if (talk_initctl() > 0)
983d9c90 5464 goto done;
d55ae9e6
LP
5465
5466 log_error("Failed to talk to init daemon.");
5467 return -EIO;
983d9c90
LP
5468
5469done:
5470 warn_wall(arg_action);
5471 return 0;
e4b61340
LP
5472}
5473
5474static int halt_main(DBusConnection *bus) {
5475 int r;
5476
bc8c2f5c 5477 if (geteuid() != 0) {
cc8a7a61 5478 log_error("Must be root.");
bc8c2f5c
LP
5479 return -EPERM;
5480 }
5481
f6144808 5482 if (arg_when > 0) {
9be9828c 5483 char *m;
08e4b1c5 5484 char date[FORMAT_TIMESTAMP_MAX];
9be9828c
LP
5485
5486 m = strv_join(arg_wall, " ");
5487 r = send_shutdownd(arg_when,
5488 arg_action == ACTION_HALT ? 'H' :
5489 arg_action == ACTION_POWEROFF ? 'P' :
5490 'r',
5491 !arg_no_wall,
5492 m);
5493 free(m);
5494
5495 if (r < 0)
f6144808 5496 log_warning("Failed to talk to shutdownd, proceeding with immediate shutdown: %s", strerror(-r));
08e4b1c5
LP
5497 else {
5498 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.",
5499 format_timestamp(date, sizeof(date), arg_when));
f6144808 5500 return 0;
08e4b1c5 5501 }
f6144808
LP
5502 }
5503
d47b555b 5504 if (!arg_dry && !arg_immediate)
e4b61340
LP
5505 return start_with_fallback(bus);
5506
d90e1a30
LP
5507 if (!arg_no_wtmp) {
5508 if (sd_booted() > 0)
5509 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
5510 else if ((r = utmp_put_shutdown(0)) < 0)
e4b61340 5511 log_warning("Failed to write utmp record: %s", strerror(-r));
d90e1a30 5512 }
e4b61340
LP
5513
5514 if (!arg_no_sync)
5515 sync();
5516
5517 if (arg_dry)
5518 return 0;
5519
5520 /* Make sure C-A-D is handled by the kernel from this
5521 * point on... */
5522 reboot(RB_ENABLE_CAD);
5523
5524 switch (arg_action) {
5525
5526 case ACTION_HALT:
3059b1c1 5527 log_info("Halting.");
e4b61340
LP
5528 reboot(RB_HALT_SYSTEM);
5529 break;
5530
5531 case ACTION_POWEROFF:
3059b1c1 5532 log_info("Powering off.");
e4b61340
LP
5533 reboot(RB_POWER_OFF);
5534 break;
5535
5536 case ACTION_REBOOT:
3059b1c1 5537 log_info("Rebooting.");
e4b61340
LP
5538 reboot(RB_AUTOBOOT);
5539 break;
5540
5541 default:
5542 assert_not_reached("Unknown halt action.");
5543 }
5544
5545 /* We should never reach this. */
5546 return -ENOSYS;
5547}
5548
5549static int runlevel_main(void) {
5550 int r, runlevel, previous;
5551
5552 if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
cd6d0a45 5553 printf("unknown\n");
e4b61340
LP
5554 return r;
5555 }
5556
5557 printf("%c %c\n",
5558 previous <= 0 ? 'N' : previous,
5559 runlevel <= 0 ? 'N' : runlevel);
5560
5561 return 0;
5562}
5563
0736af98 5564static void pager_open(void) {
611efaac
LP
5565 int fd[2];
5566 const char *pager;
c0f9c7da 5567 pid_t parent_pid;
611efaac 5568
1888c907
LP
5569 if (pager_pid > 0)
5570 return;
5571
611efaac
LP
5572 if (!on_tty() || arg_no_pager)
5573 return;
5574
abebb5af 5575 if ((pager = getenv("SYSTEMD_PAGER")) || (pager = getenv("PAGER")))
611efaac
LP
5576 if (!*pager || streq(pager, "cat"))
5577 return;
5578
4bc5f808
LP
5579 /* Determine and cache number of columns before we spawn the
5580 * pager so that we get the value from the actual tty */
5581 columns();
5582
611efaac
LP
5583 if (pipe(fd) < 0) {
5584 log_error("Failed to create pager pipe: %m");
5585 return;
5586 }
5587
c0f9c7da
LP
5588 parent_pid = getpid();
5589
1888c907
LP
5590 pager_pid = fork();
5591 if (pager_pid < 0) {
611efaac
LP
5592 log_error("Failed to fork pager: %m");
5593 close_pipe(fd);
5594 return;
5595 }
5596
1888c907
LP
5597 /* In the child start the pager */
5598 if (pager_pid == 0) {
611efaac
LP
5599
5600 dup2(fd[0], STDIN_FILENO);
5601 close_pipe(fd);
5602
4c00bf25 5603 setenv("LESS", "FRSX", 0);
611efaac 5604
c0f9c7da
LP
5605 /* Make sure the pager goes away when the parent dies */
5606 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5607 _exit(EXIT_FAILURE);
5608
5609 /* Check whether our parent died before we were able
5610 * to set the death signal */
5611 if (getppid() != parent_pid)
5612 _exit(EXIT_SUCCESS);
1888c907 5613
611efaac
LP
5614 if (pager) {
5615 execlp(pager, pager, NULL);
5616 execl("/bin/sh", "sh", "-c", pager, NULL);
5617 } else {
75d12d57
LP
5618 /* Debian's alternatives command for pagers is
5619 * called 'pager'. Note that we do not call
5620 * sensible-pagers here, since that is just a
5621 * shell script that implements a logic that
5622 * is similar to this one anyway, but is
5623 * Debian-specific. */
5624 execlp("pager", "pager", NULL);
5625
611efaac
LP
5626 execlp("less", "less", NULL);
5627 execlp("more", "more", NULL);
5628 }
5629
5630 log_error("Unable to execute pager: %m");
5631 _exit(EXIT_FAILURE);
5632 }
5633
1888c907 5634 /* Return in the parent */
611efaac
LP
5635 if (dup2(fd[1], STDOUT_FILENO) < 0)
5636 log_error("Failed to duplicate pager pipe: %m");
5637
5638 close_pipe(fd);
0736af98
MV
5639}
5640
1888c907
LP
5641static void pager_close(void) {
5642 siginfo_t dummy;
5643
5644 if (pager_pid <= 0)
5645 return;
5646
5647 /* Inform pager that we are done */
5648 fclose(stdout);
430c18ed 5649 kill(pager_pid, SIGCONT);
1888c907
LP
5650 wait_for_terminate(pager_pid, &dummy);
5651 pager_pid = 0;
5652}
5653
c0f9c7da
LP
5654static void agent_close(void) {
5655 siginfo_t dummy;
5656
5657 if (agent_pid <= 0)
5658 return;
5659
5660 /* Inform agent that we are done */
5661 kill(agent_pid, SIGTERM);
430c18ed 5662 kill(agent_pid, SIGCONT);
c0f9c7da
LP
5663 wait_for_terminate(agent_pid, &dummy);
5664 agent_pid = 0;
5665}
5666
e4b61340 5667int main(int argc, char*argv[]) {
22f4096c 5668 int r, retval = EXIT_FAILURE;
e4b61340
LP
5669 DBusConnection *bus = NULL;
5670 DBusError error;
5671
5672 dbus_error_init(&error);
5673
5674 log_parse_environment();
2396fb04 5675 log_open();
e4b61340
LP
5676
5677 if ((r = parse_argv(argc, argv)) < 0)
5678 goto finish;
5679 else if (r == 0) {
22f4096c 5680 retval = EXIT_SUCCESS;
7e4249b9
LP
5681 goto finish;
5682 }
5683
e4b61340
LP
5684 /* /sbin/runlevel doesn't need to communicate via D-Bus, so
5685 * let's shortcut this */
5686 if (arg_action == ACTION_RUNLEVEL) {
22f4096c
LP
5687 r = runlevel_main();
5688 retval = r < 0 ? EXIT_FAILURE : r;
e4b61340
LP
5689 goto finish;
5690 }
5691
82e23ddd
LP
5692 if (running_in_chroot() > 0 && arg_action != ACTION_SYSTEMCTL) {
5693 log_info("Running in chroot, ignoring request.");
5694 retval = 0;
5695 goto finish;
5696 }
5697
a8f11321
LP
5698 if (arg_transport == TRANSPORT_NORMAL)
5699 bus_connect(arg_user ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &bus, &private_bus, &error);
5700 else if (arg_transport == TRANSPORT_POLKIT) {
5701 bus_connect_system_polkit(&bus, &error);
5702 private_bus = false;
5703 } else if (arg_transport == TRANSPORT_SSH) {
5704 bus_connect_system_ssh(NULL, arg_host, &bus, &error);
5705 private_bus = false;
5706 } else
5707 assert_not_reached("Uh, invalid transport...");
e4b61340
LP
5708
5709 switch (arg_action) {
5710
22f4096c
LP
5711 case ACTION_SYSTEMCTL:
5712 r = systemctl_main(bus, argc, argv, &error);
e4b61340 5713 break;
e4b61340
LP
5714
5715 case ACTION_HALT:
5716 case ACTION_POWEROFF:
5717 case ACTION_REBOOT:
5622dde3 5718 case ACTION_KEXEC:
22f4096c 5719 r = halt_main(bus);
e4b61340
LP
5720 break;
5721
e4b61340
LP
5722 case ACTION_RUNLEVEL2:
5723 case ACTION_RUNLEVEL3:
5724 case ACTION_RUNLEVEL4:
5725 case ACTION_RUNLEVEL5:
5726 case ACTION_RESCUE:
514f4ef5 5727 case ACTION_EMERGENCY:
eb22ac37 5728 case ACTION_DEFAULT:
22f4096c 5729 r = start_with_fallback(bus);
e4b61340 5730 break;
7e4249b9 5731
e4b61340
LP
5732 case ACTION_RELOAD:
5733 case ACTION_REEXEC:
22f4096c 5734 r = reload_with_fallback(bus);
e4b61340
LP
5735 break;
5736
f6144808 5737 case ACTION_CANCEL_SHUTDOWN:
22f4096c 5738 r = send_shutdownd(0, 0, false, NULL);
f6144808
LP
5739 break;
5740
eb22ac37
LP
5741 case ACTION_INVALID:
5742 case ACTION_RUNLEVEL:
e4b61340
LP
5743 default:
5744 assert_not_reached("Unknown action");
5745 }
7e4249b9 5746
22f4096c
LP
5747 retval = r < 0 ? EXIT_FAILURE : r;
5748
7e4249b9
LP
5749finish:
5750
b574246b 5751 if (bus) {
5d452f9c 5752 dbus_connection_flush(bus);
b574246b 5753 dbus_connection_close(bus);
7e4249b9 5754 dbus_connection_unref(bus);
b574246b 5755 }
7e4249b9 5756
e4b61340
LP
5757 dbus_error_free(&error);
5758
7e4249b9
LP
5759 dbus_shutdown();
5760
ea4a240d
LP
5761 strv_free(arg_property);
5762
1888c907 5763 pager_close();
c0f9c7da 5764 agent_close();
1888c907 5765
7e4249b9
LP
5766 return retval;
5767}