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