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