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