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