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