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