]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/systemctl/systemctl.c
systemctl: remove newlines
[thirdparty/systemd.git] / src / systemctl / systemctl.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
7e4249b9
LP
2/***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
f459b602 6 Copyright 2013 Marc-Antoine Perennou
7e4249b9
LP
7***/
8
03a7b521
LP
9#include <errno.h>
10#include <fcntl.h>
7e4249b9 11#include <getopt.h>
a9cdc94f 12#include <locale.h>
7e4249b9 13#include <stdbool.h>
03a7b521
LP
14#include <stddef.h>
15#include <stdio.h>
7e4249b9 16#include <string.h>
4bb2e9d4 17#include <sys/prctl.h>
03a7b521 18#include <sys/reboot.h>
f1c5860b 19#include <sys/socket.h>
03a7b521 20#include <unistd.h>
81527be1 21
03a7b521 22#include "sd-bus.h"
f459b602 23#include "sd-daemon.h"
f459b602 24#include "sd-login.h"
03a7b521 25
b5efdb8a 26#include "alloc-util.h"
4bb2e9d4 27#include "bootspec.h"
03a7b521
LP
28#include "bus-common-errors.h"
29#include "bus-error.h"
30#include "bus-message.h"
291d565a 31#include "bus-unit-util.h"
03a7b521 32#include "bus-util.h"
ab35fb1b 33#include "cgroup-show.h"
c6c18be3 34#include "cgroup-util.h"
cda134ab 35#include "copy.h"
ad2a0358 36#include "dropin.h"
5bdf2243 37#include "efivars.h"
03a7b521 38#include "env-util.h"
804ee07c 39#include "escape.h"
03a7b521 40#include "exit-status.h"
3ffd4af2 41#include "fd-util.h"
03a7b521 42#include "fileio.h"
f97b34a6 43#include "format-util.h"
f4f15635 44#include "fs-util.h"
7d50b32a 45#include "glob-util.h"
08f3be7a 46#include "hexdecoct.h"
c52a937b 47#include "hostname-util.h"
03a7b521
LP
48#include "initreq.h"
49#include "install.h"
c004493c 50#include "io-util.h"
03a7b521 51#include "list.h"
8752c575 52#include "locale-util.h"
03a7b521
LP
53#include "log.h"
54#include "logs-show.h"
55#include "macro.h"
56#include "mkdir.h"
57#include "pager.h"
6bedfcbb 58#include "parse-util.h"
03a7b521
LP
59#include "path-lookup.h"
60#include "path-util.h"
61#include "process-util.h"
e3631d1c 62#include "reboot-util.h"
78f22b97 63#include "rlimit-util.h"
03a7b521 64#include "set.h"
592705f2 65#include "sigbus.h"
24882e06 66#include "signal-util.h"
03a7b521
LP
67#include "socket-util.h"
68#include "spawn-ask-password-agent.h"
69#include "spawn-polkit-agent.h"
70#include "special.h"
8fcde012 71#include "stat-util.h"
8559e61d 72#include "string-table.h"
03a7b521
LP
73#include "strv.h"
74#include "terminal-util.h"
89ada3ba 75#include "unit-def.h"
03a7b521 76#include "unit-name.h"
b1d4f8e1 77#include "user-util.h"
03a7b521
LP
78#include "util.h"
79#include "utmp-wtmp.h"
e449de87 80#include "verbs.h"
7f4b3c5e 81#include "virt.h"
7e4249b9 82
b613907e
SS
83/* The init script exit status codes
84 0 program is running or service is OK
85 1 program is dead and /var/run pid file exists
86 2 program is dead and /var/lock lock file exists
87 3 program is not running
88 4 program or service status is unknown
89 5-99 reserved for future LSB use
90 100-149 reserved for distribution use
91 150-199 reserved for application use
92 200-254 reserved
93*/
94enum {
95 EXIT_PROGRAM_RUNNING_OR_SERVICE_OK = 0,
96 EXIT_PROGRAM_DEAD_AND_PID_EXISTS = 1,
97 EXIT_PROGRAM_DEAD_AND_LOCK_FILE_EXISTS = 2,
98 EXIT_PROGRAM_NOT_RUNNING = 3,
99 EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN = 4,
100};
101
20b3f379 102static char **arg_types = NULL;
9b9b3d36 103static char **arg_states = NULL;
20b3f379 104static char **arg_properties = NULL;
7e4249b9 105static bool arg_all = false;
afba4199
ZJS
106static enum dependency {
107 DEPENDENCY_FORWARD,
108 DEPENDENCY_REVERSE,
109 DEPENDENCY_AFTER,
110 DEPENDENCY_BEFORE,
071066a5 111 _DEPENDENCY_MAX
afba4199 112} arg_dependency = DEPENDENCY_FORWARD;
e67c3609 113static const char *arg_job_mode = "replace";
729e3769 114static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
93a08841 115static bool arg_wait = false;
ee5762e3 116static bool arg_no_block = false;
ebed32bf 117static bool arg_no_legend = false;
0736af98 118static bool arg_no_pager = false;
e4b61340 119static bool arg_no_wtmp = false;
f3f054f0 120static bool arg_no_sync = false;
514f4ef5 121static bool arg_no_wall = false;
ee5762e3 122static bool arg_no_reload = false;
4f9a9105 123static bool arg_value = false;
991f2a39 124static bool arg_show_types = false;
b37844d3 125static bool arg_ignore_inhibitors = false;
1ae17672 126static bool arg_dry_run = false;
0183528f 127static bool arg_quiet = false;
ee5762e3 128static bool arg_full = false;
1238ee09 129static bool arg_recursive = false;
e606bb61 130static int arg_force = 0;
16f017fa 131static bool arg_ask_password = false;
729e3769 132static bool arg_runtime = false;
d309c1c3 133static UnitFilePresetMode arg_preset_mode = UNIT_FILE_PRESET_FULL;
e4b61340 134static char **arg_wall = NULL;
8a0867d6 135static const char *arg_kill_who = NULL;
8a0867d6 136static int arg_signal = SIGTERM;
0f03c2a4 137static char *arg_root = NULL;
f6144808 138static usec_t arg_when = 0;
4bb2e9d4 139static char *arg_esp_path = NULL;
acc28e2e 140static char *argv_cmdline = NULL;
4445a875 141static enum action {
e4b61340
LP
142 ACTION_SYSTEMCTL,
143 ACTION_HALT,
144 ACTION_POWEROFF,
145 ACTION_REBOOT,
20b09ca7
LP
146 ACTION_KEXEC,
147 ACTION_EXIT,
6edd7d0a
LP
148 ACTION_SUSPEND,
149 ACTION_HIBERNATE,
6524990f 150 ACTION_HYBRID_SLEEP,
e68c79db 151 ACTION_SUSPEND_THEN_HIBERNATE,
e4b61340
LP
152 ACTION_RUNLEVEL2,
153 ACTION_RUNLEVEL3,
154 ACTION_RUNLEVEL4,
155 ACTION_RUNLEVEL5,
156 ACTION_RESCUE,
514f4ef5
LP
157 ACTION_EMERGENCY,
158 ACTION_DEFAULT,
e4b61340
LP
159 ACTION_RELOAD,
160 ACTION_REEXEC,
161 ACTION_RUNLEVEL,
f6144808 162 ACTION_CANCEL_SHUTDOWN,
913c1916
AJ
163 _ACTION_MAX,
164 _ACTION_INVALID = -1
e4b61340 165} arg_action = ACTION_SYSTEMCTL;
f459b602 166static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
fc2ffaf1 167static const char *arg_host = NULL;
df50185b
LP
168static unsigned arg_lines = 10;
169static OutputMode arg_output = OUTPUT_SHORT;
5d0c05e5 170static bool arg_plain = false;
5bdf2243 171static bool arg_firmware_setup = false;
57ab2eab 172static bool arg_now = false;
82948f6c
LP
173static bool arg_jobs_before = false;
174static bool arg_jobs_after = false;
1238ee09 175
e449de87 176static int daemon_reload(int argc, char *argv[], void* userdata);
2853b60a 177static int trivial_method(int argc, char *argv[], void *userdata);
477def80 178static int halt_now(enum action a);
fa0d5878 179static int get_state_one_unit(sd_bus *bus, const char *name, UnitActiveState *active_state);
dbc2c080 180
4fbd7192
LP
181static bool original_stdout_is_tty;
182
183typedef enum BusFocus {
184 BUS_FULL, /* The full bus indicated via --system or --user */
185 BUS_MANAGER, /* The manager itself, possibly directly, possibly via the bus */
186 _BUS_FOCUS_MAX
187} BusFocus;
188
189static sd_bus *busses[_BUS_FOCUS_MAX] = {};
190
b3796dd8
JS
191static UnitFileFlags args_to_flags(void) {
192 return (arg_runtime ? UNIT_FILE_RUNTIME : 0) |
193 (arg_force ? UNIT_FILE_FORCE : 0);
194}
195
4fbd7192
LP
196static int acquire_bus(BusFocus focus, sd_bus **ret) {
197 int r;
198
199 assert(focus < _BUS_FOCUS_MAX);
200 assert(ret);
201
202 /* We only go directly to the manager, if we are using a local transport */
203 if (arg_transport != BUS_TRANSPORT_LOCAL)
204 focus = BUS_FULL;
205
d4015567
LP
206 if (getenv_bool("SYSTEMCTL_FORCE_BUS") > 0)
207 focus = BUS_FULL;
208
4fbd7192
LP
209 if (!busses[focus]) {
210 bool user;
211
212 user = arg_scope != UNIT_FILE_SYSTEM;
213
214 if (focus == BUS_MANAGER)
215 r = bus_connect_transport_systemd(arg_transport, arg_host, user, &busses[focus]);
216 else
217 r = bus_connect_transport(arg_transport, arg_host, user, &busses[focus]);
218 if (r < 0)
219 return log_error_errno(r, "Failed to connect to bus: %m");
220
221 (void) sd_bus_set_allow_interactive_authorization(busses[focus], arg_ask_password);
222 }
223
224 *ret = busses[focus];
225 return 0;
226}
227
228static void release_busses(void) {
229 BusFocus w;
230
231 for (w = 0; w < _BUS_FOCUS_MAX; w++)
232 busses[w] = sd_bus_flush_close_unref(busses[w]);
233}
234
6bb92a16 235static void ask_password_agent_open_if_enabled(void) {
729e3769 236 /* Open the password agent as a child process if necessary */
501fc174 237
1ae17672
ZJS
238 if (arg_dry_run)
239 return;
240
501fc174
LP
241 if (!arg_ask_password)
242 return;
715554e7 243
729e3769 244 if (arg_scope != UNIT_FILE_SYSTEM)
501fc174
LP
245 return;
246
cbc9fbd1
LP
247 if (arg_transport != BUS_TRANSPORT_LOCAL)
248 return;
249
6bb92a16
LP
250 ask_password_agent_open();
251}
252
8a4b13c5 253static void polkit_agent_open_maybe(void) {
6bb92a16
LP
254 /* Open the polkit agent as a child process if necessary */
255
6bb92a16
LP
256 if (arg_scope != UNIT_FILE_SYSTEM)
257 return;
258
8a4b13c5 259 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
501fc174
LP
260}
261
3c756001
LP
262static OutputFlags get_output_flags(void) {
263 return
264 arg_all * OUTPUT_SHOW_ALL |
459b9f9f 265 (arg_full || !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
40c9fe4c 266 colors_enabled() * OUTPUT_COLOR |
8b0cc9a3 267 !arg_quiet * OUTPUT_WARN_CUTOFF;
3c756001
LP
268}
269
f459b602 270static int translate_bus_error_to_exit_status(int r, const sd_bus_error *error) {
22f4096c
LP
271 assert(error);
272
f459b602 273 if (!sd_bus_error_is_set(error))
22f4096c
LP
274 return r;
275
f459b602
MAP
276 if (sd_bus_error_has_name(error, SD_BUS_ERROR_ACCESS_DENIED) ||
277 sd_bus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
278 sd_bus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
279 sd_bus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
22f4096c
LP
280 return EXIT_NOPERMISSION;
281
f459b602 282 if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
22f4096c
LP
283 return EXIT_NOTINSTALLED;
284
f459b602 285 if (sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
718db961 286 sd_bus_error_has_name(error, SD_BUS_ERROR_NOT_SUPPORTED))
22f4096c
LP
287 return EXIT_NOTIMPLEMENTED;
288
f459b602 289 if (sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
22f4096c
LP
290 return EXIT_NOTCONFIGURED;
291
292 if (r != 0)
293 return r;
294
295 return EXIT_FAILURE;
296}
297
4fbd7192 298static bool install_client_side(void) {
4fbd7192
LP
299 /* Decides when to execute enable/disable/... operations
300 * client-side rather than server-side. */
4f16c1f4 301
f38951a6 302 if (running_in_chroot_or_offline())
729e3769
LP
303 return true;
304
305 if (sd_booted() <= 0)
306 return true;
307
308 if (!isempty(arg_root))
309 return true;
310
311 if (arg_scope == UNIT_FILE_GLOBAL)
312 return true;
313
b41b9d2a
LP
314 /* Unsupported environment variable, mostly for debugging purposes */
315 if (getenv_bool("SYSTEMCTL_INSTALL_CLIENT_SIDE") > 0)
316 return true;
317
729e3769
LP
318 return false;
319}
320
36c32ba2 321static int compare_unit_info(const void *a, const void *b) {
f459b602 322 const UnitInfo *u = a, *v = b;
36c32ba2 323 const char *d1, *d2;
1238ee09
LP
324 int r;
325
326 /* First, order by machine */
327 if (!u->machine && v->machine)
328 return -1;
329 if (u->machine && !v->machine)
330 return 1;
331 if (u->machine && v->machine) {
332 r = strcasecmp(u->machine, v->machine);
333 if (r != 0)
334 return r;
335 }
36c32ba2 336
1238ee09 337 /* Second, order by unit type */
36c32ba2
LP
338 d1 = strrchr(u->id, '.');
339 d2 = strrchr(v->id, '.');
36c32ba2 340 if (d1 && d2) {
f84190d8
LP
341 r = strcasecmp(d1, d2);
342 if (r != 0)
36c32ba2
LP
343 return r;
344 }
345
1238ee09 346 /* Third, order by name */
a2a3a5b9 347 return strcasecmp(u->id, v->id);
36c32ba2
LP
348}
349
16484a8a
ZJS
350static const char* unit_type_suffix(const char *name) {
351 const char *dot;
352
353 dot = strrchr(name, '.');
354 if (!dot)
355 return "";
356
357 return dot + 1;
358}
359
d8fba7c6 360static bool output_show_unit(const UnitInfo *u, char **patterns) {
f8591ee1
LP
361 assert(u);
362
2404701e 363 if (!strv_fnmatch_or_empty(patterns, u->id, FNM_NOESCAPE))
d8fba7c6 364 return false;
d8fba7c6 365
16484a8a
ZJS
366 if (arg_types && !strv_find(arg_types, unit_type_suffix(u->id)))
367 return false;
6c71341a
ZJS
368
369 if (arg_all)
370 return true;
371
409472cb
FB
372 /* Note that '--all' is not purely a state filter, but also a
373 * filter that hides units that "follow" other units (which is
374 * used for device units that appear under different names). */
375 if (!isempty(u->following))
376 return false;
377
ebc96265
FB
378 if (!strv_isempty(arg_states))
379 return true;
380
381 /* By default show all units except the ones in inactive
382 * state and with no pending job */
6c71341a
ZJS
383 if (u->job_id > 0)
384 return true;
385
409472cb 386 if (streq(u->active_state, "inactive"))
6c71341a
ZJS
387 return false;
388
389 return true;
33330222
ZJS
390}
391
1238ee09 392static int output_units_list(const UnitInfo *unit_infos, unsigned c) {
b5d7f1bb 393 unsigned circle_len = 0, id_len, max_id_len, load_len, active_len, sub_len, job_len, desc_len, max_desc_len;
f459b602 394 const UnitInfo *u;
a1074881 395 unsigned n_shown = 0;
b5d7f1bb 396 int job_count = 0;
33330222 397
fbd0b64f
LP
398 max_id_len = STRLEN("UNIT");
399 load_len = STRLEN("LOAD");
400 active_len = STRLEN("ACTIVE");
401 sub_len = STRLEN("SUB");
402 job_len = STRLEN("JOB");
403 max_desc_len = STRLEN("DESCRIPTION");
b036fc00
LP
404
405 for (u = unit_infos; u < unit_infos + c; u++) {
1238ee09 406 max_id_len = MAX(max_id_len, strlen(u->id) + (u->machine ? strlen(u->machine)+1 : 0));
a1074881 407 load_len = MAX(load_len, strlen(u->load_state));
b036fc00
LP
408 active_len = MAX(active_len, strlen(u->active_state));
409 sub_len = MAX(sub_len, strlen(u->sub_state));
b5d7f1bb 410 max_desc_len = MAX(max_desc_len, strlen(u->description));
f459b602 411
ccd41387 412 if (u->job_id != 0) {
b036fc00 413 job_len = MAX(job_len, strlen(u->job_type));
ccd41387
ZJS
414 job_count++;
415 }
90c3f79d
LP
416
417 if (!arg_no_legend &&
418 (streq(u->active_state, "failed") ||
419 STR_IN_SET(u->load_state, "error", "not-found", "masked")))
420 circle_len = 2;
33330222
ZJS
421 }
422
184ecaf7 423 if (!arg_full && original_stdout_is_tty) {
4deb3b93 424 unsigned basic_len;
cbc9fbd1 425
b5d7f1bb 426 id_len = MIN(max_id_len, 25u); /* as much as it needs, but at most 25 for now */
a9bd056a 427 basic_len = circle_len + 1 + id_len + 1 + load_len + 1 + active_len + 1 + sub_len + 1;
cbc9fbd1 428
ccd41387
ZJS
429 if (job_count)
430 basic_len += job_len + 1;
cbc9fbd1 431
4deb3b93
MS
432 if (basic_len < (unsigned) columns()) {
433 unsigned extra_len, incr;
434 extra_len = columns() - basic_len;
cbc9fbd1 435
4deb3b93
MS
436 /* Either UNIT already got 25, or is fully satisfied.
437 * Grant up to 25 to DESC now. */
9607d947 438 incr = MIN(extra_len, 25u);
b5d7f1bb 439 desc_len = incr;
4deb3b93 440 extra_len -= incr;
cbc9fbd1 441
b5d7f1bb
LP
442 /* Of the remainder give as much as the ID needs to the ID, and give the rest to the
443 * description but not more than it needs. */
4deb3b93 444 if (extra_len > 0) {
b5d7f1bb 445 incr = MIN(max_id_len - id_len, extra_len);
4deb3b93 446 id_len += incr;
b5d7f1bb 447 desc_len += MIN(extra_len - incr, max_desc_len - desc_len);
4deb3b93 448 }
43479f8d
ZJS
449 } else
450 desc_len = 0;
b5d7f1bb 451 } else {
4deb3b93 452 id_len = max_id_len;
b5d7f1bb
LP
453 desc_len = max_desc_len;
454 }
4deb3b93 455
b036fc00 456 for (u = unit_infos; u < unit_infos + c; u++) {
1238ee09 457 _cleanup_free_ char *e = NULL, *j = NULL;
16484a8a 458 const char *on_underline = "", *off_underline = "";
90c3f79d
LP
459 const char *on_loaded = "", *off_loaded = "";
460 const char *on_active = "", *off_active = "";
461 const char *on_circle = "", *off_circle = "";
1238ee09 462 const char *id;
16484a8a 463 bool circle = false, underline = false;
b036fc00 464
ad94ad63 465 if (!n_shown && !arg_no_legend) {
90c3f79d
LP
466
467 if (circle_len > 0)
468 fputs(" ", stdout);
469
16484a8a
ZJS
470 printf("%s%-*s %-*s %-*s %-*s ",
471 ansi_underline(),
cbc9fbd1
LP
472 id_len, "UNIT",
473 load_len, "LOAD",
474 active_len, "ACTIVE",
475 sub_len, "SUB");
476
ccd41387
ZJS
477 if (job_count)
478 printf("%-*s ", job_len, "JOB");
cbc9fbd1 479
b5d7f1bb
LP
480 printf("%-*.*s%s\n",
481 desc_len,
482 !arg_full && arg_no_pager ? (int) desc_len : -1,
16484a8a
ZJS
483 "DESCRIPTION",
484 ansi_normal());
ad94ad63
ZJS
485 }
486
688c6725
LP
487 n_shown++;
488
16484a8a
ZJS
489 if (u + 1 < unit_infos + c &&
490 !streq(unit_type_suffix(u->id), unit_type_suffix((u + 1)->id))) {
491 on_underline = ansi_underline();
492 off_underline = ansi_normal();
493 underline = true;
494 }
495
250ba664 496 if (STR_IN_SET(u->load_state, "error", "not-found", "masked") && !arg_plain) {
90c3f79d 497 on_circle = ansi_highlight_yellow();
16484a8a 498 off_circle = ansi_normal();
90c3f79d 499 circle = true;
16484a8a 500 on_loaded = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
835a19e0 501 off_loaded = underline ? on_underline : ansi_normal();
250ba664 502 } else if (streq(u->active_state, "failed") && !arg_plain) {
16484a8a
ZJS
503 on_circle = ansi_highlight_red();
504 off_circle = ansi_normal();
90c3f79d 505 circle = true;
16484a8a 506 on_active = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
835a19e0 507 off_active = underline ? on_underline : ansi_normal();
90c3f79d 508 }
eb68c413 509
1238ee09 510 if (u->machine) {
605405c6 511 j = strjoin(u->machine, ":", u->id);
1238ee09
LP
512 if (!j)
513 return log_oom();
514
515 id = j;
516 } else
517 id = u->id;
518
519 if (arg_full) {
520 e = ellipsize(id, id_len, 33);
521 if (!e)
522 return log_oom();
523
524 id = e;
525 }
eb68c413 526
90c3f79d 527 if (circle_len > 0)
323b7dc9 528 printf("%s%s%s ", on_circle, circle ? special_glyph(BLACK_CIRCLE) : " ", off_circle);
90c3f79d 529
16484a8a
ZJS
530 printf("%s%s%-*s%s %s%-*s%s %s%-*s %-*s%s %-*s",
531 on_underline,
90c3f79d 532 on_active, id_len, id, off_active,
a1074881 533 on_loaded, load_len, u->load_state, off_loaded,
b036fc00
LP
534 on_active, active_len, u->active_state,
535 sub_len, u->sub_state, off_active,
ccd41387 536 job_count ? job_len + 1 : 0, u->job_id ? u->job_type : "");
cbc9fbd1 537
b5d7f1bb
LP
538 printf("%-*.*s%s\n",
539 desc_len,
540 !arg_full && arg_no_pager ? (int) desc_len : -1,
16484a8a
ZJS
541 u->description,
542 off_underline);
eb68c413
ZJS
543 }
544
ebed32bf 545 if (!arg_no_legend) {
57f7ae4f
ZJS
546 const char *on, *off;
547
548 if (n_shown) {
90c3f79d
LP
549 puts("\n"
550 "LOAD = Reflects whether the unit definition was properly loaded.\n"
e3e0314b
ZJS
551 "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
552 "SUB = The low-level unit activation state, values depend on unit type.");
553 puts(job_count ? "JOB = Pending job for the unit.\n" : "");
0b5a519c 554 on = ansi_highlight();
1fc464f6 555 off = ansi_normal();
57f7ae4f 556 } else {
0b5a519c 557 on = ansi_highlight_red();
1fc464f6 558 off = ansi_normal();
57f7ae4f 559 }
eb68c413
ZJS
560
561 if (arg_all)
48c2826b 562 printf("%s%u loaded units listed.%s\n"
57f7ae4f
ZJS
563 "To show all installed unit files use 'systemctl list-unit-files'.\n",
564 on, n_shown, off);
eb68c413 565 else
48c2826b 566 printf("%s%u loaded units listed.%s Pass --all to see loaded but inactive units, too.\n"
57f7ae4f
ZJS
567 "To show all installed unit files use 'systemctl list-unit-files'.\n",
568 on, n_shown, off);
eb68c413 569 }
1238ee09
LP
570
571 return 0;
eb68c413
ZJS
572}
573
a00963a2 574static int get_unit_list(
f459b602 575 sd_bus *bus,
1238ee09
LP
576 const char *machine,
577 char **patterns,
578 UnitInfo **unit_infos,
579 int c,
580 sd_bus_message **_reply) {
a00963a2 581
4afd3348
LP
582 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
583 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
584 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
ca2d3784 585 size_t size = c;
1238ee09 586 int r;
f459b602 587 UnitInfo u;
313fe66f 588 bool fallback = false;
7e4249b9 589
265a7a2a 590 assert(bus);
1238ee09 591 assert(unit_infos);
f459b602 592 assert(_reply);
1238ee09 593
cdc06ed7 594 r = sd_bus_message_new_method_call(
f22f08cd 595 bus,
cdc06ed7 596 &m,
f22f08cd
SP
597 "org.freedesktop.systemd1",
598 "/org/freedesktop/systemd1",
599 "org.freedesktop.systemd1.Manager",
313fe66f 600 "ListUnitsByPatterns");
cdc06ed7
DS
601 if (r < 0)
602 return bus_log_create_error(r);
603
604 r = sd_bus_message_append_strv(m, arg_states);
605 if (r < 0)
606 return bus_log_create_error(r);
607
313fe66f 608 r = sd_bus_message_append_strv(m, patterns);
609 if (r < 0)
610 return bus_log_create_error(r);
611
cdc06ed7 612 r = sd_bus_call(bus, m, 0, &error, &reply);
33d52725
ZJS
613 if (r < 0 && (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_METHOD) ||
614 sd_bus_error_has_name(&error, SD_BUS_ERROR_ACCESS_DENIED))) {
313fe66f 615 /* Fallback to legacy ListUnitsFiltered method */
616 fallback = true;
617 log_debug_errno(r, "Failed to list units: %s Falling back to ListUnitsFiltered method.", bus_error_message(&error, r));
618 m = sd_bus_message_unref(m);
619 sd_bus_error_free(&error);
620
621 r = sd_bus_message_new_method_call(
622 bus,
623 &m,
624 "org.freedesktop.systemd1",
625 "/org/freedesktop/systemd1",
626 "org.freedesktop.systemd1.Manager",
627 "ListUnitsFiltered");
628 if (r < 0)
629 return bus_log_create_error(r);
630
631 r = sd_bus_message_append_strv(m, arg_states);
632 if (r < 0)
633 return bus_log_create_error(r);
634
635 r = sd_bus_call(bus, m, 0, &error, &reply);
636 }
4c3e8e39
LP
637 if (r < 0)
638 return log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
7e4249b9 639
f459b602
MAP
640 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
641 if (r < 0)
642 return bus_log_parse_error(r);
7e4249b9 643
f459b602 644 while ((r = bus_parse_unit_info(reply, &u)) > 0) {
1238ee09
LP
645 u.machine = machine;
646
313fe66f 647 if (!output_show_unit(&u, fallback ? patterns : NULL))
8d5ba5a9 648 continue;
7e4249b9 649
1238ee09 650 if (!GREEDY_REALLOC(*unit_infos, size, c+1))
f459b602 651 return log_oom();
36c32ba2 652
1238ee09 653 (*unit_infos)[c++] = u;
991f2a39 654 }
f459b602
MAP
655 if (r < 0)
656 return bus_log_parse_error(r);
991f2a39 657
f459b602
MAP
658 r = sd_bus_message_exit_container(reply);
659 if (r < 0)
660 return bus_log_parse_error(r);
661
1cc6c93a 662 *_reply = TAKE_PTR(reply);
f459b602 663
1238ee09
LP
664 return c;
665}
666
667static void message_set_freep(Set **set) {
224b0e7a 668 set_free_with_destructor(*set, sd_bus_message_unref);
1238ee09
LP
669}
670
671static int get_unit_list_recursive(
672 sd_bus *bus,
673 char **patterns,
674 UnitInfo **_unit_infos,
675 Set **_replies,
676 char ***_machines) {
677
678 _cleanup_free_ UnitInfo *unit_infos = NULL;
679 _cleanup_(message_set_freep) Set *replies;
680 sd_bus_message *reply;
681 int c, r;
682
683 assert(bus);
684 assert(_replies);
685 assert(_unit_infos);
686 assert(_machines);
687
d5099efc 688 replies = set_new(NULL);
1238ee09
LP
689 if (!replies)
690 return log_oom();
691
692 c = get_unit_list(bus, NULL, patterns, &unit_infos, 0, &reply);
693 if (c < 0)
694 return c;
695
696 r = set_put(replies, reply);
697 if (r < 0) {
698 sd_bus_message_unref(reply);
4c3e8e39 699 return log_oom();
1238ee09
LP
700 }
701
702 if (arg_recursive) {
703 _cleanup_strv_free_ char **machines = NULL;
704 char **i;
705
706 r = sd_get_machine_names(&machines);
707 if (r < 0)
4c3e8e39 708 return log_error_errno(r, "Failed to get machine names: %m");
1238ee09
LP
709
710 STRV_FOREACH(i, machines) {
4afd3348 711 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *container = NULL;
1238ee09
LP
712 int k;
713
de33fc62 714 r = sd_bus_open_system_machine(&container, *i);
1238ee09 715 if (r < 0) {
4c3e8e39 716 log_warning_errno(r, "Failed to connect to container %s, ignoring: %m", *i);
1238ee09
LP
717 continue;
718 }
719
720 k = get_unit_list(container, *i, patterns, &unit_infos, c, &reply);
721 if (k < 0)
722 return k;
723
724 c = k;
725
726 r = set_put(replies, reply);
727 if (r < 0) {
728 sd_bus_message_unref(reply);
4c3e8e39 729 return log_oom();
1238ee09
LP
730 }
731 }
732
1cc6c93a 733 *_machines = TAKE_PTR(machines);
1238ee09
LP
734 } else
735 *_machines = NULL;
736
1cc6c93a 737 *_unit_infos = TAKE_PTR(unit_infos);
f459b602 738
1cc6c93a 739 *_replies = TAKE_PTR(replies);
1238ee09 740
f459b602 741 return c;
991f2a39
ZJS
742}
743
e449de87 744static int list_units(int argc, char *argv[], void *userdata) {
f459b602 745 _cleanup_free_ UnitInfo *unit_infos = NULL;
1238ee09
LP
746 _cleanup_(message_set_freep) Set *replies = NULL;
747 _cleanup_strv_free_ char **machines = NULL;
4fbd7192 748 sd_bus *bus;
991f2a39
ZJS
749 int r;
750
4fbd7192
LP
751 r = acquire_bus(BUS_MANAGER, &bus);
752 if (r < 0)
753 return r;
754
ee5324aa 755 (void) pager_open(arg_no_pager, false);
d2ad7e1b 756
e449de87 757 r = get_unit_list_recursive(bus, strv_skip(argv, 1), &unit_infos, &replies, &machines);
991f2a39
ZJS
758 if (r < 0)
759 return r;
760
f459b602 761 qsort_safe(unit_infos, r, sizeof(UnitInfo), compare_unit_info);
1238ee09 762 return output_units_list(unit_infos, r);
991f2a39
ZJS
763}
764
a00963a2 765static int get_triggered_units(
f459b602
MAP
766 sd_bus *bus,
767 const char* path,
768 char*** ret) {
a00963a2 769
4afd3348 770 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
991f2a39
ZJS
771 int r;
772
4fbd7192
LP
773 assert(bus);
774 assert(path);
775 assert(ret);
776
f459b602
MAP
777 r = sd_bus_get_property_strv(
778 bus,
779 "org.freedesktop.systemd1",
780 path,
781 "org.freedesktop.systemd1.Unit",
782 "Triggers",
783 &error,
784 ret);
f459b602 785 if (r < 0)
691395d8 786 return log_error_errno(r, "Failed to determine triggers: %s", bus_error_message(&error, r));
991f2a39
ZJS
787
788 return 0;
789}
790
f459b602
MAP
791static int get_listening(
792 sd_bus *bus,
793 const char* unit_path,
cbb76c29 794 char*** listening) {
f459b602 795
4afd3348
LP
796 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
797 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602 798 const char *type, *path;
cbb76c29 799 int r, n = 0;
991f2a39 800
f459b602
MAP
801 r = sd_bus_get_property(
802 bus,
803 "org.freedesktop.systemd1",
804 unit_path,
805 "org.freedesktop.systemd1.Socket",
806 "Listen",
807 &error,
808 &reply,
809 "a(ss)");
691395d8
LP
810 if (r < 0)
811 return log_error_errno(r, "Failed to get list of listening sockets: %s", bus_error_message(&error, r));
991f2a39 812
f459b602
MAP
813 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
814 if (r < 0)
815 return bus_log_parse_error(r);
991f2a39 816
f459b602 817 while ((r = sd_bus_message_read(reply, "(ss)", &type, &path)) > 0) {
36c32ba2 818
0d95178e 819 r = strv_extend(listening, type);
f459b602
MAP
820 if (r < 0)
821 return log_oom();
991f2a39 822
0d95178e 823 r = strv_extend(listening, path);
f459b602
MAP
824 if (r < 0)
825 return log_oom();
7e4249b9 826
cbb76c29 827 n++;
36c32ba2 828 }
f459b602
MAP
829 if (r < 0)
830 return bus_log_parse_error(r);
831
832 r = sd_bus_message_exit_container(reply);
833 if (r < 0)
834 return bus_log_parse_error(r);
36c32ba2 835
cbb76c29 836 return n;
991f2a39
ZJS
837}
838
839struct socket_info {
0cfc3525 840 const char *machine;
991f2a39
ZJS
841 const char* id;
842
843 char* type;
844 char* path;
845
846 /* Note: triggered is a list here, although it almost certainly
847 * will always be one unit. Nevertheless, dbus API allows for multiple
f7340ab2 848 * values, so let's follow that. */
991f2a39
ZJS
849 char** triggered;
850
851 /* The strv above is shared. free is set only in the first one. */
852 bool own_triggered;
853};
854
cbb76c29 855static int socket_info_compare(const struct socket_info *a, const struct socket_info *b) {
cbc9fbd1
LP
856 int o;
857
cbb76c29
LP
858 assert(a);
859 assert(b);
860
0cfc3525
TA
861 if (!a->machine && b->machine)
862 return -1;
863 if (a->machine && !b->machine)
864 return 1;
865 if (a->machine && b->machine) {
866 o = strcasecmp(a->machine, b->machine);
867 if (o != 0)
868 return o;
869 }
870
cbc9fbd1 871 o = strcmp(a->path, b->path);
991f2a39
ZJS
872 if (o == 0)
873 o = strcmp(a->type, b->type);
cbc9fbd1 874
991f2a39
ZJS
875 return o;
876}
877
878static int output_sockets_list(struct socket_info *socket_infos, unsigned cs) {
879 struct socket_info *s;
fbd0b64f
LP
880 unsigned pathlen = STRLEN("LISTEN"),
881 typelen = STRLEN("TYPE") * arg_show_types,
882 socklen = STRLEN("UNIT"),
883 servlen = STRLEN("ACTIVATES");
991f2a39
ZJS
884 const char *on, *off;
885
886 for (s = socket_infos; s < socket_infos + cs; s++) {
991f2a39 887 unsigned tmp = 0;
cbc9fbd1 888 char **a;
991f2a39
ZJS
889
890 socklen = MAX(socklen, strlen(s->id));
891 if (arg_show_types)
892 typelen = MAX(typelen, strlen(s->type));
0cfc3525 893 pathlen = MAX(pathlen, strlen(s->path) + (s->machine ? strlen(s->machine)+1 : 0));
991f2a39
ZJS
894
895 STRV_FOREACH(a, s->triggered)
896 tmp += strlen(*a) + 2*(a != s->triggered);
897 servlen = MAX(servlen, tmp);
898 }
899
900 if (cs) {
571bfc6c
MM
901 if (!arg_no_legend)
902 printf("%-*s %-*.*s%-*s %s\n",
903 pathlen, "LISTEN",
904 typelen + arg_show_types, typelen + arg_show_types, "TYPE ",
905 socklen, "UNIT",
906 "ACTIVATES");
991f2a39
ZJS
907
908 for (s = socket_infos; s < socket_infos + cs; s++) {
0cfc3525
TA
909 _cleanup_free_ char *j = NULL;
910 const char *path;
991f2a39
ZJS
911 char **a;
912
0cfc3525 913 if (s->machine) {
605405c6 914 j = strjoin(s->machine, ":", s->path);
0cfc3525
TA
915 if (!j)
916 return log_oom();
917 path = j;
918 } else
919 path = s->path;
920
991f2a39
ZJS
921 if (arg_show_types)
922 printf("%-*s %-*s %-*s",
0cfc3525 923 pathlen, path, typelen, s->type, socklen, s->id);
991f2a39
ZJS
924 else
925 printf("%-*s %-*s",
0cfc3525 926 pathlen, path, socklen, s->id);
991f2a39
ZJS
927 STRV_FOREACH(a, s->triggered)
928 printf("%s %s",
929 a == s->triggered ? "" : ",", *a);
930 printf("\n");
931 }
932
0b5a519c 933 on = ansi_highlight();
1fc464f6 934 off = ansi_normal();
571bfc6c
MM
935 if (!arg_no_legend)
936 printf("\n");
991f2a39 937 } else {
0b5a519c 938 on = ansi_highlight_red();
1fc464f6 939 off = ansi_normal();
991f2a39
ZJS
940 }
941
571bfc6c
MM
942 if (!arg_no_legend) {
943 printf("%s%u sockets listed.%s\n", on, cs, off);
944 if (!arg_all)
945 printf("Pass --all to see loaded but inactive sockets, too.\n");
946 }
265a7a2a
ZJS
947
948 return 0;
949}
950
e449de87 951static int list_sockets(int argc, char *argv[], void *userdata) {
0cfc3525
TA
952 _cleanup_(message_set_freep) Set *replies = NULL;
953 _cleanup_strv_free_ char **machines = NULL;
f459b602 954 _cleanup_free_ UnitInfo *unit_infos = NULL;
8d5ba5a9 955 _cleanup_free_ struct socket_info *socket_infos = NULL;
f459b602 956 const UnitInfo *u;
991f2a39 957 struct socket_info *s;
cbb76c29 958 unsigned cs = 0;
991f2a39 959 size_t size = 0;
ad83b4c4 960 int r = 0, n;
4fbd7192 961 sd_bus *bus;
265a7a2a 962
4fbd7192
LP
963 r = acquire_bus(BUS_MANAGER, &bus);
964 if (r < 0)
965 return r;
966
ee5324aa 967 (void) pager_open(arg_no_pager, false);
d2ad7e1b 968
e449de87 969 n = get_unit_list_recursive(bus, strv_skip(argv, 1), &unit_infos, &replies, &machines);
cbb76c29
LP
970 if (n < 0)
971 return n;
265a7a2a 972
cbb76c29 973 for (u = unit_infos; u < unit_infos + n; u++) {
0d95178e 974 _cleanup_strv_free_ char **listening = NULL, **triggered = NULL;
cbb76c29 975 int i, c;
991f2a39 976
cbc9fbd1 977 if (!endswith(u->id, ".socket"))
991f2a39
ZJS
978 continue;
979
980 r = get_triggered_units(bus, u->unit_path, &triggered);
981 if (r < 0)
982 goto cleanup;
983
cbb76c29
LP
984 c = get_listening(bus, u->unit_path, &listening);
985 if (c < 0) {
986 r = c;
991f2a39 987 goto cleanup;
cbb76c29 988 }
991f2a39
ZJS
989
990 if (!GREEDY_REALLOC(socket_infos, size, cs + c)) {
991 r = log_oom();
992 goto cleanup;
993 }
994
995 for (i = 0; i < c; i++)
996 socket_infos[cs + i] = (struct socket_info) {
0cfc3525 997 .machine = u->machine,
991f2a39 998 .id = u->id,
0d95178e
KS
999 .type = listening[i*2],
1000 .path = listening[i*2 + 1],
991f2a39
ZJS
1001 .triggered = triggered,
1002 .own_triggered = i==0,
1003 };
1004
1005 /* from this point on we will cleanup those socket_infos */
1006 cs += c;
0d95178e
KS
1007 free(listening);
1008 listening = triggered = NULL; /* avoid cleanup */
991f2a39
ZJS
1009 }
1010
7ff7394d
ZJS
1011 qsort_safe(socket_infos, cs, sizeof(struct socket_info),
1012 (__compar_fn_t) socket_info_compare);
991f2a39
ZJS
1013
1014 output_sockets_list(socket_infos, cs);
1015
1016 cleanup:
1017 assert(cs == 0 || socket_infos);
1018 for (s = socket_infos; s < socket_infos + cs; s++) {
1019 free(s->type);
1020 free(s->path);
1021 if (s->own_triggered)
1022 strv_free(s->triggered);
1023 }
4445a875 1024
872c8faa 1025 return r;
4445a875
LP
1026}
1027
cbb76c29
LP
1028static int get_next_elapse(
1029 sd_bus *bus,
1030 const char *path,
1031 dual_timestamp *next) {
1032
4afd3348 1033 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
cbb76c29
LP
1034 dual_timestamp t;
1035 int r;
1036
1037 assert(bus);
1038 assert(path);
1039 assert(next);
1040
1041 r = sd_bus_get_property_trivial(
1042 bus,
1043 "org.freedesktop.systemd1",
1044 path,
1045 "org.freedesktop.systemd1.Timer",
1046 "NextElapseUSecMonotonic",
1047 &error,
1048 't',
1049 &t.monotonic);
691395d8 1050 if (r < 0)
021723c6 1051 return log_error_errno(r, "Failed to get next elapse time: %s", bus_error_message(&error, r));
cbb76c29
LP
1052
1053 r = sd_bus_get_property_trivial(
1054 bus,
1055 "org.freedesktop.systemd1",
1056 path,
1057 "org.freedesktop.systemd1.Timer",
1058 "NextElapseUSecRealtime",
1059 &error,
1060 't',
1061 &t.realtime);
691395d8 1062 if (r < 0)
021723c6 1063 return log_error_errno(r, "Failed to get next elapse time: %s", bus_error_message(&error, r));
cbb76c29
LP
1064
1065 *next = t;
1066 return 0;
1067}
1068
d784e2db
LP
1069static int get_last_trigger(
1070 sd_bus *bus,
1071 const char *path,
1072 usec_t *last) {
1073
4afd3348 1074 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
d784e2db
LP
1075 int r;
1076
1077 assert(bus);
1078 assert(path);
1079 assert(last);
1080
1081 r = sd_bus_get_property_trivial(
1082 bus,
1083 "org.freedesktop.systemd1",
1084 path,
1085 "org.freedesktop.systemd1.Timer",
dedabea4 1086 "LastTriggerUSec",
d784e2db
LP
1087 &error,
1088 't',
1089 last);
691395d8
LP
1090 if (r < 0)
1091 return log_error_errno(r, "Failed to get last trigger time: %s", bus_error_message(&error, r));
d784e2db
LP
1092
1093 return 0;
1094}
1095
cbb76c29 1096struct timer_info {
806a37e7 1097 const char* machine;
cbb76c29
LP
1098 const char* id;
1099 usec_t next_elapse;
d784e2db 1100 usec_t last_trigger;
cbb76c29
LP
1101 char** triggered;
1102};
1103
1104static int timer_info_compare(const struct timer_info *a, const struct timer_info *b) {
806a37e7
TA
1105 int o;
1106
cbb76c29
LP
1107 assert(a);
1108 assert(b);
1109
806a37e7
TA
1110 if (!a->machine && b->machine)
1111 return -1;
1112 if (a->machine && !b->machine)
1113 return 1;
1114 if (a->machine && b->machine) {
1115 o = strcasecmp(a->machine, b->machine);
1116 if (o != 0)
1117 return o;
1118 }
1119
cbb76c29
LP
1120 if (a->next_elapse < b->next_elapse)
1121 return -1;
1122 if (a->next_elapse > b->next_elapse)
1123 return 1;
1124
1125 return strcmp(a->id, b->id);
1126}
1127
1128static int output_timers_list(struct timer_info *timer_infos, unsigned n) {
1129 struct timer_info *t;
1130 unsigned
fbd0b64f
LP
1131 nextlen = STRLEN("NEXT"),
1132 leftlen = STRLEN("LEFT"),
1133 lastlen = STRLEN("LAST"),
1134 passedlen = STRLEN("PASSED"),
1135 unitlen = STRLEN("UNIT"),
1136 activatelen = STRLEN("ACTIVATES");
cbb76c29
LP
1137
1138 const char *on, *off;
1139
1140 assert(timer_infos || n == 0);
1141
1142 for (t = timer_infos; t < timer_infos + n; t++) {
1143 unsigned ul = 0;
1144 char **a;
1145
1146 if (t->next_elapse > 0) {
1147 char tstamp[FORMAT_TIMESTAMP_MAX] = "", trel[FORMAT_TIMESTAMP_RELATIVE_MAX] = "";
1148
1149 format_timestamp(tstamp, sizeof(tstamp), t->next_elapse);
1150 nextlen = MAX(nextlen, strlen(tstamp) + 1);
1151
1152 format_timestamp_relative(trel, sizeof(trel), t->next_elapse);
1153 leftlen = MAX(leftlen, strlen(trel));
1154 }
1155
d784e2db
LP
1156 if (t->last_trigger > 0) {
1157 char tstamp[FORMAT_TIMESTAMP_MAX] = "", trel[FORMAT_TIMESTAMP_RELATIVE_MAX] = "";
1158
1159 format_timestamp(tstamp, sizeof(tstamp), t->last_trigger);
1160 lastlen = MAX(lastlen, strlen(tstamp) + 1);
1161
1162 format_timestamp_relative(trel, sizeof(trel), t->last_trigger);
1163 passedlen = MAX(passedlen, strlen(trel));
1164 }
1165
806a37e7 1166 unitlen = MAX(unitlen, strlen(t->id) + (t->machine ? strlen(t->machine)+1 : 0));
cbb76c29
LP
1167
1168 STRV_FOREACH(a, t->triggered)
1169 ul += strlen(*a) + 2*(a != t->triggered);
d784e2db 1170
cbb76c29
LP
1171 activatelen = MAX(activatelen, ul);
1172 }
1173
1174 if (n > 0) {
1175 if (!arg_no_legend)
d784e2db
LP
1176 printf("%-*s %-*s %-*s %-*s %-*s %s\n",
1177 nextlen, "NEXT",
1178 leftlen, "LEFT",
1179 lastlen, "LAST",
1180 passedlen, "PASSED",
1181 unitlen, "UNIT",
1182 "ACTIVATES");
cbb76c29
LP
1183
1184 for (t = timer_infos; t < timer_infos + n; t++) {
806a37e7
TA
1185 _cleanup_free_ char *j = NULL;
1186 const char *unit;
d784e2db
LP
1187 char tstamp1[FORMAT_TIMESTAMP_MAX] = "n/a", trel1[FORMAT_TIMESTAMP_RELATIVE_MAX] = "n/a";
1188 char tstamp2[FORMAT_TIMESTAMP_MAX] = "n/a", trel2[FORMAT_TIMESTAMP_RELATIVE_MAX] = "n/a";
cbb76c29
LP
1189 char **a;
1190
d784e2db
LP
1191 format_timestamp(tstamp1, sizeof(tstamp1), t->next_elapse);
1192 format_timestamp_relative(trel1, sizeof(trel1), t->next_elapse);
cbb76c29 1193
d784e2db
LP
1194 format_timestamp(tstamp2, sizeof(tstamp2), t->last_trigger);
1195 format_timestamp_relative(trel2, sizeof(trel2), t->last_trigger);
1196
806a37e7 1197 if (t->machine) {
605405c6 1198 j = strjoin(t->machine, ":", t->id);
806a37e7
TA
1199 if (!j)
1200 return log_oom();
1201 unit = j;
1202 } else
1203 unit = t->id;
1204
d784e2db 1205 printf("%-*s %-*s %-*s %-*s %-*s",
806a37e7 1206 nextlen, tstamp1, leftlen, trel1, lastlen, tstamp2, passedlen, trel2, unitlen, unit);
cbb76c29
LP
1207
1208 STRV_FOREACH(a, t->triggered)
1209 printf("%s %s",
1210 a == t->triggered ? "" : ",", *a);
1211 printf("\n");
1212 }
1213
1214 on = ansi_highlight();
1fc464f6 1215 off = ansi_normal();
cbb76c29
LP
1216 if (!arg_no_legend)
1217 printf("\n");
1218 } else {
1219 on = ansi_highlight_red();
1fc464f6 1220 off = ansi_normal();
cbb76c29
LP
1221 }
1222
1223 if (!arg_no_legend) {
1224 printf("%s%u timers listed.%s\n", on, n, off);
1225 if (!arg_all)
1226 printf("Pass --all to see loaded but inactive timers, too.\n");
1227 }
1228
1229 return 0;
1230}
1231
f5080e73
DH
1232static usec_t calc_next_elapse(dual_timestamp *nw, dual_timestamp *next) {
1233 usec_t next_elapse;
1234
1235 assert(nw);
1236 assert(next);
1237
3a43da28 1238 if (next->monotonic != USEC_INFINITY && next->monotonic > 0) {
f5080e73
DH
1239 usec_t converted;
1240
1241 if (next->monotonic > nw->monotonic)
1242 converted = nw->realtime + (next->monotonic - nw->monotonic);
1243 else
1244 converted = nw->realtime - (nw->monotonic - next->monotonic);
1245
3a43da28 1246 if (next->realtime != USEC_INFINITY && next->realtime > 0)
f5080e73
DH
1247 next_elapse = MIN(converted, next->realtime);
1248 else
1249 next_elapse = converted;
1250
1251 } else
1252 next_elapse = next->realtime;
1253
1254 return next_elapse;
1255}
1256
e449de87 1257static int list_timers(int argc, char *argv[], void *userdata) {
806a37e7
TA
1258 _cleanup_(message_set_freep) Set *replies = NULL;
1259 _cleanup_strv_free_ char **machines = NULL;
cbb76c29
LP
1260 _cleanup_free_ struct timer_info *timer_infos = NULL;
1261 _cleanup_free_ UnitInfo *unit_infos = NULL;
1262 struct timer_info *t;
1263 const UnitInfo *u;
1264 size_t size = 0;
1823b86e 1265 int n, c = 0;
cbb76c29 1266 dual_timestamp nw;
4fbd7192 1267 sd_bus *bus;
1823b86e 1268 int r = 0;
cbb76c29 1269
4fbd7192
LP
1270 r = acquire_bus(BUS_MANAGER, &bus);
1271 if (r < 0)
1272 return r;
1273
ee5324aa 1274 (void) pager_open(arg_no_pager, false);
d2ad7e1b 1275
e449de87 1276 n = get_unit_list_recursive(bus, strv_skip(argv, 1), &unit_infos, &replies, &machines);
cbb76c29
LP
1277 if (n < 0)
1278 return n;
1279
1280 dual_timestamp_get(&nw);
1281
1282 for (u = unit_infos; u < unit_infos + n; u++) {
1283 _cleanup_strv_free_ char **triggered = NULL;
5cb14b37 1284 dual_timestamp next = DUAL_TIMESTAMP_NULL;
d784e2db 1285 usec_t m, last = 0;
cbb76c29 1286
cbb76c29
LP
1287 if (!endswith(u->id, ".timer"))
1288 continue;
1289
1290 r = get_triggered_units(bus, u->unit_path, &triggered);
1291 if (r < 0)
1292 goto cleanup;
1293
1294 r = get_next_elapse(bus, u->unit_path, &next);
1295 if (r < 0)
1296 goto cleanup;
1297
d784e2db
LP
1298 get_last_trigger(bus, u->unit_path, &last);
1299
cbb76c29
LP
1300 if (!GREEDY_REALLOC(timer_infos, size, c+1)) {
1301 r = log_oom();
1302 goto cleanup;
1303 }
1304
f5080e73
DH
1305 m = calc_next_elapse(&nw, &next);
1306
cbb76c29 1307 timer_infos[c++] = (struct timer_info) {
806a37e7 1308 .machine = u->machine,
cbb76c29
LP
1309 .id = u->id,
1310 .next_elapse = m,
d784e2db 1311 .last_trigger = last,
1cc6c93a 1312 .triggered = TAKE_PTR(triggered),
cbb76c29 1313 };
cbb76c29
LP
1314 }
1315
1316 qsort_safe(timer_infos, c, sizeof(struct timer_info),
1317 (__compar_fn_t) timer_info_compare);
1318
1319 output_timers_list(timer_infos, c);
1320
1321 cleanup:
1322 for (t = timer_infos; t < timer_infos + c; t++)
1323 strv_free(t->triggered);
1324
1325 return r;
1326}
1327
729e3769
LP
1328static int compare_unit_file_list(const void *a, const void *b) {
1329 const char *d1, *d2;
1330 const UnitFileList *u = a, *v = b;
1331
1332 d1 = strrchr(u->path, '.');
1333 d2 = strrchr(v->path, '.');
1334
1335 if (d1 && d2) {
1336 int r;
1337
1338 r = strcasecmp(d1, d2);
1339 if (r != 0)
1340 return r;
1341 }
1342
2b6bf07d 1343 return strcasecmp(basename(u->path), basename(v->path));
729e3769
LP
1344}
1345
313fe66f 1346static bool output_show_unit_file(const UnitFileList *u, char **states, char **patterns) {
f8591ee1
LP
1347 assert(u);
1348
2404701e 1349 if (!strv_fnmatch_or_empty(patterns, basename(u->path), FNM_NOESCAPE))
d8fba7c6 1350 return false;
d8fba7c6 1351
6c71341a
ZJS
1352 if (!strv_isempty(arg_types)) {
1353 const char *dot;
1354
1355 dot = strrchr(u->path, '.');
1356 if (!dot)
1357 return false;
1358
1359 if (!strv_find(arg_types, dot+1))
1360 return false;
1361 }
1362
313fe66f 1363 if (!strv_isempty(states) &&
1364 !strv_find(states, unit_file_state_to_string(u->state)))
bceccd5e 1365 return false;
fec1530e 1366
6c71341a 1367 return true;
729e3769
LP
1368}
1369
8d5ba5a9 1370static void output_unit_file_list(const UnitFileList *units, unsigned c) {
0d292f5e 1371 unsigned max_id_len, id_cols, state_cols;
729e3769
LP
1372 const UnitFileList *u;
1373
fbd0b64f
LP
1374 max_id_len = STRLEN("UNIT FILE");
1375 state_cols = STRLEN("STATE");
cbc9fbd1 1376
1c0a113f 1377 for (u = units; u < units + c; u++) {
2b6bf07d 1378 max_id_len = MAX(max_id_len, strlen(basename(u->path)));
1c0a113f
ZJS
1379 state_cols = MAX(state_cols, strlen(unit_file_state_to_string(u->state)));
1380 }
1381
1382 if (!arg_full) {
1383 unsigned basic_cols;
cbc9fbd1 1384
9607d947 1385 id_cols = MIN(max_id_len, 25u);
1c0a113f
ZJS
1386 basic_cols = 1 + id_cols + state_cols;
1387 if (basic_cols < (unsigned) columns())
1388 id_cols += MIN(columns() - basic_cols, max_id_len - id_cols);
1389 } else
1390 id_cols = max_id_len;
1391
11690bcc 1392 if (!arg_no_legend && c > 0)
6ae3e62a
ZJS
1393 printf("%s%-*s %-*s%s\n",
1394 ansi_underline(),
cbc9fbd1 1395 id_cols, "UNIT FILE",
6ae3e62a
ZJS
1396 state_cols, "STATE",
1397 ansi_normal());
729e3769
LP
1398
1399 for (u = units; u < units + c; u++) {
aaa6732d 1400 const char *on_underline = NULL, *on_color = NULL, *off = NULL, *id;
7fd1b19b 1401 _cleanup_free_ char *e = NULL;
aaa6732d
LP
1402 bool underline;
1403
1404 underline = u + 1 < units + c &&
1405 !streq(unit_type_suffix(u->path), unit_type_suffix((u + 1)->path));
6ae3e62a 1406
aaa6732d 1407 if (underline)
6ae3e62a 1408 on_underline = ansi_underline();
729e3769 1409
4c315c2c
IS
1410 if (IN_SET(u->state,
1411 UNIT_FILE_MASKED,
1412 UNIT_FILE_MASKED_RUNTIME,
1413 UNIT_FILE_DISABLED,
6ae3e62a 1414 UNIT_FILE_BAD))
aaa6732d 1415 on_color = underline ? ansi_highlight_red_underline() : ansi_highlight_red();
6ae3e62a 1416 else if (u->state == UNIT_FILE_ENABLED)
aaa6732d
LP
1417 on_color = underline ? ansi_highlight_green_underline() : ansi_highlight_green();
1418
1419 if (on_underline || on_color)
1420 off = ansi_normal();
729e3769 1421
2b6bf07d 1422 id = basename(u->path);
729e3769 1423
1c0a113f 1424 e = arg_full ? NULL : ellipsize(id, id_cols, 33);
729e3769 1425
aaa6732d
LP
1426 printf("%s%-*s %s%-*s%s\n",
1427 strempty(on_underline),
1c0a113f 1428 id_cols, e ? e : id,
aaa6732d 1429 strempty(on_color), state_cols, unit_file_state_to_string(u->state), strempty(off));
729e3769
LP
1430 }
1431
1c0a113f 1432 if (!arg_no_legend)
0d292f5e 1433 printf("\n%u unit files listed.\n", c);
729e3769
LP
1434}
1435
e449de87 1436static int list_unit_files(int argc, char *argv[], void *userdata) {
4afd3348 1437 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f84190d8 1438 _cleanup_free_ UnitFileList *units = NULL;
8d5ba5a9
ZJS
1439 UnitFileList *unit;
1440 size_t size = 0;
f459b602
MAP
1441 unsigned c = 0;
1442 const char *state;
1443 char *path;
f84190d8 1444 int r;
313fe66f 1445 bool fallback = false;
729e3769 1446
4fbd7192 1447 if (install_client_side()) {
729e3769
LP
1448 Hashmap *h;
1449 UnitFileList *u;
1450 Iterator i;
f459b602 1451 unsigned n_units;
729e3769 1452
d5099efc 1453 h = hashmap_new(&string_hash_ops);
0d0f0c50
SL
1454 if (!h)
1455 return log_oom();
729e3769 1456
313fe66f 1457 r = unit_file_get_list(arg_scope, arg_root, h, arg_states, strv_skip(argv, 1));
729e3769 1458 if (r < 0) {
8ea913b2 1459 unit_file_list_free(h);
691395d8 1460 return log_error_errno(r, "Failed to get unit file list: %m");
729e3769
LP
1461 }
1462
1463 n_units = hashmap_size(h);
fdbdf6ec 1464
0da999fa
ZJS
1465 units = new(UnitFileList, n_units ?: 1); /* avoid malloc(0) */
1466 if (!units) {
729e3769 1467 unit_file_list_free(h);
0d0f0c50 1468 return log_oom();
729e3769
LP
1469 }
1470
1471 HASHMAP_FOREACH(u, h, i) {
313fe66f 1472 if (!output_show_unit_file(u, NULL, NULL))
8d5ba5a9
ZJS
1473 continue;
1474
1475 units[c++] = *u;
729e3769
LP
1476 free(u);
1477 }
1478
8d5ba5a9 1479 assert(c <= n_units);
729e3769 1480 hashmap_free(h);
5f056378
CH
1481
1482 r = 0;
729e3769 1483 } else {
313fe66f 1484 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
4afd3348 1485 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192
LP
1486 sd_bus *bus;
1487
1488 r = acquire_bus(BUS_MANAGER, &bus);
1489 if (r < 0)
1490 return r;
6e646d22 1491
313fe66f 1492 r = sd_bus_message_new_method_call(
f22f08cd 1493 bus,
313fe66f 1494 &m,
729e3769
LP
1495 "org.freedesktop.systemd1",
1496 "/org/freedesktop/systemd1",
1497 "org.freedesktop.systemd1.Manager",
313fe66f 1498 "ListUnitFilesByPatterns");
1499 if (r < 0)
1500 return bus_log_create_error(r);
1501
1502 r = sd_bus_message_append_strv(m, arg_states);
1503 if (r < 0)
1504 return bus_log_create_error(r);
1505
1506 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
1507 if (r < 0)
1508 return bus_log_create_error(r);
1509
1510 r = sd_bus_call(bus, m, 0, &error, &reply);
1511 if (r < 0 && sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
1512 /* Fallback to legacy ListUnitFiles method */
1513 fallback = true;
1514 log_debug_errno(r, "Failed to list unit files: %s Falling back to ListUnitsFiles method.", bus_error_message(&error, r));
1515 m = sd_bus_message_unref(m);
1516 sd_bus_error_free(&error);
1517
1518 r = sd_bus_message_new_method_call(
1519 bus,
1520 &m,
1521 "org.freedesktop.systemd1",
1522 "/org/freedesktop/systemd1",
1523 "org.freedesktop.systemd1.Manager",
1524 "ListUnitFiles");
1525 if (r < 0)
1526 return bus_log_create_error(r);
1527
1528 r = sd_bus_call(bus, m, 0, &error, &reply);
1529 }
691395d8
LP
1530 if (r < 0)
1531 return log_error_errno(r, "Failed to list unit files: %s", bus_error_message(&error, r));
729e3769 1532
f459b602
MAP
1533 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ss)");
1534 if (r < 0)
1535 return bus_log_parse_error(r);
729e3769 1536
f459b602 1537 while ((r = sd_bus_message_read(reply, "(ss)", &path, &state)) > 0) {
729e3769 1538
f459b602
MAP
1539 if (!GREEDY_REALLOC(units, size, c + 1))
1540 return log_oom();
729e3769 1541
8d5ba5a9 1542 units[c] = (struct UnitFileList) {
f459b602
MAP
1543 path,
1544 unit_file_state_from_string(state)
1545 };
8d5ba5a9 1546
313fe66f 1547 if (output_show_unit_file(&units[c],
1548 fallback ? arg_states : NULL,
1549 fallback ? strv_skip(argv, 1) : NULL))
313cefa1 1550 c++;
8d5ba5a9 1551
729e3769 1552 }
f459b602
MAP
1553 if (r < 0)
1554 return bus_log_parse_error(r);
1555
1556 r = sd_bus_message_exit_container(reply);
1557 if (r < 0)
1558 return bus_log_parse_error(r);
729e3769
LP
1559 }
1560
ee5324aa 1561 (void) pager_open(arg_no_pager, false);
d2ad7e1b 1562
4fe1be9c
LP
1563 qsort_safe(units, c, sizeof(UnitFileList), compare_unit_file_list);
1564 output_unit_file_list(units, c);
729e3769 1565
0da999fa 1566 if (install_client_side())
8d5ba5a9
ZJS
1567 for (unit = units; unit < units + c; unit++)
1568 free(unit->path);
1569
f84190d8 1570 return 0;
729e3769
LP
1571}
1572
55c0b89c 1573static int list_dependencies_print(const char *name, int level, unsigned int branches, bool last) {
55c0b89c 1574 _cleanup_free_ char *n = NULL;
9607d947 1575 size_t max_len = MAX(columns(),20u);
cbc9fbd1
LP
1576 size_t len = 0;
1577 int i;
55c0b89c 1578
5d0c05e5 1579 if (!arg_plain) {
cbc9fbd1 1580
5d0c05e5
LN
1581 for (i = level - 1; i >= 0; i--) {
1582 len += 2;
f168c273 1583 if (len > max_len - 3 && !arg_full) {
5d0c05e5
LN
1584 printf("%s...\n",max_len % 2 ? "" : " ");
1585 return 0;
1586 }
323b7dc9 1587 printf("%s", special_glyph(branches & (1 << i) ? TREE_VERTICAL : TREE_SPACE));
5d0c05e5 1588 }
55c0b89c 1589 len += 2;
cbc9fbd1 1590
f168c273 1591 if (len > max_len - 3 && !arg_full) {
55c0b89c
LN
1592 printf("%s...\n",max_len % 2 ? "" : " ");
1593 return 0;
1594 }
cbc9fbd1 1595
323b7dc9 1596 printf("%s", special_glyph(last ? TREE_RIGHT : TREE_BRANCH));
55c0b89c 1597 }
55c0b89c 1598
9ed794a3 1599 if (arg_full) {
55c0b89c
LN
1600 printf("%s\n", name);
1601 return 0;
1602 }
1603
1604 n = ellipsize(name, max_len-len, 100);
f168c273 1605 if (!n)
55c0b89c
LN
1606 return log_oom();
1607
1608 printf("%s\n", n);
1609 return 0;
1610}
1611
f459b602 1612static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***deps) {
32b47279
YW
1613 struct DependencyStatusInfo {
1614 char **dep[5];
1615 } info = {};
1616
1617 static const struct bus_properties_map map[_DEPENDENCY_MAX][6] = {
1618 [DEPENDENCY_FORWARD] = {
1619 { "Requires", "as", NULL, offsetof(struct DependencyStatusInfo, dep[0]) },
1620 { "Requisite", "as", NULL, offsetof(struct DependencyStatusInfo, dep[1]) },
1621 { "Wants", "as", NULL, offsetof(struct DependencyStatusInfo, dep[2]) },
1622 { "ConsistsOf", "as", NULL, offsetof(struct DependencyStatusInfo, dep[3]) },
1623 { "BindsTo", "as", NULL, offsetof(struct DependencyStatusInfo, dep[4]) },
1624 {}
1625 },
1626 [DEPENDENCY_REVERSE] = {
1627 { "RequiredBy", "as", NULL, offsetof(struct DependencyStatusInfo, dep[0]) },
1628 { "RequisiteOf", "as", NULL, offsetof(struct DependencyStatusInfo, dep[1]) },
1629 { "WantedBy", "as", NULL, offsetof(struct DependencyStatusInfo, dep[2]) },
1630 { "PartOf", "as", NULL, offsetof(struct DependencyStatusInfo, dep[3]) },
1631 { "BoundBy", "as", NULL, offsetof(struct DependencyStatusInfo, dep[4]) },
1632 {}
1633 },
1634 [DEPENDENCY_AFTER] = {
1635 { "After", "as", NULL, offsetof(struct DependencyStatusInfo, dep[0]) },
1636 {}
1637 },
1638 [DEPENDENCY_BEFORE] = {
1639 { "Before", "as", NULL, offsetof(struct DependencyStatusInfo, dep[0]) },
1640 {}
1641 },
afba4199 1642 };
55c0b89c 1643
4afd3348 1644 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f459b602
MAP
1645 _cleanup_strv_free_ char **ret = NULL;
1646 _cleanup_free_ char *path = NULL;
32b47279 1647 int i, r;
55c0b89c
LN
1648
1649 assert(bus);
1650 assert(name);
1651 assert(deps);
1652
1653 path = unit_dbus_path_from_name(name);
f459b602
MAP
1654 if (!path)
1655 return log_oom();
55c0b89c 1656
32b47279
YW
1657 r = bus_map_all_properties(bus,
1658 "org.freedesktop.systemd1",
1659 path,
1660 map[arg_dependency],
f39cbb6e 1661 BUS_MAP_STRDUP,
32b47279 1662 &error,
f37f8a61 1663 NULL,
32b47279 1664 &info);
691395d8
LP
1665 if (r < 0)
1666 return log_error_errno(r, "Failed to get properties of %s: %s", name, bus_error_message(&error, r));
55c0b89c 1667
32b47279
YW
1668 if (IN_SET(arg_dependency, DEPENDENCY_AFTER, DEPENDENCY_BEFORE)) {
1669 *deps = info.dep[0];
1670 return 0;
1671 }
55c0b89c 1672
32b47279
YW
1673 for (i = 0; i < 5; i++) {
1674 r = strv_extend_strv(&ret, info.dep[i], true);
f459b602 1675 if (r < 0)
32b47279
YW
1676 return log_oom();
1677 info.dep[i] = strv_free(info.dep[i]);
f459b602 1678 }
540e7dbe 1679
1cc6c93a 1680 *deps = TAKE_PTR(ret);
540e7dbe 1681
f459b602 1682 return 0;
55c0b89c
LN
1683}
1684
1685static int list_dependencies_compare(const void *_a, const void *_b) {
1686 const char **a = (const char**) _a, **b = (const char**) _b;
cbc9fbd1 1687
55c0b89c
LN
1688 if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET)
1689 return 1;
1690 if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET)
1691 return -1;
cbc9fbd1 1692
55c0b89c
LN
1693 return strcasecmp(*a, *b);
1694}
1695
f459b602
MAP
1696static int list_dependencies_one(
1697 sd_bus *bus,
1698 const char *name,
1699 int level,
1700 char ***units,
1701 unsigned int branches) {
1702
e3e45d4f 1703 _cleanup_strv_free_ char **deps = NULL;
55c0b89c 1704 char **c;
55c0b89c
LN
1705 int r = 0;
1706
cbc9fbd1
LP
1707 assert(bus);
1708 assert(name);
1709 assert(units);
1710
e3e45d4f
SP
1711 r = strv_extend(units, name);
1712 if (r < 0)
55c0b89c
LN
1713 return log_oom();
1714
1715 r = list_dependencies_get_dependencies(bus, name, &deps);
1716 if (r < 0)
cec7eda5 1717 return r;
55c0b89c 1718
7ff7394d 1719 qsort_safe(deps, strv_length(deps), sizeof (char*), list_dependencies_compare);
55c0b89c
LN
1720
1721 STRV_FOREACH(c, deps) {
e3e45d4f 1722 if (strv_contains(*units, *c)) {
5d0c05e5 1723 if (!arg_plain) {
60705040 1724 printf(" ");
5d0c05e5
LN
1725 r = list_dependencies_print("...", level + 1, (branches << 1) | (c[1] == NULL ? 0 : 1), 1);
1726 if (r < 0)
1727 return r;
1728 }
55c0b89c
LN
1729 continue;
1730 }
1731
250ba664
ZJS
1732 if (arg_plain)
1733 printf(" ");
1734 else {
fa0d5878 1735 UnitActiveState active_state = _UNIT_ACTIVE_STATE_INVALID;
250ba664
ZJS
1736 const char *on;
1737
fa0d5878 1738 (void) get_state_one_unit(bus, *c, &active_state);
baa9ecc1 1739
fa0d5878 1740 switch (active_state) {
baa9ecc1
LP
1741 case UNIT_ACTIVE:
1742 case UNIT_RELOADING:
1743 case UNIT_ACTIVATING:
1744 on = ansi_highlight_green();
1745 break;
1746
1747 case UNIT_INACTIVE:
1748 case UNIT_DEACTIVATING:
1749 on = ansi_normal();
1750 break;
1751
1752 default:
1753 on = ansi_highlight_red();
1754 break;
fa0d5878
BR
1755 }
1756
323b7dc9 1757 printf("%s%s%s ", on, special_glyph(BLACK_CIRCLE), ansi_normal());
250ba664 1758 }
dbc2c080 1759
55c0b89c 1760 r = list_dependencies_print(*c, level, branches, c[1] == NULL);
cec7eda5
ZJS
1761 if (r < 0)
1762 return r;
55c0b89c
LN
1763
1764 if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) {
e3e45d4f 1765 r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (c[1] == NULL ? 0 : 1));
f168c273 1766 if (r < 0)
cec7eda5 1767 return r;
55c0b89c
LN
1768 }
1769 }
f459b602 1770
e3e45d4f
SP
1771 if (!arg_plain)
1772 strv_remove(*units, name);
f459b602 1773
cec7eda5 1774 return 0;
55c0b89c
LN
1775}
1776
e449de87 1777static int list_dependencies(int argc, char *argv[], void *userdata) {
5d0c05e5 1778 _cleanup_strv_free_ char **units = NULL;
f459b602 1779 _cleanup_free_ char *unit = NULL;
e31165b2 1780 const char *u;
4fbd7192 1781 sd_bus *bus;
7410616c 1782 int r;
55c0b89c 1783
e449de87 1784 if (argv[1]) {
37cbc1d5 1785 r = unit_name_mangle(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, &unit);
7410616c
LP
1786 if (r < 0)
1787 return log_error_errno(r, "Failed to mangle unit name: %m");
1788
e31165b2
LP
1789 u = unit;
1790 } else
1791 u = SPECIAL_DEFAULT_TARGET;
55c0b89c 1792
4fbd7192
LP
1793 r = acquire_bus(BUS_MANAGER, &bus);
1794 if (r < 0)
1795 return r;
1796
ee5324aa 1797 (void) pager_open(arg_no_pager, false);
d2ad7e1b 1798
e31165b2
LP
1799 puts(u);
1800
5d0c05e5 1801 return list_dependencies_one(bus, u, 0, &units, 0);
55c0b89c
LN
1802}
1803
0d292f5e
LP
1804struct machine_info {
1805 bool is_host;
1806 char *name;
0d292f5e 1807 char *state;
8fcf784d
LP
1808 char *control_group;
1809 uint32_t n_failed_units;
1810 uint32_t n_jobs;
1811 usec_t timestamp;
1812};
1813
1814static const struct bus_properties_map machine_info_property_map[] = {
1815 { "SystemState", "s", NULL, offsetof(struct machine_info, state) },
1816 { "NJobs", "u", NULL, offsetof(struct machine_info, n_jobs) },
1817 { "NFailedUnits", "u", NULL, offsetof(struct machine_info, n_failed_units) },
1818 { "ControlGroup", "s", NULL, offsetof(struct machine_info, control_group) },
1819 { "UserspaceTimestamp", "t", NULL, offsetof(struct machine_info, timestamp) },
1820 {}
0d292f5e
LP
1821};
1822
e7e55dbd 1823static void machine_info_clear(struct machine_info *info) {
f8654baa
ZJS
1824 assert(info);
1825
1826 free(info->name);
1827 free(info->state);
1828 free(info->control_group);
1829 zero(*info);
e7e55dbd
DH
1830}
1831
0d292f5e
LP
1832static void free_machines_list(struct machine_info *machine_infos, int n) {
1833 int i;
1834
1835 if (!machine_infos)
1836 return;
1837
e7e55dbd
DH
1838 for (i = 0; i < n; i++)
1839 machine_info_clear(&machine_infos[i]);
0d292f5e
LP
1840
1841 free(machine_infos);
1842}
1843
1844static int compare_machine_info(const void *a, const void *b) {
1845 const struct machine_info *u = a, *v = b;
1846
1847 if (u->is_host != v->is_host)
50933da0 1848 return u->is_host > v->is_host ? -1 : 1;
0d292f5e
LP
1849
1850 return strcasecmp(u->name, v->name);
1851}
1852
1853static int get_machine_properties(sd_bus *bus, struct machine_info *mi) {
4afd3348 1854 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *container = NULL;
0d292f5e
LP
1855 int r;
1856
1857 assert(mi);
1858
1859 if (!bus) {
de33fc62 1860 r = sd_bus_open_system_machine(&container, mi->name);
0d292f5e
LP
1861 if (r < 0)
1862 return r;
1863
1864 bus = container;
1865 }
1866
a7e4861c
YW
1867 r = bus_map_all_properties(
1868 bus,
1869 "org.freedesktop.systemd1",
1870 "/org/freedesktop/systemd1",
1871 machine_info_property_map,
1872 BUS_MAP_STRDUP,
1873 NULL,
1874 NULL,
1875 mi);
0d292f5e
LP
1876 if (r < 0)
1877 return r;
1878
1879 return 0;
1880}
1881
1882static bool output_show_machine(const char *name, char **patterns) {
2404701e 1883 return strv_fnmatch_or_empty(patterns, name, FNM_NOESCAPE);
0d292f5e
LP
1884}
1885
1886static int get_machine_list(
1887 sd_bus *bus,
1888 struct machine_info **_machine_infos,
1889 char **patterns) {
1890
1891 struct machine_info *machine_infos = NULL;
1892 _cleanup_strv_free_ char **m = NULL;
1893 _cleanup_free_ char *hn = NULL;
1894 size_t sz = 0;
1895 char **i;
4c3e8e39 1896 int c = 0, r;
0d292f5e
LP
1897
1898 hn = gethostname_malloc();
1899 if (!hn)
1900 return log_oom();
1901
1902 if (output_show_machine(hn, patterns)) {
1903 if (!GREEDY_REALLOC0(machine_infos, sz, c+1))
1904 return log_oom();
1905
1906 machine_infos[c].is_host = true;
ae2a15bc 1907 machine_infos[c].name = TAKE_PTR(hn);
0d292f5e 1908
f9e0eefc 1909 (void) get_machine_properties(bus, &machine_infos[c]);
0d292f5e
LP
1910 c++;
1911 }
1912
4c3e8e39
LP
1913 r = sd_get_machine_names(&m);
1914 if (r < 0)
1915 return log_error_errno(r, "Failed to get machine list: %m");
1916
0d292f5e
LP
1917 STRV_FOREACH(i, m) {
1918 _cleanup_free_ char *class = NULL;
1919
1920 if (!output_show_machine(*i, patterns))
1921 continue;
1922
1923 sd_machine_get_class(*i, &class);
1924 if (!streq_ptr(class, "container"))
1925 continue;
1926
1927 if (!GREEDY_REALLOC0(machine_infos, sz, c+1)) {
1928 free_machines_list(machine_infos, c);
1929 return log_oom();
1930 }
1931
1932 machine_infos[c].is_host = false;
1933 machine_infos[c].name = strdup(*i);
1934 if (!machine_infos[c].name) {
1935 free_machines_list(machine_infos, c);
1936 return log_oom();
1937 }
1938
f9e0eefc 1939 (void) get_machine_properties(NULL, &machine_infos[c]);
0d292f5e
LP
1940 c++;
1941 }
1942
1943 *_machine_infos = machine_infos;
1944 return c;
1945}
1946
1947static void output_machines_list(struct machine_info *machine_infos, unsigned n) {
1948 struct machine_info *m;
1949 unsigned
90c3f79d 1950 circle_len = 0,
fbd0b64f
LP
1951 namelen = STRLEN("NAME"),
1952 statelen = STRLEN("STATE"),
1953 failedlen = STRLEN("FAILED"),
1954 jobslen = STRLEN("JOBS");
0d292f5e
LP
1955
1956 assert(machine_infos || n == 0);
1957
1958 for (m = machine_infos; m < machine_infos + n; m++) {
fbd0b64f
LP
1959 namelen = MAX(namelen,
1960 strlen(m->name) + (m->is_host ? STRLEN(" (host)") : 0));
7bf7ce28 1961 statelen = MAX(statelen, strlen_ptr(m->state));
0d292f5e
LP
1962 failedlen = MAX(failedlen, DECIMAL_STR_WIDTH(m->n_failed_units));
1963 jobslen = MAX(jobslen, DECIMAL_STR_WIDTH(m->n_jobs));
90c3f79d 1964
250ba664 1965 if (!arg_plain && !streq_ptr(m->state, "running"))
90c3f79d 1966 circle_len = 2;
0d292f5e
LP
1967 }
1968
90c3f79d
LP
1969 if (!arg_no_legend) {
1970 if (circle_len > 0)
1971 fputs(" ", stdout);
1972
0d292f5e
LP
1973 printf("%-*s %-*s %-*s %-*s\n",
1974 namelen, "NAME",
1975 statelen, "STATE",
1976 failedlen, "FAILED",
1977 jobslen, "JOBS");
90c3f79d 1978 }
0d292f5e
LP
1979
1980 for (m = machine_infos; m < machine_infos + n; m++) {
90c3f79d
LP
1981 const char *on_state = "", *off_state = "";
1982 const char *on_failed = "", *off_failed = "";
1983 bool circle = false;
0d292f5e
LP
1984
1985 if (streq_ptr(m->state, "degraded")) {
1986 on_state = ansi_highlight_red();
1fc464f6 1987 off_state = ansi_normal();
90c3f79d 1988 circle = true;
0d292f5e
LP
1989 } else if (!streq_ptr(m->state, "running")) {
1990 on_state = ansi_highlight_yellow();
1fc464f6 1991 off_state = ansi_normal();
90c3f79d
LP
1992 circle = true;
1993 }
0d292f5e
LP
1994
1995 if (m->n_failed_units > 0) {
1996 on_failed = ansi_highlight_red();
1fc464f6 1997 off_failed = ansi_normal();
0d292f5e
LP
1998 } else
1999 on_failed = off_failed = "";
2000
90c3f79d 2001 if (circle_len > 0)
323b7dc9 2002 printf("%s%s%s ", on_state, circle ? special_glyph(BLACK_CIRCLE) : " ", off_state);
90c3f79d 2003
0d292f5e 2004 if (m->is_host)
c6ba5b80 2005 printf("%-*s (host) %s%-*s%s %s%*" PRIu32 "%s %*" PRIu32 "\n",
fbd0b64f
LP
2006 (int) (namelen - (STRLEN(" (host)"))),
2007 strna(m->name),
0d292f5e
LP
2008 on_state, statelen, strna(m->state), off_state,
2009 on_failed, failedlen, m->n_failed_units, off_failed,
2010 jobslen, m->n_jobs);
2011 else
c6ba5b80 2012 printf("%-*s %s%-*s%s %s%*" PRIu32 "%s %*" PRIu32 "\n",
0d292f5e
LP
2013 namelen, strna(m->name),
2014 on_state, statelen, strna(m->state), off_state,
2015 on_failed, failedlen, m->n_failed_units, off_failed,
2016 jobslen, m->n_jobs);
2017 }
2018
2019 if (!arg_no_legend)
2020 printf("\n%u machines listed.\n", n);
2021}
2022
e449de87 2023static int list_machines(int argc, char *argv[], void *userdata) {
0d292f5e 2024 struct machine_info *machine_infos = NULL;
4fbd7192 2025 sd_bus *bus;
0d292f5e
LP
2026 int r;
2027
4fbd7192
LP
2028 r = acquire_bus(BUS_MANAGER, &bus);
2029 if (r < 0)
2030 return r;
2031
e449de87 2032 r = get_machine_list(bus, &machine_infos, strv_skip(argv, 1));
0d292f5e
LP
2033 if (r < 0)
2034 return r;
2035
ee5324aa 2036 (void) pager_open(arg_no_pager, false);
d2ad7e1b 2037
0d292f5e
LP
2038 qsort_safe(machine_infos, r, sizeof(struct machine_info), compare_machine_info);
2039 output_machines_list(machine_infos, r);
2040 free_machines_list(machine_infos, r);
2041
2042 return 0;
2043}
2044
e449de87 2045static int get_default(int argc, char *argv[], void *userdata) {
4afd3348 2046 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602
MAP
2047 _cleanup_free_ char *_path = NULL;
2048 const char *path;
99504dd4 2049 int r;
99504dd4 2050
4fbd7192 2051 if (install_client_side()) {
f459b602 2052 r = unit_file_get_default(arg_scope, arg_root, &_path);
f647962d
MS
2053 if (r < 0)
2054 return log_error_errno(r, "Failed to get default target: %m");
f459b602 2055 path = _path;
99504dd4 2056
5f056378 2057 r = 0;
99504dd4 2058 } else {
4afd3348 2059 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192
LP
2060 sd_bus *bus;
2061
2062 r = acquire_bus(BUS_MANAGER, &bus);
2063 if (r < 0)
2064 return r;
6e646d22 2065
f459b602
MAP
2066 r = sd_bus_call_method(
2067 bus,
2068 "org.freedesktop.systemd1",
2069 "/org/freedesktop/systemd1",
2070 "org.freedesktop.systemd1.Manager",
2071 "GetDefaultTarget",
2072 &error,
2073 &reply,
2074 NULL);
691395d8
LP
2075 if (r < 0)
2076 return log_error_errno(r, "Failed to get default target: %s", bus_error_message(&error, r));
99504dd4 2077
f459b602
MAP
2078 r = sd_bus_message_read(reply, "s", &path);
2079 if (r < 0)
2080 return bus_log_parse_error(r);
99504dd4
VP
2081 }
2082
2083 if (path)
2084 printf("%s\n", path);
2085
f459b602 2086 return 0;
99504dd4
VP
2087}
2088
e449de87 2089static int set_default(int argc, char *argv[], void *userdata) {
718db961 2090 _cleanup_free_ char *unit = NULL;
acc0269c 2091 UnitFileChange *changes = NULL;
da6053d0 2092 size_t n_changes = 0;
718db961
LP
2093 int r;
2094
e449de87
LP
2095 assert(argc >= 2);
2096 assert(argv);
2097
37cbc1d5 2098 r = unit_name_mangle_with_suffix(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".target", &unit);
7410616c
LP
2099 if (r < 0)
2100 return log_error_errno(r, "Failed to mangle unit name: %m");
718db961 2101
4fbd7192 2102 if (install_client_side()) {
b3796dd8 2103 r = unit_file_set_default(arg_scope, UNIT_FILE_FORCE, arg_root, unit, &changes, &n_changes);
af3d8113 2104 unit_file_dump_changes(r, "set default", changes, n_changes, arg_quiet);
5f056378
CH
2105
2106 if (r > 0)
2107 r = 0;
718db961 2108 } else {
4afd3348
LP
2109 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2110 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4fbd7192 2111 sd_bus *bus;
718db961 2112
8a4b13c5 2113 polkit_agent_open_maybe();
6e646d22 2114
4fbd7192
LP
2115 r = acquire_bus(BUS_MANAGER, &bus);
2116 if (r < 0)
2117 return r;
2118
6e646d22 2119 r = sd_bus_call_method(
718db961
LP
2120 bus,
2121 "org.freedesktop.systemd1",
2122 "/org/freedesktop/systemd1",
2123 "org.freedesktop.systemd1.Manager",
6e646d22
LP
2124 "SetDefaultTarget",
2125 &error,
2126 &reply,
2127 "sb", unit, 1);
691395d8
LP
2128 if (r < 0)
2129 return log_error_errno(r, "Failed to set default target: %s", bus_error_message(&error, r));
718db961 2130
acc0269c 2131 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
718db961 2132 if (r < 0)
acc0269c 2133 goto finish;
718db961 2134
93c941e3 2135 /* Try to reload if enabled */
718db961 2136 if (!arg_no_reload)
e449de87 2137 r = daemon_reload(argc, argv, userdata);
718db961
LP
2138 else
2139 r = 0;
2140 }
2141
acc0269c
CH
2142finish:
2143 unit_file_changes_free(changes, n_changes);
2144
718db961
LP
2145 return r;
2146}
2147
76d8ca22 2148static int output_waiting_jobs(sd_bus *bus, uint32_t id, const char *method, const char *prefix) {
82948f6c
LP
2149 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2150 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2151 const char *name, *type, *state, *job_path, *unit_path;
2152 uint32_t other_id;
2153 int r;
2154
2155 assert(bus);
2156
2157 r = sd_bus_call_method(
2158 bus,
2159 "org.freedesktop.systemd1",
2160 "/org/freedesktop/systemd1",
2161 "org.freedesktop.systemd1.Manager",
2162 method,
2163 &error,
2164 &reply,
2165 "u", id);
76d8ca22
ZJS
2166 if (r < 0)
2167 return log_debug_errno(r, "Failed to get waiting jobs for job %" PRIu32, id);
82948f6c
LP
2168
2169 r = sd_bus_message_enter_container(reply, 'a', "(usssoo)");
76d8ca22
ZJS
2170 if (r < 0)
2171 return bus_log_parse_error(r);
82948f6c
LP
2172
2173 while ((r = sd_bus_message_read(reply, "(usssoo)", &other_id, &name, &type, &state, &job_path, &unit_path)) > 0)
bc357ce5 2174 printf("%s %u (%s/%s)\n", prefix, other_id, name, type);
76d8ca22
ZJS
2175 if (r < 0)
2176 return bus_log_parse_error(r);
82948f6c
LP
2177
2178 r = sd_bus_message_exit_container(reply);
76d8ca22
ZJS
2179 if (r < 0)
2180 return bus_log_parse_error(r);
2181
2182 return 0;
82948f6c
LP
2183}
2184
75add28a
ZJS
2185struct job_info {
2186 uint32_t id;
f459b602 2187 const char *name, *type, *state;
75add28a
ZJS
2188};
2189
82948f6c 2190static void output_jobs_list(sd_bus *bus, const struct job_info* jobs, unsigned n, bool skipped) {
f459b602
MAP
2191 unsigned id_len, unit_len, type_len, state_len;
2192 const struct job_info *j;
75add28a
ZJS
2193 const char *on, *off;
2194 bool shorten = false;
2195
2196 assert(n == 0 || jobs);
2197
2198 if (n == 0) {
250ba664
ZJS
2199 if (!arg_no_legend) {
2200 on = ansi_highlight_green();
1fc464f6 2201 off = ansi_normal();
75add28a 2202
250ba664
ZJS
2203 printf("%sNo jobs %s.%s\n", on, skipped ? "listed" : "running", off);
2204 }
75add28a
ZJS
2205 return;
2206 }
2207
ee5324aa 2208 (void) pager_open(arg_no_pager, false);
75add28a 2209
fbd0b64f
LP
2210 id_len = STRLEN("JOB");
2211 unit_len = STRLEN("UNIT");
2212 type_len = STRLEN("TYPE");
2213 state_len = STRLEN("STATE");
6d6d40c9 2214
f459b602
MAP
2215 for (j = jobs; j < jobs + n; j++) {
2216 uint32_t id = j->id;
2217 assert(j->name && j->type && j->state);
75add28a 2218
f459b602
MAP
2219 id_len = MAX(id_len, DECIMAL_STR_WIDTH(id));
2220 unit_len = MAX(unit_len, strlen(j->name));
2221 type_len = MAX(type_len, strlen(j->type));
2222 state_len = MAX(state_len, strlen(j->state));
2223 }
75add28a 2224
f459b602
MAP
2225 if (!arg_full && id_len + 1 + unit_len + type_len + 1 + state_len > columns()) {
2226 unit_len = MAX(33u, columns() - id_len - type_len - state_len - 3);
2227 shorten = true;
2228 }
75add28a 2229
6ce774fd
MM
2230 if (!arg_no_legend)
2231 printf("%*s %-*s %-*s %-*s\n",
2232 id_len, "JOB",
2233 unit_len, "UNIT",
2234 type_len, "TYPE",
2235 state_len, "STATE");
75add28a 2236
f459b602
MAP
2237 for (j = jobs; j < jobs + n; j++) {
2238 _cleanup_free_ char *e = NULL;
75add28a 2239
f459b602
MAP
2240 if (streq(j->state, "running")) {
2241 on = ansi_highlight();
1fc464f6 2242 off = ansi_normal();
f459b602
MAP
2243 } else
2244 on = off = "";
2245
2246 e = shorten ? ellipsize(j->name, unit_len, 33) : NULL;
2247 printf("%*u %s%-*s%s %-*s %s%-*s%s\n",
2248 id_len, j->id,
2249 on, unit_len, e ? e : j->name, off,
2250 type_len, j->type,
2251 on, state_len, j->state, off);
82948f6c
LP
2252
2253 if (arg_jobs_after)
bc357ce5 2254 output_waiting_jobs(bus, j->id, "GetJobAfter", "\twaiting for job");
82948f6c 2255 if (arg_jobs_before)
bc357ce5 2256 output_waiting_jobs(bus, j->id, "GetJobBefore", "\tblocking job");
75add28a
ZJS
2257 }
2258
6ce774fd
MM
2259 if (!arg_no_legend) {
2260 on = ansi_highlight();
1fc464f6 2261 off = ansi_normal();
75add28a 2262
6ce774fd
MM
2263 printf("\n%s%u jobs listed%s.\n", on, n, off);
2264 }
75add28a
ZJS
2265}
2266
d8fba7c6 2267static bool output_show_job(struct job_info *job, char **patterns) {
2404701e 2268 return strv_fnmatch_or_empty(patterns, job->name, FNM_NOESCAPE);
d8fba7c6
ZJS
2269}
2270
e449de87 2271static int list_jobs(int argc, char *argv[], void *userdata) {
4afd3348
LP
2272 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2273 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602
MAP
2274 const char *name, *type, *state, *job_path, *unit_path;
2275 _cleanup_free_ struct job_info *jobs = NULL;
2276 size_t size = 0;
2277 unsigned c = 0;
4fbd7192 2278 sd_bus *bus;
f459b602 2279 uint32_t id;
f84190d8 2280 int r;
d8fba7c6 2281 bool skipped = false;
ec14911e 2282
4fbd7192
LP
2283 r = acquire_bus(BUS_MANAGER, &bus);
2284 if (r < 0)
2285 return r;
2286
f459b602 2287 r = sd_bus_call_method(
f22f08cd
SP
2288 bus,
2289 "org.freedesktop.systemd1",
2290 "/org/freedesktop/systemd1",
2291 "org.freedesktop.systemd1.Manager",
2292 "ListJobs",
f459b602 2293 &error,
f22f08cd 2294 &reply,
f459b602 2295 NULL);
691395d8
LP
2296 if (r < 0)
2297 return log_error_errno(r, "Failed to list jobs: %s", bus_error_message(&error, r));
7e4249b9 2298
f459b602
MAP
2299 r = sd_bus_message_enter_container(reply, 'a', "(usssoo)");
2300 if (r < 0)
2301 return bus_log_parse_error(r);
7e4249b9 2302
f459b602 2303 while ((r = sd_bus_message_read(reply, "(usssoo)", &id, &name, &type, &state, &job_path, &unit_path)) > 0) {
d8fba7c6
ZJS
2304 struct job_info job = { id, name, type, state };
2305
e449de87 2306 if (!output_show_job(&job, strv_skip(argv, 1))) {
d8fba7c6
ZJS
2307 skipped = true;
2308 continue;
2309 }
8fe914ec 2310
f459b602
MAP
2311 if (!GREEDY_REALLOC(jobs, size, c + 1))
2312 return log_oom();
7e4249b9 2313
d8fba7c6 2314 jobs[c++] = job;
7e4249b9 2315 }
f459b602
MAP
2316 if (r < 0)
2317 return bus_log_parse_error(r);
7e4249b9 2318
f459b602
MAP
2319 r = sd_bus_message_exit_container(reply);
2320 if (r < 0)
2321 return bus_log_parse_error(r);
f73e33d9 2322
ee5324aa 2323 (void) pager_open(arg_no_pager, false);
d2ad7e1b 2324
82948f6c 2325 output_jobs_list(bus, jobs, c, skipped);
91d0f17e 2326 return 0;
7e4249b9
LP
2327}
2328
e449de87 2329static int cancel_job(int argc, char *argv[], void *userdata) {
4fbd7192 2330 sd_bus *bus;
729e3769 2331 char **name;
342641fb 2332 int r = 0;
7e4249b9 2333
e449de87 2334 if (argc <= 1)
2853b60a 2335 return trivial_method(argc, argv, userdata);
ee5762e3 2336
4fbd7192
LP
2337 r = acquire_bus(BUS_MANAGER, &bus);
2338 if (r < 0)
2339 return r;
2340
8a4b13c5 2341 polkit_agent_open_maybe();
d2ad7e1b 2342
e449de87 2343 STRV_FOREACH(name, strv_skip(argv, 1)) {
4afd3348 2344 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5dd9014f 2345 uint32_t id;
342641fb 2346 int q;
7e4249b9 2347
342641fb 2348 q = safe_atou32(*name, &id);
f647962d
MS
2349 if (q < 0)
2350 return log_error_errno(q, "Failed to parse job id \"%s\": %m", *name);
7e4249b9 2351
6e646d22 2352 q = sd_bus_call_method(
f22f08cd
SP
2353 bus,
2354 "org.freedesktop.systemd1",
2355 "/org/freedesktop/systemd1",
2356 "org.freedesktop.systemd1.Manager",
6e646d22
LP
2357 "CancelJob",
2358 &error,
2359 NULL,
2360 "u", id);
342641fb 2361 if (q < 0) {
691395d8 2362 log_error_errno(q, "Failed to cancel job %"PRIu32": %s", id, bus_error_message(&error, q));
342641fb
LP
2363 if (r == 0)
2364 r = q;
f459b602 2365 }
7e4249b9
LP
2366 }
2367
342641fb 2368 return r;
7e4249b9
LP
2369}
2370
f459b602 2371static int need_daemon_reload(sd_bus *bus, const char *unit) {
4afd3348 2372 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602
MAP
2373 const char *path;
2374 int b, r;
94c01aeb 2375
f459b602
MAP
2376 /* We ignore all errors here, since this is used to show a
2377 * warning only */
45fb0699 2378
f459b602
MAP
2379 /* We don't use unit_dbus_path_from_name() directly since we
2380 * don't want to load the unit if it isn't loaded. */
f84190d8 2381
f459b602 2382 r = sd_bus_call_method(
f22f08cd
SP
2383 bus,
2384 "org.freedesktop.systemd1",
2385 "/org/freedesktop/systemd1",
2386 "org.freedesktop.systemd1.Manager",
2387 "GetUnit",
f459b602 2388 NULL,
f22f08cd 2389 &reply,
e3e0314b 2390 "s", unit);
f84190d8
LP
2391 if (r < 0)
2392 return r;
45fb0699 2393
f459b602
MAP
2394 r = sd_bus_message_read(reply, "o", &path);
2395 if (r < 0)
2396 return r;
f84190d8 2397
f459b602 2398 r = sd_bus_get_property_trivial(
f22f08cd 2399 bus,
b0193f1c
LP
2400 "org.freedesktop.systemd1",
2401 path,
f459b602
MAP
2402 "org.freedesktop.systemd1.Unit",
2403 "NeedDaemonReload",
2404 NULL,
2405 'b', &b);
f84190d8
LP
2406 if (r < 0)
2407 return r;
45fb0699 2408
45fb0699
LP
2409 return b;
2410}
2411
3f36991e 2412static void warn_unit_file_changed(const char *name) {
87ec20ef
LP
2413 assert(name);
2414
e9f4aabd 2415 log_warning("%sWarning:%s The unit file, source configuration file or drop-ins of %s changed on disk. Run 'systemctl%s daemon-reload' to reload units.",
3f36991e 2416 ansi_highlight_red(),
1fc464f6 2417 ansi_normal(),
3f36991e
ZJS
2418 name,
2419 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user");
2420}
2421
33f6c497
ZJS
2422static int unit_file_find_path(LookupPaths *lp, const char *unit_name, char **unit_path) {
2423 char **p;
2424
2425 assert(lp);
2426 assert(unit_name);
33f6c497 2427
a3c4eb07 2428 STRV_FOREACH(p, lp->search_path) {
c6dd36b6
FS
2429 _cleanup_free_ char *path = NULL, *lpath = NULL;
2430 int r;
33f6c497 2431
3ef21542 2432 path = path_join(NULL, *p, unit_name);
33f6c497
ZJS
2433 if (!path)
2434 return log_oom();
2435
c4f4fce7 2436 r = chase_symlinks(path, arg_root, 0, &lpath);
c6dd36b6
FS
2437 if (r == -ENOENT)
2438 continue;
2439 if (r == -ENOMEM)
2440 return log_oom();
2441 if (r < 0)
2442 return log_error_errno(r, "Failed to access path '%s': %m", path);
2443
ae2a15bc
LP
2444 if (unit_path)
2445 *unit_path = TAKE_PTR(lpath);
2446
c6dd36b6 2447 return 1;
33f6c497
ZJS
2448 }
2449
2450 return 0;
2451}
2452
173471b7
ZJS
2453static int unit_find_template_path(
2454 const char *unit_name,
2455 LookupPaths *lp,
2456 char **fragment_path,
2457 char **template) {
2458
2459 _cleanup_free_ char *_template = NULL;
2460 int r;
2461
2462 /* Returns 1 if a fragment was found, 0 if not found, negative on error. */
2463
2464 r = unit_file_find_path(lp, unit_name, fragment_path);
2465 if (r != 0)
2466 return r; /* error or found a real unit */
2467
2468 r = unit_name_template(unit_name, &_template);
2469 if (r == -EINVAL)
2470 return 0; /* not a template, does not exist */
2471 if (r < 0)
2472 return log_error_errno(r, "Failed to determine template name: %m");
2473
2474 r = unit_file_find_path(lp, _template, fragment_path);
2475 if (r < 0)
2476 return r;
2477
ae2a15bc
LP
2478 if (template)
2479 *template = TAKE_PTR(_template);
2480
173471b7
ZJS
2481 return r;
2482}
2483
6e646d22
LP
2484static int unit_find_paths(
2485 sd_bus *bus,
2486 const char *unit_name,
6e646d22
LP
2487 LookupPaths *lp,
2488 char **fragment_path,
2489 char ***dropin_paths) {
dab2bce8
IS
2490
2491 _cleanup_free_ char *path = NULL;
2492 _cleanup_strv_free_ char **dropins = NULL;
33f6c497
ZJS
2493 int r;
2494
ad2a0358
ZJS
2495 /**
2496 * Finds where the unit is defined on disk. Returns 0 if the unit
2497 * is not found. Returns 1 if it is found, and sets
2498 * - the path to the unit in *path, if it exists on disk,
2499 * - and a strv of existing drop-ins in *dropins,
2500 * if the arg is not NULL and any dropins were found.
2501 */
2502
33f6c497 2503 assert(unit_name);
ad2a0358 2504 assert(fragment_path);
33f6c497
ZJS
2505 assert(lp);
2506
4fbd7192 2507 if (!install_client_side() && !unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
4afd3348 2508 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
33f6c497 2509 _cleanup_free_ char *unit = NULL;
33f6c497
ZJS
2510
2511 unit = unit_dbus_path_from_name(unit_name);
2512 if (!unit)
2513 return log_oom();
2514
33f6c497
ZJS
2515 r = sd_bus_get_property_string(
2516 bus,
2517 "org.freedesktop.systemd1",
2518 unit,
2519 "org.freedesktop.systemd1.Unit",
2520 "FragmentPath",
2521 &error,
ad2a0358
ZJS
2522 &path);
2523 if (r < 0)
2524 return log_error_errno(r, "Failed to get FragmentPath: %s", bus_error_message(&error, r));
2525
dab2bce8
IS
2526 if (dropin_paths) {
2527 r = sd_bus_get_property_strv(
2528 bus,
2529 "org.freedesktop.systemd1",
2530 unit,
2531 "org.freedesktop.systemd1.Unit",
2532 "DropInPaths",
2533 &error,
2534 &dropins);
2535 if (r < 0)
2536 return log_error_errno(r, "Failed to get DropInPaths: %s", bus_error_message(&error, r));
33f6c497 2537 }
ad2a0358 2538 } else {
173471b7 2539 _cleanup_set_free_ Set *names = NULL;
6483ad89 2540 _cleanup_free_ char *template = NULL;
33f6c497 2541
ad2a0358
ZJS
2542 names = set_new(NULL);
2543 if (!names)
7410616c 2544 return log_oom();
33f6c497 2545
173471b7 2546 r = unit_find_template_path(unit_name, lp, &path, &template);
ad2a0358
ZJS
2547 if (r < 0)
2548 return r;
2549
173471b7 2550 if (r > 0)
6483ad89
ZJS
2551 /* We found the unit file. If we followed symlinks, this name might be
2552 * different then the unit_name with started with. Look for dropins matching
2553 * that "final" name. */
2554 r = set_put(names, basename(path));
2555 else if (!template)
2556 /* No unit file, let's look for dropins matching the original name.
2557 * systemd has fairly complicated rules (based on unit type and provenience),
2558 * which units are allowed not to have the main unit file. We err on the
2559 * side of including too many files, and always try to load dropins. */
2560 r = set_put(names, unit_name);
2561 else
2562 /* The cases where we allow a unit to exist without the main file are
2563 * never valid for templates. Don't try to load dropins in this case. */
2564 goto not_found;
2565
c6dd36b6
FS
2566 if (r < 0)
2567 return log_error_errno(r, "Failed to add unit name: %m");
2568
dab2bce8 2569 if (dropin_paths) {
95778782
ZJS
2570 r = unit_file_find_dropin_conf_paths(arg_root, lp->search_path,
2571 NULL, names, &dropins);
dab2bce8
IS
2572 if (r < 0)
2573 return r;
2574 }
2575 }
2576
2577 r = 0;
2578
2579 if (!isempty(path)) {
1cc6c93a 2580 *fragment_path = TAKE_PTR(path);
dab2bce8
IS
2581 r = 1;
2582 }
2583
2584 if (dropin_paths && !strv_isempty(dropins)) {
1cc6c93a 2585 *dropin_paths = TAKE_PTR(dropins);
dab2bce8 2586 r = 1;
33f6c497 2587 }
6483ad89 2588 not_found:
39c38ce1 2589 if (r == 0 && !arg_force)
b5e6a600
IS
2590 log_error("No files found for %s.", unit_name);
2591
ad2a0358 2592 return r;
33f6c497
ZJS
2593}
2594
fa0d5878 2595static int get_state_one_unit(sd_bus *bus, const char *name, UnitActiveState *active_state) {
b430f85f 2596 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3d083b22 2597 _cleanup_free_ char *buf = NULL, *path = NULL;
fa0d5878 2598 UnitActiveState state;
f22f08cd 2599 int r;
701cdcb9 2600
31be1221 2601 assert(name);
fa0d5878 2602 assert(active_state);
701cdcb9 2603
3d083b22
LP
2604 path = unit_dbus_path_from_name(name);
2605 if (!path)
2606 return log_oom();
2607
2608 r = sd_bus_get_property_string(
f22f08cd
SP
2609 bus,
2610 "org.freedesktop.systemd1",
3d083b22
LP
2611 path,
2612 "org.freedesktop.systemd1.Unit",
2613 "ActiveState",
b430f85f 2614 &error,
3d083b22
LP
2615 &buf);
2616 if (r < 0)
2617 return log_error_errno(r, "Failed to retrieve unit state: %s", bus_error_message(&error, r));
b430f85f 2618
3d083b22
LP
2619 state = unit_active_state_from_string(buf);
2620 if (state == _UNIT_ACTIVE_STATE_INVALID) {
2621 log_error("Invalid unit state '%s' for: %s", buf, name);
2622 return -EINVAL;
60f9ba0b 2623 }
701cdcb9 2624
fa0d5878
BR
2625 *active_state = state;
2626 return 0;
701cdcb9
MS
2627}
2628
9d9dd746 2629static int unit_is_masked(sd_bus *bus, const char *name) {
bd062910 2630 _cleanup_free_ char *load_state = NULL;
f22f08cd 2631 int r;
701cdcb9 2632
bd062910 2633 r = unit_load_state(bus, name, &load_state);
691395d8 2634 if (r < 0)
bd062910 2635 return r;
d0a5cdb2 2636
9d9dd746
ZJS
2637 return streq(load_state, "masked");
2638}
2639
2640static int check_triggering_units(sd_bus *bus, const char *name) {
2641 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2642 _cleanup_free_ char *n = NULL, *path = NULL;
2643 _cleanup_strv_free_ char **triggered_by = NULL;
2644 bool print_warning_label = true;
2645 UnitActiveState active_state;
2646 char **i;
2647 int r;
2648
2649 r = unit_name_mangle(name, 0, &n);
2650 if (r < 0)
2651 return log_error_errno(r, "Failed to mangle unit name: %m");
2652
2653 r = unit_is_masked(bus, n);
2654 if (r != 0)
2655 return r < 0 ? r : 0;
2656
2657 path = unit_dbus_path_from_name(n);
2658 if (!path)
2659 return log_oom();
701cdcb9 2660
f459b602
MAP
2661 r = sd_bus_get_property_strv(
2662 bus,
2663 "org.freedesktop.systemd1",
2664 path,
2665 "org.freedesktop.systemd1.Unit",
2666 "TriggeredBy",
2667 &error,
2668 &triggered_by);
691395d8
LP
2669 if (r < 0)
2670 return log_error_errno(r, "Failed to get triggered by array of %s: %s", n, bus_error_message(&error, r));
701cdcb9 2671
f459b602 2672 STRV_FOREACH(i, triggered_by) {
fa0d5878 2673 r = get_state_one_unit(bus, *i, &active_state);
f647962d 2674 if (r < 0)
fa0d5878 2675 return r;
701cdcb9 2676
fa0d5878 2677 if (!IN_SET(active_state, UNIT_ACTIVE, UNIT_RELOADING))
f459b602 2678 continue;
60f9ba0b 2679
f459b602
MAP
2680 if (print_warning_label) {
2681 log_warning("Warning: Stopping %s, but it can still be activated by:", n);
2682 print_warning_label = false;
701cdcb9 2683 }
1c291cf3 2684
f459b602 2685 log_warning(" %s", *i);
701cdcb9 2686 }
f459b602
MAP
2687
2688 return 0;
701cdcb9
MS
2689}
2690
2fc9a280
LP
2691static const struct {
2692 const char *verb;
2693 const char *method;
2694} unit_actions[] = {
2695 { "start", "StartUnit" },
2696 { "stop", "StopUnit" },
2697 { "condstop", "StopUnit" },
2698 { "reload", "ReloadUnit" },
2699 { "restart", "RestartUnit" },
2700 { "try-restart", "TryRestartUnit" },
2701 { "condrestart", "TryRestartUnit" },
2702 { "reload-or-restart", "ReloadOrRestartUnit" },
aabf5d42 2703 { "try-reload-or-restart", "ReloadOrTryRestartUnit" },
2fc9a280
LP
2704 { "reload-or-try-restart", "ReloadOrTryRestartUnit" },
2705 { "condreload", "ReloadOrTryRestartUnit" },
2706 { "force-reload", "ReloadOrTryRestartUnit" }
2707};
2708
39602c39
TA
2709static const char *verb_to_method(const char *verb) {
2710 uint i;
2711
2712 for (i = 0; i < ELEMENTSOF(unit_actions); i++)
2713 if (streq_ptr(unit_actions[i].verb, verb))
2714 return unit_actions[i].method;
2715
2716 return "StartUnit";
2717}
2718
2719static const char *method_to_verb(const char *method) {
2720 uint i;
2721
2722 for (i = 0; i < ELEMENTSOF(unit_actions); i++)
2723 if (streq_ptr(unit_actions[i].method, method))
2724 return unit_actions[i].verb;
2725
2726 return "n/a";
2727}
2728
93a08841
MP
2729typedef struct {
2730 sd_bus_slot *match;
2731 sd_event *event;
2732 Set *unit_paths;
2733 bool any_failed;
2734} WaitContext;
2735
2736static void wait_context_free(WaitContext *c) {
2737 c->match = sd_bus_slot_unref(c->match);
2738 c->event = sd_event_unref(c->event);
6fa4160d 2739 c->unit_paths = set_free_free(c->unit_paths);
93a08841
MP
2740}
2741
2742static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
2743 WaitContext *c = userdata;
2744 const char *path;
2745 int r;
2746
2747 path = sd_bus_message_get_path(m);
2748 if (!set_contains(c->unit_paths, path))
2749 return 0;
2750
2751 /* Check if ActiveState changed to inactive/failed */
2752 /* (s interface, a{sv} changed_properties, as invalidated_properties) */
2753 r = sd_bus_message_skip(m, "s");
2754 if (r < 0)
2755 return bus_log_parse_error(r);
6fa4160d 2756
93a08841
MP
2757 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
2758 if (r < 0)
2759 return bus_log_parse_error(r);
2760
2761 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
2762 const char *s;
93a08841
MP
2763
2764 r = sd_bus_message_read(m, "s", &s);
2765 if (r < 0)
2766 return bus_log_parse_error(r);
6fa4160d 2767
93a08841 2768 if (streq(s, "ActiveState")) {
6fa4160d
LP
2769 bool is_failed;
2770
93a08841
MP
2771 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, "s");
2772 if (r < 0)
2773 return bus_log_parse_error(r);
6fa4160d 2774
93a08841
MP
2775 r = sd_bus_message_read(m, "s", &s);
2776 if (r < 0)
2777 return bus_log_parse_error(r);
6fa4160d 2778
93a08841
MP
2779 is_failed = streq(s, "failed");
2780 if (streq(s, "inactive") || is_failed) {
2781 log_debug("%s became %s, dropping from --wait tracking", path, s);
6fa4160d
LP
2782 free(set_remove(c->unit_paths, path));
2783 c->any_failed = c->any_failed || is_failed;
93a08841
MP
2784 } else
2785 log_debug("ActiveState on %s changed to %s", path, s);
6fa4160d 2786
93a08841
MP
2787 break; /* no need to dissect the rest of the message */
2788 } else {
2789 /* other property */
2790 r = sd_bus_message_skip(m, "v");
2791 if (r < 0)
2792 return bus_log_parse_error(r);
2793 }
2794 r = sd_bus_message_exit_container(m);
2795 if (r < 0)
2796 return bus_log_parse_error(r);
2797 }
2798 if (r < 0)
2799 return bus_log_parse_error(r);
2800
2801 if (set_isempty(c->unit_paths))
2802 sd_event_exit(c->event, EXIT_SUCCESS);
2803
2804 return 0;
2805}
2806
e4b61340 2807static int start_unit_one(
f459b602 2808 sd_bus *bus,
e4b61340
LP
2809 const char *method,
2810 const char *name,
2811 const char *mode,
f459b602 2812 sd_bus_error *error,
93a08841
MP
2813 BusWaitForJobs *w,
2814 WaitContext *wait_context) {
7e4249b9 2815
4afd3348 2816 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
45fb0699 2817 const char *path;
7e4249b9 2818 int r;
7e4249b9 2819
e4b61340
LP
2820 assert(method);
2821 assert(name);
2822 assert(mode);
22f4096c 2823 assert(error);
7e4249b9 2824
93a08841
MP
2825 if (wait_context) {
2826 _cleanup_free_ char *unit_path = NULL;
93a08841
MP
2827
2828 log_debug("Watching for property changes of %s", name);
2829 r = sd_bus_call_method(
2830 bus,
2831 "org.freedesktop.systemd1",
2832 "/org/freedesktop/systemd1",
2833 "org.freedesktop.systemd1.Manager",
2834 "RefUnit",
2835 error,
2836 NULL,
2837 "s", name);
2838 if (r < 0)
2839 return log_error_errno(r, "Failed to RefUnit %s: %s", name, bus_error_message(error, r));
2840
2841 unit_path = unit_dbus_path_from_name(name);
2842 if (!unit_path)
2843 return log_oom();
2844
2845 r = set_put_strdup(wait_context->unit_paths, unit_path);
2846 if (r < 0)
2847 return log_error_errno(r, "Failed to add unit path %s to set: %m", unit_path);
2848
75152a4d
LP
2849 r = sd_bus_match_signal_async(bus,
2850 &wait_context->match,
2851 NULL,
2852 unit_path,
2853 "org.freedesktop.DBus.Properties",
2854 "PropertiesChanged",
2855 on_properties_changed, NULL, wait_context);
93a08841 2856 if (r < 0)
75152a4d 2857 return log_error_errno(r, "Failed to request match for PropertiesChanged signal: %m");
93a08841
MP
2858 }
2859
dbc9830c
ZJS
2860 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
2861 arg_dry_run ? "Would execute" : "Executing",
1ae17672
ZJS
2862 method, name, mode);
2863 if (arg_dry_run)
2864 return 0;
342641fb 2865
6e646d22 2866 r = sd_bus_call_method(
f22f08cd 2867 bus,
b0193f1c
LP
2868 "org.freedesktop.systemd1",
2869 "/org/freedesktop/systemd1",
2870 "org.freedesktop.systemd1.Manager",
6e646d22
LP
2871 method,
2872 error,
2873 &reply,
2874 "ss", name, mode);
f459b602 2875 if (r < 0) {
39602c39
TA
2876 const char *verb;
2877
033f0ab8
LP
2878 /* There's always a fallback possible for legacy actions. */
2879 if (arg_action != ACTION_SYSTEMCTL)
2880 return r;
67f3c402 2881
39602c39
TA
2882 verb = method_to_verb(method);
2883
ee87525c
FB
2884 log_error("Failed to %s %s: %s", verb, name, bus_error_message(error, r));
2885
2886 if (!sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT) &&
5b464a18
ZJS
2887 !sd_bus_error_has_name(error, BUS_ERROR_UNIT_MASKED) &&
2888 !sd_bus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE))
a6405ca2 2889 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
0b8505b7
RC
2890 arg_scope == UNIT_FILE_SYSTEM ? "system" : "user",
2891 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
a6405ca2 2892 name[0] == '-' ? " --" : "",
0b8505b7 2893 name);
ee87525c
FB
2894
2895 return r;
7e4249b9
LP
2896 }
2897
f459b602
MAP
2898 r = sd_bus_message_read(reply, "o", &path);
2899 if (r < 0)
2900 return bus_log_parse_error(r);
45fb0699 2901
e3e0314b 2902 if (need_daemon_reload(bus, name) > 0)
3f36991e 2903 warn_unit_file_changed(name);
45fb0699 2904
ebd011d9
LP
2905 if (w) {
2906 log_debug("Adding %s to the set", path);
2907 r = bus_wait_for_jobs_add(w, path);
cbc9fbd1
LP
2908 if (r < 0)
2909 return log_oom();
e4b61340 2910 }
7e4249b9 2911
46eddbb5 2912 return 0;
7e4249b9
LP
2913}
2914
e3e0314b 2915static int expand_names(sd_bus *bus, char **names, const char* suffix, char ***ret) {
e3e0314b
ZJS
2916 _cleanup_strv_free_ char **mangled = NULL, **globs = NULL;
2917 char **name;
7410616c 2918 int r, i;
e3e0314b 2919
4fbd7192
LP
2920 assert(bus);
2921 assert(ret);
2922
e3e0314b
ZJS
2923 STRV_FOREACH(name, names) {
2924 char *t;
37cbc1d5 2925 UnitNameMangle options = UNIT_NAME_MANGLE_GLOB | (arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN);
e3e0314b 2926
e80733be 2927 if (suffix)
37cbc1d5 2928 r = unit_name_mangle_with_suffix(*name, options, suffix, &t);
e80733be 2929 else
37cbc1d5 2930 r = unit_name_mangle(*name, options, &t);
7410616c
LP
2931 if (r < 0)
2932 return log_error_errno(r, "Failed to mangle name: %m");
e3e0314b
ZJS
2933
2934 if (string_is_glob(t))
6e18964d 2935 r = strv_consume(&globs, t);
e3e0314b 2936 else
6e18964d
ZJS
2937 r = strv_consume(&mangled, t);
2938 if (r < 0)
e3e0314b 2939 return log_oom();
e3e0314b
ZJS
2940 }
2941
2942 /* Query the manager only if any of the names are a glob, since
2943 * this is fairly expensive */
2944 if (!strv_isempty(globs)) {
4afd3348 2945 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
e3e0314b 2946 _cleanup_free_ UnitInfo *unit_infos = NULL;
1b53f64b 2947 size_t allocated, n;
e3e0314b 2948
1238ee09 2949 r = get_unit_list(bus, NULL, globs, &unit_infos, 0, &reply);
e3e0314b
ZJS
2950 if (r < 0)
2951 return r;
2952
1b53f64b
LP
2953 n = strv_length(mangled);
2954 allocated = n + 1;
2955
2956 for (i = 0; i < r; i++) {
2957 if (!GREEDY_REALLOC(mangled, allocated, n+2))
2958 return log_oom();
2959
2960 mangled[n] = strdup(unit_infos[i].id);
2961 if (!mangled[n])
e3e0314b 2962 return log_oom();
1b53f64b
LP
2963
2964 mangled[++n] = NULL;
2965 }
e3e0314b
ZJS
2966 }
2967
1cc6c93a 2968 *ret = TAKE_PTR(mangled);
1238ee09 2969
e3e0314b
ZJS
2970 return 0;
2971}
2972
47a0eaa6
MS
2973static const struct {
2974 const char *target;
2975 const char *verb;
2976 const char *mode;
2977} action_table[_ACTION_MAX] = {
e68c79db
ML
2978 [ACTION_HALT] = { SPECIAL_HALT_TARGET, "halt", "replace-irreversibly" },
2979 [ACTION_POWEROFF] = { SPECIAL_POWEROFF_TARGET, "poweroff", "replace-irreversibly" },
2980 [ACTION_REBOOT] = { SPECIAL_REBOOT_TARGET, "reboot", "replace-irreversibly" },
2981 [ACTION_KEXEC] = { SPECIAL_KEXEC_TARGET, "kexec", "replace-irreversibly" },
2982 [ACTION_RUNLEVEL2] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2983 [ACTION_RUNLEVEL3] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2984 [ACTION_RUNLEVEL4] = { SPECIAL_MULTI_USER_TARGET, NULL, "isolate" },
2985 [ACTION_RUNLEVEL5] = { SPECIAL_GRAPHICAL_TARGET, NULL, "isolate" },
2986 [ACTION_RESCUE] = { SPECIAL_RESCUE_TARGET, "rescue", "isolate" },
2987 [ACTION_EMERGENCY] = { SPECIAL_EMERGENCY_TARGET, "emergency", "isolate" },
2988 [ACTION_DEFAULT] = { SPECIAL_DEFAULT_TARGET, "default", "isolate" },
2989 [ACTION_EXIT] = { SPECIAL_EXIT_TARGET, "exit", "replace-irreversibly" },
2990 [ACTION_SUSPEND] = { SPECIAL_SUSPEND_TARGET, "suspend", "replace-irreversibly" },
2991 [ACTION_HIBERNATE] = { SPECIAL_HIBERNATE_TARGET, "hibernate", "replace-irreversibly" },
2992 [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
2993 [ACTION_SUSPEND_THEN_HIBERNATE] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET, "suspend-then-hibernate", "replace-irreversibly" },
47a0eaa6
MS
2994};
2995
514f4ef5 2996static enum action verb_to_action(const char *verb) {
47a0eaa6
MS
2997 enum action i;
2998
913c1916 2999 for (i = 0; i < _ACTION_MAX; i++)
f459b602 3000 if (streq_ptr(action_table[i].verb, verb))
47a0eaa6 3001 return i;
514f4ef5 3002
f459b602
MAP
3003 return _ACTION_INVALID;
3004}
e4b61340 3005
e449de87 3006static int start_unit(int argc, char *argv[], void *userdata) {
ebd011d9 3007 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
08073121 3008 const char *method, *mode, *one_name, *suffix = NULL;
ebd011d9 3009 _cleanup_strv_free_ char **names = NULL;
4fbd7192 3010 sd_bus *bus;
93a08841 3011 _cleanup_(wait_context_free) WaitContext wait_context = {};
729e3769 3012 char **name;
b6520546 3013 int r = 0;
e4b61340 3014
f886603b
AJ
3015 if (arg_wait && !STR_IN_SET(argv[0], "start", "restart")) {
3016 log_error("--wait may only be used with the 'start' or 'restart' commands.");
93a08841
MP
3017 return -EINVAL;
3018 }
3019
3020 /* we cannot do sender tracking on the private bus, so we need the full
3021 * one for RefUnit to implement --wait */
3022 r = acquire_bus(arg_wait ? BUS_FULL : BUS_MANAGER, &bus);
4fbd7192
LP
3023 if (r < 0)
3024 return r;
3025
d2ad7e1b 3026 ask_password_agent_open_if_enabled();
8a4b13c5 3027 polkit_agent_open_maybe();
d2ad7e1b 3028
e4b61340 3029 if (arg_action == ACTION_SYSTEMCTL) {
47a0eaa6 3030 enum action action;
e4b61340 3031
e449de87
LP
3032 action = verb_to_action(argv[0]);
3033
913c1916
AJ
3034 if (action != _ACTION_INVALID) {
3035 method = "StartUnit";
3036 mode = action_table[action].mode;
3037 one_name = action_table[action].target;
3038 } else {
3039 if (streq(argv[0], "isolate")) {
3040 method = "StartUnit";
3041 mode = "isolate";
3042
3043 suffix = ".target";
3044 } else {
3045 method = verb_to_method(argv[0]);
3046 mode = arg_job_mode;
3047 }
3048 one_name = NULL;
3049 }
e4b61340 3050 } else {
78ca9099 3051 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
47a0eaa6 3052 assert(action_table[arg_action].target);
913c1916 3053 assert(action_table[arg_action].mode);
e4b61340
LP
3054
3055 method = "StartUnit";
47a0eaa6 3056 mode = action_table[arg_action].mode;
e3e0314b 3057 one_name = action_table[arg_action].target;
514f4ef5
LP
3058 }
3059
e3e0314b
ZJS
3060 if (one_name)
3061 names = strv_new(one_name, NULL);
3062 else {
e449de87 3063 r = expand_names(bus, strv_skip(argv, 1), suffix, &names);
e3e0314b 3064 if (r < 0)
691395d8 3065 return log_error_errno(r, "Failed to expand names: %m");
e3e0314b 3066 }
b6520546 3067
6e905d93 3068 if (!arg_no_block) {
ebd011d9 3069 r = bus_wait_for_jobs_new(bus, &w);
f647962d
MS
3070 if (r < 0)
3071 return log_error_errno(r, "Could not watch jobs: %m");
e4b61340
LP
3072 }
3073
93a08841 3074 if (arg_wait) {
93a08841
MP
3075 wait_context.unit_paths = set_new(&string_hash_ops);
3076 if (!wait_context.unit_paths)
3077 return log_oom();
3078
31b2cd5d 3079 r = sd_bus_call_method_async(
93a08841 3080 bus,
31b2cd5d 3081 NULL,
93a08841
MP
3082 "org.freedesktop.systemd1",
3083 "/org/freedesktop/systemd1",
3084 "org.freedesktop.systemd1.Manager",
3085 "Subscribe",
31b2cd5d
LP
3086 NULL, NULL,
3087 NULL);
93a08841 3088 if (r < 0)
31b2cd5d 3089 return log_error_errno(r, "Failed to enable subscription: %m");
93a08841
MP
3090 r = sd_event_default(&wait_context.event);
3091 if (r < 0)
3092 return log_error_errno(r, "Failed to allocate event loop: %m");
3093 r = sd_bus_attach_event(bus, wait_context.event, 0);
3094 if (r < 0)
3095 return log_error_errno(r, "Failed to attach bus to event loop: %m");
3096 }
3097
b6520546 3098 STRV_FOREACH(name, names) {
4afd3348 3099 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
b6520546 3100 int q;
f459b602 3101
93a08841 3102 q = start_unit_one(bus, method, *name, mode, &error, w, arg_wait ? &wait_context : NULL);
e3e0314b 3103 if (r >= 0 && q < 0)
b6520546 3104 r = translate_bus_error_to_exit_status(q, &error);
e4b61340
LP
3105 }
3106
67f3c402 3107 if (!arg_no_block) {
c11bda1e
ZJS
3108 int q, arg_count = 0;
3109 const char* extra_args[4] = {};
4524439e 3110
4524439e
ZJS
3111 if (arg_scope != UNIT_FILE_SYSTEM)
3112 extra_args[arg_count++] = "--user";
3113
3114 assert(IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_REMOTE, BUS_TRANSPORT_MACHINE));
3115 if (arg_transport == BUS_TRANSPORT_REMOTE) {
3116 extra_args[arg_count++] = "-H";
3117 extra_args[arg_count++] = arg_host;
3118 } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
3119 extra_args[arg_count++] = "-M";
3120 extra_args[arg_count++] = arg_host;
3121 }
f459b602 3122
4524439e 3123 q = bus_wait_for_jobs(w, arg_quiet, extra_args);
f459b602
MAP
3124 if (q < 0)
3125 return q;
49111a70
ZJS
3126
3127 /* When stopping units, warn if they can still be triggered by
3128 * another active unit (socket, path, timer) */
b6520546
ZJS
3129 if (!arg_quiet && streq(method, "StopUnit"))
3130 STRV_FOREACH(name, names)
3131 check_triggering_units(bus, *name);
67f3c402 3132 }
514f4ef5 3133
93a08841
MP
3134 if (r >= 0 && arg_wait) {
3135 int q;
3136 q = sd_event_loop(wait_context.event);
3137 if (q < 0)
3138 return log_error_errno(q, "Failed to run event loop: %m");
3139 if (wait_context.any_failed)
3140 r = EXIT_FAILURE;
3141 }
3142
f459b602 3143 return r;
e4b61340
LP
3144}
3145
349cc4a5 3146#if ENABLE_LOGIND
4fbd7192 3147static int logind_set_wall_message(void) {
4afd3348 3148 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 3149 sd_bus *bus;
f2d11d35
LP
3150 _cleanup_free_ char *m = NULL;
3151 int r;
3152
4fbd7192
LP
3153 r = acquire_bus(BUS_FULL, &bus);
3154 if (r < 0)
3155 return r;
f2d11d35
LP
3156
3157 m = strv_join(arg_wall, " ");
3158 if (!m)
3159 return log_oom();
3160
dbc9830c
ZJS
3161 log_debug("%s wall message \"%s\".", arg_dry_run ? "Would set" : "Setting", m);
3162 if (arg_dry_run)
3163 return 0;
3164
f2d11d35
LP
3165 r = sd_bus_call_method(
3166 bus,
3167 "org.freedesktop.login1",
3168 "/org/freedesktop/login1",
3169 "org.freedesktop.login1.Manager",
3170 "SetWallMessage",
3171 &error,
3172 NULL,
3173 "sb",
3174 m,
3175 !arg_no_wall);
3176
3177 if (r < 0)
3178 return log_warning_errno(r, "Failed to set wall message, ignoring: %s", bus_error_message(&error, r));
f2d11d35
LP
3179 return 0;
3180}
79f1c8f6 3181#endif
f2d11d35 3182
7e59bfcb
LP
3183/* Ask systemd-logind, which might grant access to unprivileged users
3184 * through PolicyKit */
4fbd7192 3185static int logind_reboot(enum action a) {
349cc4a5 3186#if ENABLE_LOGIND
4afd3348 3187 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
58158dc7 3188 const char *method, *description;
4fbd7192 3189 sd_bus *bus;
f459b602 3190 int r;
4c80c73c 3191
4fbd7192
LP
3192 r = acquire_bus(BUS_FULL, &bus);
3193 if (r < 0)
3194 return r;
f2d11d35 3195
4c80c73c
KS
3196 switch (a) {
3197
36b69c31
LP
3198 case ACTION_POWEROFF:
3199 method = "PowerOff";
3200 description = "power off system";
3201 break;
3202
4c80c73c
KS
3203 case ACTION_REBOOT:
3204 method = "Reboot";
58158dc7 3205 description = "reboot system";
4c80c73c
KS
3206 break;
3207
36b69c31
LP
3208 case ACTION_HALT:
3209 method = "Halt";
3210 description = "halt system";
4c80c73c
KS
3211 break;
3212
d889a206
LP
3213 case ACTION_SUSPEND:
3214 method = "Suspend";
58158dc7 3215 description = "suspend system";
d889a206
LP
3216 break;
3217
3218 case ACTION_HIBERNATE:
3219 method = "Hibernate";
58158dc7 3220 description = "hibernate system";
d889a206
LP
3221 break;
3222
6524990f
LP
3223 case ACTION_HYBRID_SLEEP:
3224 method = "HybridSleep";
58158dc7 3225 description = "put system into hybrid sleep";
6524990f
LP
3226 break;
3227
e68c79db
ML
3228 case ACTION_SUSPEND_THEN_HIBERNATE:
3229 method = "SuspendThenHibernate";
c58493c0
ML
3230 description = "put system into suspend followed by hibernate";
3231 break;
3232
4c80c73c
KS
3233 default:
3234 return -EINVAL;
3235 }
3236
8a4b13c5 3237 polkit_agent_open_maybe();
d2ad7e1b
ZJS
3238 (void) logind_set_wall_message();
3239
dbc9830c
ZJS
3240 log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run ? "Would execute" : "Executing", method);
3241 if (arg_dry_run)
3242 return 0;
3243
f459b602 3244 r = sd_bus_call_method(
f22f08cd
SP
3245 bus,
3246 "org.freedesktop.login1",
3247 "/org/freedesktop/login1",
3248 "org.freedesktop.login1.Manager",
3249 method,
f459b602 3250 &error,
f22f08cd 3251 NULL,
342641fb 3252 "b", arg_ask_password);
f459b602 3253 if (r < 0)
691395d8 3254 return log_error_errno(r, "Failed to %s via logind: %s", description, bus_error_message(&error, r));
f459b602 3255
691395d8 3256 return 0;
4c80c73c
KS
3257#else
3258 return -ENOSYS;
3259#endif
3260}
3261
4fbd7192 3262static int logind_check_inhibitors(enum action a) {
349cc4a5 3263#if ENABLE_LOGIND
4afd3348 3264 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
59164be4 3265 _cleanup_strv_free_ char **sessions = NULL;
f459b602
MAP
3266 const char *what, *who, *why, *mode;
3267 uint32_t uid, pid;
4fbd7192 3268 sd_bus *bus;
f459b602 3269 unsigned c = 0;
59164be4 3270 char **s;
f459b602 3271 int r;
b37844d3 3272
748ebafa
LP
3273 if (arg_ignore_inhibitors || arg_force > 0)
3274 return 0;
3275
3276 if (arg_when > 0)
3277 return 0;
3278
3279 if (geteuid() == 0)
b37844d3
LP
3280 return 0;
3281
3282 if (!on_tty())
3283 return 0;
e08ab379
LP
3284
3285 if (arg_transport != BUS_TRANSPORT_LOCAL)
3286 return 0;
b37844d3 3287
4fbd7192
LP
3288 r = acquire_bus(BUS_FULL, &bus);
3289 if (r < 0)
3290 return r;
3291
f459b602 3292 r = sd_bus_call_method(
b37844d3
LP
3293 bus,
3294 "org.freedesktop.login1",
3295 "/org/freedesktop/login1",
3296 "org.freedesktop.login1.Manager",
3297 "ListInhibitors",
b37844d3 3298 NULL,
f459b602
MAP
3299 &reply,
3300 NULL);
b37844d3
LP
3301 if (r < 0)
3302 /* If logind is not around, then there are no inhibitors... */
3303 return 0;
3304
4aa2beac 3305 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
f459b602
MAP
3306 if (r < 0)
3307 return bus_log_parse_error(r);
b37844d3 3308
4aa2beac 3309 while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
59164be4 3310 _cleanup_free_ char *comm = NULL, *user = NULL;
f459b602 3311 _cleanup_strv_free_ char **sv = NULL;
b37844d3
LP
3312
3313 if (!streq(mode, "block"))
f459b602 3314 continue;
b37844d3
LP
3315
3316 sv = strv_split(what, ":");
3317 if (!sv)
3318 return log_oom();
3319
ee043777 3320 if (!pid_is_valid((pid_t) pid)) {
72b3f82e 3321 log_error("Invalid PID "PID_FMT".", (pid_t) pid);
ee043777
LP
3322 return -ERANGE;
3323 }
d028e018 3324
b37844d3 3325 if (!strv_contains(sv,
4c315c2c
IS
3326 IN_SET(a,
3327 ACTION_HALT,
3328 ACTION_POWEROFF,
3329 ACTION_REBOOT,
3330 ACTION_KEXEC) ? "shutdown" : "sleep"))
f459b602 3331 continue;
b37844d3
LP
3332
3333 get_process_comm(pid, &comm);
59164be4 3334 user = uid_to_name(uid);
f459b602 3335
de0671ee 3336 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT" \"%s\", user %s), reason is \"%s\".",
d028e018 3337 who, (pid_t) pid, strna(comm), strna(user), why);
b37844d3 3338
f459b602 3339 c++;
b37844d3 3340 }
f459b602
MAP
3341 if (r < 0)
3342 return bus_log_parse_error(r);
b37844d3 3343
f459b602
MAP
3344 r = sd_bus_message_exit_container(reply);
3345 if (r < 0)
3346 return bus_log_parse_error(r);
b37844d3 3347
59164be4
LP
3348 /* Check for current sessions */
3349 sd_get_sessions(&sessions);
3350 STRV_FOREACH(s, sessions) {
59164be4
LP
3351 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
3352
3353 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
3354 continue;
3355
3356 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
3357 continue;
3358
28abce5d 3359 if (sd_session_get_type(*s, &type) < 0 || !STR_IN_SET(type, "x11", "wayland", "tty", "mir"))
59164be4
LP
3360 continue;
3361
3362 sd_session_get_tty(*s, &tty);
3363 sd_session_get_seat(*s, &seat);
3364 sd_session_get_service(*s, &service);
3365 user = uid_to_name(uid);
3366
3367 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
3368 c++;
3369 }
3370
b37844d3
LP
3371 if (c <= 0)
3372 return 0;
3373
59164be4 3374 log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'systemctl %s -i'.",
47a0eaa6 3375 action_table[a].verb);
b37844d3
LP
3376
3377 return -EPERM;
3378#else
3379 return 0;
3380#endif
3381}
3382
4fbd7192 3383static int logind_prepare_firmware_setup(void) {
349cc4a5 3384#if ENABLE_LOGIND
4afd3348 3385 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 3386 sd_bus *bus;
a4921cf4
JJ
3387 int r;
3388
4fbd7192
LP
3389 r = acquire_bus(BUS_FULL, &bus);
3390 if (r < 0)
3391 return r;
a4921cf4 3392
a4921cf4
JJ
3393 r = sd_bus_call_method(
3394 bus,
3395 "org.freedesktop.login1",
3396 "/org/freedesktop/login1",
3397 "org.freedesktop.login1.Manager",
3398 "SetRebootToFirmwareSetup",
3399 &error,
3400 NULL,
3401 "b", true);
4fbd7192
LP
3402 if (r < 0)
3403 return log_error_errno(r, "Cannot indicate to EFI to boot into setup mode: %s", bus_error_message(&error, r));
a4921cf4
JJ
3404
3405 return 0;
3406#else
3407 log_error("Cannot remotely indicate to EFI to boot into setup mode.");
4fbd7192 3408 return -ENOSYS;
a4921cf4
JJ
3409#endif
3410}
3411
4fbd7192
LP
3412static int prepare_firmware_setup(void) {
3413 int r;
3414
3415 if (!arg_firmware_setup)
3416 return 0;
3417
3418 if (arg_transport == BUS_TRANSPORT_LOCAL) {
3419
3420 r = efi_set_reboot_to_firmware(true);
3421 if (r < 0)
3422 log_debug_errno(r, "Cannot indicate to EFI to boot into setup mode, will retry via logind: %m");
3423 else
3424 return r;
3425 }
3426
3427 return logind_prepare_firmware_setup();
3428}
3429
4bb2e9d4
ZJS
3430static int load_kexec_kernel(void) {
3431 _cleanup_(boot_config_free) BootConfig config = {};
5caa3167 3432 _cleanup_free_ char *where = NULL, *kernel = NULL, *initrd = NULL, *options = NULL;
4bb2e9d4
ZJS
3433 const BootEntry *e;
3434 pid_t pid;
3435 int r;
3436
3437 if (kexec_loaded()) {
3438 log_debug("Kexec kernel already loaded.");
3439 return 0;
3440 }
3441
c0d73214
ZJS
3442 if (access(KEXEC, X_OK) < 0)
3443 return log_error_errno(errno, KEXEC" is not available: %m");
3444
5caa3167
LP
3445 r = find_esp_and_warn(arg_esp_path, false, &where, NULL, NULL, NULL, NULL);
3446 if (r == -ENOKEY) /* find_esp_and_warn() doesn't warn about this case */
3447 return log_error_errno(r, "Cannot find the ESP partition mount point.");
3448 if (r < 0) /* But it logs about all these cases, hence don't log here again */
3449 return r;
4bb2e9d4 3450
5caa3167 3451 r = boot_entries_load_config(where, &config);
4bb2e9d4 3452 if (r < 0)
5caa3167 3453 return log_error_errno(r, "Failed to load bootspec config from \"%s/loader\": %m", where);
4bb2e9d4
ZJS
3454
3455 if (config.default_entry < 0) {
3456 log_error("No entry suitable as default, refusing to guess.");
3457 return -ENOENT;
3458 }
3459 e = &config.entries[config.default_entry];
3460
3461 if (strv_length(e->initrd) > 1) {
3462 log_error("Boot entry specifies multiple initrds, which is not supported currently.");
3463 return -EINVAL;
3464 }
3465
5caa3167 3466 kernel = path_join(NULL, where, e->kernel);
4bb2e9d4 3467 if (!strv_isempty(e->initrd))
5caa3167 3468 initrd = path_join(NULL, where, *e->initrd);
4bb2e9d4
ZJS
3469 options = strv_join(e->options, " ");
3470 if (!options)
3471 return log_oom();
3472
cd086a01
ZJS
3473 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
3474 "%s "KEXEC" --load \"%s\" --append \"%s\"%s%s%s",
3475 arg_dry_run ? "Would run" : "Running",
3476 kernel,
3477 options,
3478 initrd ? " --initrd \"" : NULL, strempty(initrd), initrd ? "\"" : "");
4bb2e9d4
ZJS
3479 if (arg_dry_run)
3480 return 0;
3481
b6e1fff1 3482 r = safe_fork("(kexec)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
4c253ed1 3483 if (r < 0)
b6e1fff1 3484 return r;
4c253ed1 3485 if (r == 0) {
4bb2e9d4
ZJS
3486 const char* const args[] = {
3487 KEXEC,
3488 "--load", kernel,
3489 "--append", options,
3490 initrd ? "--initrd" : NULL, initrd,
3491 NULL };
3492
3493 /* Child */
4bb2e9d4
ZJS
3494 execv(args[0], (char * const *) args);
3495 _exit(EXIT_FAILURE);
4c253ed1
LP
3496 }
3497
df685d57
ZJS
3498 r = wait_for_terminate_and_check("kexec", pid, WAIT_LOG);
3499 if (r < 0)
3500 return r;
3501 if (r > 0)
3502 /* Command failed */
3503 return -EPROTO;
3504 return 0;
4bb2e9d4
ZJS
3505}
3506
57ab9006 3507static int set_exit_code(uint8_t code) {
4afd3348 3508 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
57ab9006
LP
3509 sd_bus *bus;
3510 int r;
3511
3512 r = acquire_bus(BUS_MANAGER, &bus);
3513 if (r < 0)
3514 return r;
3515
3516 r = sd_bus_call_method(
3517 bus,
3518 "org.freedesktop.systemd1",
3519 "/org/freedesktop/systemd1",
3520 "org.freedesktop.systemd1.Manager",
3521 "SetExitCode",
3522 &error,
3523 NULL,
3524 "y", code);
3525 if (r < 0)
af3d8113 3526 return log_error_errno(r, "Failed to set exit code: %s", bus_error_message(&error, r));
57ab9006
LP
3527
3528 return 0;
3529}
3530
e449de87 3531static int start_special(int argc, char *argv[], void *userdata) {
4c80c73c 3532 enum action a;
983d9c90 3533 int r;
2b0f4e6f
ZJS
3534 bool termination_action; /* an action that terminates the manager,
3535 * can be performed also by signal. */
983d9c90 3536
e449de87 3537 assert(argv);
514f4ef5 3538
e449de87 3539 a = verb_to_action(argv[0]);
4c80c73c 3540
4fbd7192 3541 r = logind_check_inhibitors(a);
748ebafa
LP
3542 if (r < 0)
3543 return r;
3544
fba868fa
LP
3545 if (arg_force >= 2) {
3546 r = must_be_root();
3547 if (r < 0)
3548 return r;
c32b90de
LP
3549 }
3550
4fbd7192 3551 r = prepare_firmware_setup();
a4921cf4
JJ
3552 if (r < 0)
3553 return r;
5bdf2243 3554
e449de87 3555 if (a == ACTION_REBOOT && argc > 1) {
27c06cb5 3556 r = update_reboot_parameter_and_warn(argv[1]);
b986229e
SW
3557 if (r < 0)
3558 return r;
57ab9006 3559
4bb2e9d4
ZJS
3560 } else if (a == ACTION_KEXEC) {
3561 r = load_kexec_kernel();
d23b5ce2
ZJS
3562 if (r < 0 && arg_force >= 1)
3563 log_notice("Failed to load kexec kernel, continuing without.");
3564 else if (r < 0)
4bb2e9d4
ZJS
3565 return r;
3566
e449de87 3567 } else if (a == ACTION_EXIT && argc > 1) {
7bbb5359 3568 uint8_t code;
287419c1 3569
57ab9006
LP
3570 /* If the exit code is not given on the command line,
3571 * don't reset it to zero: just keep it as it might
3572 * have been set previously. */
287419c1 3573
e449de87 3574 r = safe_atou8(argv[1], &code);
4fbd7192 3575 if (r < 0)
57ab9006 3576 return log_error_errno(r, "Invalid exit code.");
4fbd7192 3577
57ab9006 3578 r = set_exit_code(code);
691395d8 3579 if (r < 0)
57ab9006 3580 return r;
b986229e
SW
3581 }
3582
2b0f4e6f
ZJS
3583 termination_action = IN_SET(a,
3584 ACTION_HALT,
3585 ACTION_POWEROFF,
3586 ACTION_REBOOT);
3587 if (termination_action && arg_force >= 2)
477def80 3588 return halt_now(a);
e606bb61 3589
7e59bfcb 3590 if (arg_force >= 1 &&
5955df2c 3591 (termination_action || IN_SET(a, ACTION_KEXEC, ACTION_EXIT)))
2b0f4e6f
ZJS
3592 r = trivial_method(argc, argv, userdata);
3593 else {
3594 /* First try logind, to allow authentication with polkit */
3595 if (IN_SET(a,
3596 ACTION_POWEROFF,
3597 ACTION_REBOOT,
36b69c31 3598 ACTION_HALT,
2b0f4e6f
ZJS
3599 ACTION_SUSPEND,
3600 ACTION_HIBERNATE,
c58493c0 3601 ACTION_HYBRID_SLEEP,
e68c79db 3602 ACTION_SUSPEND_THEN_HIBERNATE)) {
2b0f4e6f
ZJS
3603
3604 r = logind_reboot(a);
3605 if (r >= 0)
3606 return r;
3607 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
3608 /* requested operation is not supported or already in progress */
3609 return r;
20b09ca7 3610
130246d2
LP
3611 /* On all other errors, try low-level operation. In order to minimize the difference between
3612 * operation with and without logind, we explicitly enable non-blocking mode for this, as
3613 * logind's shutdown operations are always non-blocking. */
3614
3615 arg_no_block = true;
3616
3617 } else if (IN_SET(a, ACTION_EXIT, ACTION_KEXEC))
3618 /* Since exit/kexec are so close in behaviour to power-off/reboot, let's also make them
3619 * asynchronous, in order to not confuse the user needlessly with unexpected behaviour. */
3620 arg_no_block = true;
7089051f 3621
2b0f4e6f 3622 r = start_unit(argc, argv, userdata);
4c80c73c 3623 }
983d9c90 3624
2b0f4e6f
ZJS
3625 if (termination_action && arg_force < 2 &&
3626 IN_SET(r, -ENOENT, -ETIMEDOUT))
cc7de2ba 3627 log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1).");
2b0f4e6f
ZJS
3628
3629 return r;
514f4ef5
LP
3630}
3631
988b3b17
ZJS
3632static int start_system_special(int argc, char *argv[], void *userdata) {
3633 /* Like start_special above, but raises an error when running in user mode */
3634
3635 if (arg_scope != UNIT_FILE_SYSTEM) {
3636 log_error("Bad action for %s mode.",
3637 arg_scope == UNIT_FILE_GLOBAL ? "--global" : "--user");
3638 return -EINVAL;
3639 }
3640
3641 return start_special(argc, argv, userdata);
3642}
3643
fa0d5878 3644static int check_unit_generic(int code, const UnitActiveState good_states[], int nb_states, char **args) {
e3e0314b 3645 _cleanup_strv_free_ char **names = NULL;
fa0d5878 3646 UnitActiveState active_state;
4fbd7192 3647 sd_bus *bus;
729e3769 3648 char **name;
fa0d5878 3649 int r, i;
d60f6ad0 3650 bool found = false;
0183528f 3651
4fbd7192
LP
3652 r = acquire_bus(BUS_MANAGER, &bus);
3653 if (r < 0)
3654 return r;
3655
e3e0314b 3656 r = expand_names(bus, args, NULL, &names);
f647962d
MS
3657 if (r < 0)
3658 return log_error_errno(r, "Failed to expand names: %m");
e3e0314b
ZJS
3659
3660 STRV_FOREACH(name, names) {
fa0d5878
BR
3661 r = get_state_one_unit(bus, *name, &active_state);
3662 if (r < 0)
3663 return r;
3664
3665 if (!arg_quiet)
3666 puts(unit_active_state_to_string(active_state));
60f9ba0b 3667
fa0d5878
BR
3668 for (i = 0; i < nb_states; ++i)
3669 if (good_states[i] == active_state)
3670 found = true;
1a0fce45
TA
3671 }
3672
d60f6ad0
LN
3673 /* use the given return code for the case that we won't find
3674 * any unit which matches the list */
3675 return found ? 0 : code;
1a0fce45
TA
3676}
3677
e449de87 3678static int check_unit_active(int argc, char *argv[], void *userdata) {
fa0d5878 3679 const UnitActiveState states[] = { UNIT_ACTIVE, UNIT_RELOADING };
e3e0314b 3680 /* According to LSB: 3, "program is not running" */
b613907e 3681 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1));
e3e0314b 3682}
0183528f 3683
e449de87 3684static int check_unit_failed(int argc, char *argv[], void *userdata) {
fa0d5878 3685 const UnitActiveState states[] = { UNIT_FAILED };
b613907e 3686 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1));
48220598
LP
3687}
3688
e449de87 3689static int kill_unit(int argc, char *argv[], void *userdata) {
e3e0314b 3690 _cleanup_strv_free_ char **names = NULL;
ac5e3a50 3691 char *kill_who = NULL, **name;
4fbd7192 3692 sd_bus *bus;
e3e0314b 3693 int r, q;
8a0867d6 3694
4fbd7192
LP
3695 r = acquire_bus(BUS_MANAGER, &bus);
3696 if (r < 0)
3697 return r;
3698
8a4b13c5 3699 polkit_agent_open_maybe();
d2ad7e1b 3700
8a0867d6
LP
3701 if (!arg_kill_who)
3702 arg_kill_who = "all";
3703
ac5e3a50
JS
3704 /* --fail was specified */
3705 if (streq(arg_job_mode, "fail"))
81d62103 3706 kill_who = strjoina(arg_kill_who, "-fail");
ac5e3a50 3707
e449de87 3708 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
e3e0314b 3709 if (r < 0)
691395d8 3710 return log_error_errno(r, "Failed to expand names: %m");
60f9ba0b 3711
e3e0314b 3712 STRV_FOREACH(name, names) {
4afd3348 3713 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
342641fb 3714
6e646d22 3715 q = sd_bus_call_method(
f22f08cd 3716 bus,
b0193f1c
LP
3717 "org.freedesktop.systemd1",
3718 "/org/freedesktop/systemd1",
3719 "org.freedesktop.systemd1.Manager",
6e646d22
LP
3720 "KillUnit",
3721 &error,
3722 NULL,
169d7fb6 3723 "ssi", *name, kill_who ? kill_who : arg_kill_who, arg_signal);
e3e0314b 3724 if (q < 0) {
169d7fb6 3725 log_error_errno(q, "Failed to kill unit %s: %s", *name, bus_error_message(&error, q));
e3e0314b
ZJS
3726 if (r == 0)
3727 r = q;
f459b602 3728 }
8a0867d6 3729 }
f459b602 3730
e3e0314b 3731 return r;
8a0867d6
LP
3732}
3733
582a507f 3734typedef struct ExecStatusInfo {
0129173a
LP
3735 char *name;
3736
582a507f
LP
3737 char *path;
3738 char **argv;
3739
b708e7ce
LP
3740 bool ignore;
3741
582a507f
LP
3742 usec_t start_timestamp;
3743 usec_t exit_timestamp;
3744 pid_t pid;
3745 int code;
3746 int status;
3747
3748 LIST_FIELDS(struct ExecStatusInfo, exec);
3749} ExecStatusInfo;
3750
3751static void exec_status_info_free(ExecStatusInfo *i) {
3752 assert(i);
3753
0129173a 3754 free(i->name);
582a507f
LP
3755 free(i->path);
3756 strv_free(i->argv);
3757 free(i);
3758}
3759
f459b602 3760static int exec_status_info_deserialize(sd_bus_message *m, ExecStatusInfo *i) {
b21a0ef8 3761 uint64_t start_timestamp, exit_timestamp, start_timestamp_monotonic, exit_timestamp_monotonic;
f459b602 3762 const char *path;
582a507f
LP
3763 uint32_t pid;
3764 int32_t code, status;
f459b602 3765 int ignore, r;
582a507f 3766
f459b602 3767 assert(m);
582a507f 3768 assert(i);
582a507f 3769
f459b602
MAP
3770 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_STRUCT, "sasbttttuii");
3771 if (r < 0)
3772 return bus_log_parse_error(r);
3773 else if (r == 0)
3774 return 0;
582a507f 3775
f459b602
MAP
3776 r = sd_bus_message_read(m, "s", &path);
3777 if (r < 0)
3778 return bus_log_parse_error(r);
582a507f 3779
f84190d8
LP
3780 i->path = strdup(path);
3781 if (!i->path)
f459b602 3782 return log_oom();
582a507f 3783
f459b602
MAP
3784 r = sd_bus_message_read_strv(m, &i->argv);
3785 if (r < 0)
3786 return bus_log_parse_error(r);
3787
3788 r = sd_bus_message_read(m,
3789 "bttttuii",
3790 &ignore,
3791 &start_timestamp, &start_timestamp_monotonic,
3792 &exit_timestamp, &exit_timestamp_monotonic,
3793 &pid,
3794 &code, &status);
3795 if (r < 0)
3796 return bus_log_parse_error(r);
582a507f 3797
b708e7ce 3798 i->ignore = ignore;
582a507f
LP
3799 i->start_timestamp = (usec_t) start_timestamp;
3800 i->exit_timestamp = (usec_t) exit_timestamp;
3801 i->pid = (pid_t) pid;
3802 i->code = code;
3803 i->status = status;
3804
f459b602
MAP
3805 r = sd_bus_message_exit_container(m);
3806 if (r < 0)
3807 return bus_log_parse_error(r);
3808
3809 return 1;
582a507f
LP
3810}
3811
d5db7fe6
WC
3812typedef struct UnitCondition {
3813 char *name;
b1ed76ae 3814 char *param;
d5db7fe6
WC
3815 bool trigger;
3816 bool negate;
d5db7fe6
WC
3817 int tristate;
3818
b1ed76ae 3819 LIST_FIELDS(struct UnitCondition, conditions);
d5db7fe6
WC
3820} UnitCondition;
3821
3822static void unit_condition_free(UnitCondition *c) {
9bb71940
ZJS
3823 if (!c)
3824 return;
d5db7fe6
WC
3825
3826 free(c->name);
3827 free(c->param);
3828 free(c);
3829}
3830
9bb71940
ZJS
3831DEFINE_TRIVIAL_CLEANUP_FUNC(UnitCondition*, unit_condition_free);
3832
61cbdc4b
LP
3833typedef struct UnitStatusInfo {
3834 const char *id;
3835 const char *load_state;
3836 const char *active_state;
3837 const char *sub_state;
a4375746 3838 const char *unit_file_state;
d2dc52db 3839 const char *unit_file_preset;
61cbdc4b
LP
3840
3841 const char *description;
4a9e2fff 3842 const char *following;
61cbdc4b 3843
49dbfa7b
LP
3844 char **documentation;
3845
1b64d026
LP
3846 const char *fragment_path;
3847 const char *source_path;
4ad49000 3848 const char *control_group;
61cbdc4b 3849
76d14b87
OS
3850 char **dropin_paths;
3851
9f39404c 3852 const char *load_error;
f42806df 3853 const char *result;
9f39404c 3854
584be568 3855 usec_t inactive_exit_timestamp;
df50185b 3856 usec_t inactive_exit_timestamp_monotonic;
584be568
LP
3857 usec_t active_enter_timestamp;
3858 usec_t active_exit_timestamp;
3859 usec_t inactive_enter_timestamp;
3860
45fb0699 3861 bool need_daemon_reload;
055ef36b 3862 bool transient;
45fb0699 3863
61cbdc4b
LP
3864 /* Service */
3865 pid_t main_pid;
3866 pid_t control_pid;
3867 const char *status_text;
175728c4 3868 const char *pid_file;
d06dacd0 3869 bool running:1;
b4af5a80 3870 int status_errno;
61cbdc4b
LP
3871
3872 usec_t start_timestamp;
3873 usec_t exit_timestamp;
3874
3875 int exit_code, exit_status;
3876
90bbc946
LP
3877 usec_t condition_timestamp;
3878 bool condition_result;
b1ed76ae 3879 LIST_HEAD(UnitCondition, conditions);
59fccdc5
LP
3880
3881 usec_t assert_timestamp;
3882 bool assert_result;
3883 bool failed_assert_trigger;
3884 bool failed_assert_negate;
3885 const char *failed_assert;
3886 const char *failed_assert_parameter;
601b0842
GS
3887 usec_t next_elapse_real;
3888 usec_t next_elapse_monotonic;
90bbc946 3889
61cbdc4b
LP
3890 /* Socket */
3891 unsigned n_accepted;
3892 unsigned n_connections;
b8131a87 3893 bool accept;
61cbdc4b 3894
13160134 3895 /* Pairs of type, path */
67419600
OS
3896 char **listen;
3897
61cbdc4b
LP
3898 /* Device */
3899 const char *sysfs_path;
3900
3901 /* Mount, Automount */
3902 const char *where;
3903
3904 /* Swap */
3905 const char *what;
582a507f 3906
934277fe
LP
3907 /* CGroup */
3908 uint64_t memory_current;
da4d897e
TH
3909 uint64_t memory_low;
3910 uint64_t memory_high;
3911 uint64_t memory_max;
96e131ea 3912 uint64_t memory_swap_max;
934277fe 3913 uint64_t memory_limit;
5ad096b3 3914 uint64_t cpu_usage_nsec;
03a7b521
LP
3915 uint64_t tasks_current;
3916 uint64_t tasks_max;
934277fe 3917
0e97c93f
DM
3918 uint64_t ip_ingress_bytes;
3919 uint64_t ip_egress_bytes;
3920
582a507f 3921 LIST_HEAD(ExecStatusInfo, exec);
61cbdc4b
LP
3922} UnitStatusInfo;
3923
a7335518
ZJS
3924static void unit_status_info_free(UnitStatusInfo *info) {
3925 ExecStatusInfo *p;
3926 UnitCondition *c;
3927
3928 strv_free(info->documentation);
3929 strv_free(info->dropin_paths);
3930 strv_free(info->listen);
3931
3932 while ((c = info->conditions)) {
3933 LIST_REMOVE(conditions, info->conditions, c);
3934 unit_condition_free(c);
3935 }
3936
3937 while ((p = info->exec)) {
3938 LIST_REMOVE(exec, info->exec, p);
3939 exec_status_info_free(p);
3940 }
3941}
3942
f459b602 3943static void print_status_info(
291d565a 3944 sd_bus *bus,
f459b602
MAP
3945 UnitStatusInfo *i,
3946 bool *ellipsized) {
3947
c7080257 3948 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1, since2[FORMAT_TIMESTAMP_MAX], *s2;
b0d14c69 3949 const char *active_on, *active_off, *on, *off, *ss;
c7080257
LP
3950 _cleanup_free_ char *formatted_path = NULL;
3951 ExecStatusInfo *p;
584be568 3952 usec_t timestamp;
1b64d026 3953 const char *path;
13160134 3954 char **t, **t2;
291d565a 3955 int r;
582a507f 3956
61cbdc4b
LP
3957 assert(i);
3958
3959 /* This shows pretty information about a unit. See
3960 * print_property() for a low-level property printer */
3961
b0d14c69
LP
3962 if (streq_ptr(i->active_state, "failed")) {
3963 active_on = ansi_highlight_red();
1fc464f6 3964 active_off = ansi_normal();
1cf03a4f 3965 } else if (STRPTR_IN_SET(i->active_state, "active", "reloading")) {
b0d14c69 3966 active_on = ansi_highlight_green();
1fc464f6 3967 active_off = ansi_normal();
b0d14c69
LP
3968 } else
3969 active_on = active_off = "";
3970
323b7dc9 3971 printf("%s%s%s %s", active_on, special_glyph(BLACK_CIRCLE), active_off, strna(i->id));
61cbdc4b
LP
3972
3973 if (i->description && !streq_ptr(i->id, i->description))
3974 printf(" - %s", i->description);
3975
3976 printf("\n");
3977
4a9e2fff 3978 if (i->following)
856323c9 3979 printf(" Follow: unit currently follows state of %s\n", i->following);
4a9e2fff 3980
f7b9e331 3981 if (streq_ptr(i->load_state, "error")) {
0b5a519c 3982 on = ansi_highlight_red();
1fc464f6 3983 off = ansi_normal();
c31b4423
LP
3984 } else
3985 on = off = "";
3986
c7080257
LP
3987 path = i->source_path ?: i->fragment_path;
3988 if (path && terminal_urlify_path(path, NULL, &formatted_path) >= 0)
3989 path = formatted_path;
1b64d026 3990
055ef36b 3991 if (i->load_error != 0)
856323c9
ZJS
3992 printf(" Loaded: %s%s%s (Reason: %s)\n",
3993 on, strna(i->load_state), off, i->load_error);
15ce1647
LP
3994 else if (path && !isempty(i->unit_file_state) && !isempty(i->unit_file_preset) &&
3995 !STR_IN_SET(i->unit_file_state, "generated", "transient"))
d2dc52db
LP
3996 printf(" Loaded: %s%s%s (%s; %s; vendor preset: %s)\n",
3997 on, strna(i->load_state), off, path, i->unit_file_state, i->unit_file_preset);
3998 else if (path && !isempty(i->unit_file_state))
856323c9
ZJS
3999 printf(" Loaded: %s%s%s (%s; %s)\n",
4000 on, strna(i->load_state), off, path, i->unit_file_state);
1b64d026 4001 else if (path)
856323c9
ZJS
4002 printf(" Loaded: %s%s%s (%s)\n",
4003 on, strna(i->load_state), off, path);
61cbdc4b 4004 else
856323c9
ZJS
4005 printf(" Loaded: %s%s%s\n",
4006 on, strna(i->load_state), off);
61cbdc4b 4007
055ef36b
LP
4008 if (i->transient)
4009 printf("Transient: yes\n");
4010
76d14b87 4011 if (!strv_isempty(i->dropin_paths)) {
f459b602 4012 _cleanup_free_ char *dir = NULL;
76d14b87 4013 bool last = false;
f459b602 4014 char ** dropin;
76d14b87
OS
4015
4016 STRV_FOREACH(dropin, i->dropin_paths) {
c7080257
LP
4017 _cleanup_free_ char *dropin_formatted = NULL;
4018 const char *df;
4019
eb2c3192
LP
4020 if (!dir || last) {
4021 printf(dir ? " " :
4022 " Drop-In: ");
76d14b87 4023
97b11eed 4024 dir = mfree(dir);
76d14b87 4025
5f311f8c
LP
4026 dir = dirname_malloc(*dropin);
4027 if (!dir) {
76d14b87
OS
4028 log_oom();
4029 return;
4030 }
4031
eb2c3192
LP
4032 printf("%s\n"
4033 " %s", dir,
323b7dc9 4034 special_glyph(TREE_RIGHT));
76d14b87
OS
4035 }
4036
4037 last = ! (*(dropin + 1) && startswith(*(dropin + 1), dir));
4038
c7080257
LP
4039 if (terminal_urlify_path(*dropin, basename(*dropin), &dropin_formatted) >= 0)
4040 df = dropin_formatted;
4041 else
4042 df = *dropin;
4043
4044 printf("%s%s", df, last ? "\n" : ", ");
76d14b87 4045 }
76d14b87
OS
4046 }
4047
2ee68f72 4048 ss = streq_ptr(i->active_state, i->sub_state) ? NULL : i->sub_state;
2ee68f72 4049 if (ss)
856323c9 4050 printf(" Active: %s%s (%s)%s",
b0d14c69 4051 active_on, strna(i->active_state), ss, active_off);
2ee68f72 4052 else
856323c9 4053 printf(" Active: %s%s%s",
b0d14c69 4054 active_on, strna(i->active_state), active_off);
61cbdc4b 4055
f42806df
LP
4056 if (!isempty(i->result) && !streq(i->result, "success"))
4057 printf(" (Result: %s)", i->result);
4058
1cf03a4f
ZJS
4059 timestamp = STRPTR_IN_SET(i->active_state, "active", "reloading") ? i->active_enter_timestamp :
4060 STRPTR_IN_SET(i->active_state, "inactive", "failed") ? i->inactive_enter_timestamp :
4061 STRPTR_IN_SET(i->active_state, "activating") ? i->inactive_exit_timestamp :
4062 i->active_exit_timestamp;
584be568 4063
bbb8486e 4064 s1 = format_timestamp_relative(since1, sizeof(since1), timestamp);
584be568
LP
4065 s2 = format_timestamp(since2, sizeof(since2), timestamp);
4066
4067 if (s1)
538da63d 4068 printf(" since %s; %s\n", s2, s1);
584be568 4069 else if (s2)
538da63d 4070 printf(" since %s\n", s2);
584be568
LP
4071 else
4072 printf("\n");
4073
601b0842
GS
4074 if (endswith(i->id, ".timer")) {
4075 char tstamp1[FORMAT_TIMESTAMP_RELATIVE_MAX],
4076 tstamp2[FORMAT_TIMESTAMP_MAX];
4077 char *next_rel_time, *next_time;
4078 dual_timestamp nw, next = {i->next_elapse_real,
4079 i->next_elapse_monotonic};
4080 usec_t next_elapse;
4081
4082 printf(" Trigger: ");
4083
4084 dual_timestamp_get(&nw);
4085 next_elapse = calc_next_elapse(&nw, &next);
4086 next_rel_time = format_timestamp_relative(tstamp1,
4087 sizeof(tstamp1),
4088 next_elapse);
4089 next_time = format_timestamp(tstamp2,
4090 sizeof(tstamp2),
4091 next_elapse);
4092
4093 if (next_time && next_rel_time)
4094 printf("%s; %s\n", next_time, next_rel_time);
4095 else
4096 printf("n/a\n");
4097 }
4098
90bbc946 4099 if (!i->condition_result && i->condition_timestamp > 0) {
d5db7fe6
WC
4100 UnitCondition *c;
4101 int n = 0;
4102
bbb8486e 4103 s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp);
90bbc946
LP
4104 s2 = format_timestamp(since2, sizeof(since2), i->condition_timestamp);
4105
59fccdc5 4106 printf("Condition: start %scondition failed%s at %s%s%s\n",
1fc464f6 4107 ansi_highlight_yellow(), ansi_normal(),
5cfee414 4108 s2, s1 ? "; " : "", strempty(s1));
d5db7fe6 4109
b1ed76ae 4110 LIST_FOREACH(conditions, c, i->conditions)
d5db7fe6
WC
4111 if (c->tristate < 0)
4112 n++;
d5db7fe6 4113
b1ed76ae
ZJS
4114 LIST_FOREACH(conditions, c, i->conditions)
4115 if (c->tristate < 0)
4116 printf(" %s %s=%s%s%s was not met\n",
4117 --n ? special_glyph(TREE_BRANCH) : special_glyph(TREE_RIGHT),
4118 c->name,
4119 c->trigger ? "|" : "",
4120 c->negate ? "!" : "",
4121 c->param);
59fccdc5
LP
4122 }
4123
4124 if (!i->assert_result && i->assert_timestamp > 0) {
4125 s1 = format_timestamp_relative(since1, sizeof(since1), i->assert_timestamp);
4126 s2 = format_timestamp(since2, sizeof(since2), i->assert_timestamp);
4127
4128 printf(" Assert: start %sassertion failed%s at %s%s%s\n",
1fc464f6 4129 ansi_highlight_red(), ansi_normal(),
5cfee414 4130 s2, s1 ? "; " : "", strempty(s1));
59fccdc5
LP
4131 if (i->failed_assert_trigger)
4132 printf(" none of the trigger assertions were met\n");
4133 else if (i->failed_assert)
4134 printf(" %s=%s%s was not met\n",
4135 i->failed_assert,
4136 i->failed_assert_negate ? "!" : "",
4137 i->failed_assert_parameter);
90bbc946
LP
4138 }
4139
61cbdc4b 4140 if (i->sysfs_path)
856323c9 4141 printf(" Device: %s\n", i->sysfs_path);
9feeba4b 4142 if (i->where)
856323c9 4143 printf(" Where: %s\n", i->where);
9feeba4b 4144 if (i->what)
856323c9 4145 printf(" What: %s\n", i->what);
49dbfa7b 4146
78c7d20e
LP
4147 STRV_FOREACH(t, i->documentation) {
4148 _cleanup_free_ char *formatted = NULL;
4149 const char *q;
4150
4151 if (terminal_urlify(*t, NULL, &formatted) >= 0)
4152 q = formatted;
4153 else
4154 q = *t;
4155
4156 printf(" %*s %s\n", 9, t == i->documentation ? "Docs:" : "", q);
4157 }
49dbfa7b 4158
13160134 4159 STRV_FOREACH_PAIR(t, t2, i->listen)
856323c9 4160 printf(" %*s %s (%s)\n", 9, t == i->listen ? "Listen:" : "", *t2, *t);
67419600 4161
b8131a87 4162 if (i->accept)
856323c9 4163 printf(" Accepted: %u; Connected: %u\n", i->n_accepted, i->n_connections);
61cbdc4b 4164
582a507f 4165 LIST_FOREACH(exec, p, i->exec) {
13160134 4166 _cleanup_free_ char *argv = NULL;
9a57c629 4167 bool good;
582a507f
LP
4168
4169 /* Only show exited processes here */
4170 if (p->code == 0)
4171 continue;
4172
13160134 4173 argv = strv_join(p->argv, " ");
1fa2f38f 4174 printf(" Process: "PID_FMT" %s=%s ", p->pid, p->name, strna(argv));
582a507f 4175
1f0958f6 4176 good = is_clean_exit(p->code, p->status, EXIT_CLEAN_DAEMON, NULL);
9a57c629 4177 if (!good) {
0b5a519c 4178 on = ansi_highlight_red();
1fc464f6 4179 off = ansi_normal();
9a57c629
LP
4180 } else
4181 on = off = "";
4182
4183 printf("%s(code=%s, ", on, sigchld_code_to_string(p->code));
4184
d06dacd0
LP
4185 if (p->code == CLD_EXITED) {
4186 const char *c;
4187
582a507f 4188 printf("status=%i", p->status);
d06dacd0 4189
1b64d026
LP
4190 c = exit_status_to_string(p->status, EXIT_STATUS_SYSTEMD);
4191 if (c)
d06dacd0
LP
4192 printf("/%s", c);
4193
4194 } else
582a507f 4195 printf("signal=%s", signal_to_string(p->status));
9a57c629
LP
4196
4197 printf(")%s\n", off);
4198
582a507f
LP
4199 if (i->main_pid == p->pid &&
4200 i->start_timestamp == p->start_timestamp &&
4201 i->exit_timestamp == p->start_timestamp)
4202 /* Let's not show this twice */
4203 i->main_pid = 0;
4204
4205 if (p->pid == i->control_pid)
4206 i->control_pid = 0;
4207 }
4208
61cbdc4b 4209 if (i->main_pid > 0 || i->control_pid > 0) {
61cbdc4b 4210 if (i->main_pid > 0) {
8c06592f 4211 printf(" Main PID: "PID_FMT, i->main_pid);
61cbdc4b
LP
4212
4213 if (i->running) {
a081b9ce
LP
4214
4215 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4216 _cleanup_free_ char *comm = NULL;
4217
4218 (void) get_process_comm(i->main_pid, &comm);
4219 if (comm)
4220 printf(" (%s)", comm);
4221 }
4222
6d4fc029 4223 } else if (i->exit_code > 0) {
61cbdc4b
LP
4224 printf(" (code=%s, ", sigchld_code_to_string(i->exit_code));
4225
d06dacd0
LP
4226 if (i->exit_code == CLD_EXITED) {
4227 const char *c;
4228
61cbdc4b 4229 printf("status=%i", i->exit_status);
d06dacd0 4230
1b64d026
LP
4231 c = exit_status_to_string(i->exit_status, EXIT_STATUS_SYSTEMD);
4232 if (c)
d06dacd0
LP
4233 printf("/%s", c);
4234
4235 } else
582a507f 4236 printf("signal=%s", signal_to_string(i->exit_status));
6d4fc029
LP
4237 printf(")");
4238 }
13160134 4239 }
61cbdc4b
LP
4240
4241 if (i->control_pid > 0) {
13160134 4242 _cleanup_free_ char *c = NULL;
61cbdc4b 4243
1089dcd4
LP
4244 if (i->main_pid > 0)
4245 fputs("; Control PID: ", stdout);
4246 else
4247 fputs("Cntrl PID: ", stdout); /* if first in column, abbreviated so it fits alignment */
4248
4249 printf(PID_FMT, i->control_pid);
61cbdc4b 4250
a081b9ce
LP
4251 if (arg_transport == BUS_TRANSPORT_LOCAL) {
4252 (void) get_process_comm(i->control_pid, &c);
4253 if (c)
4254 printf(" (%s)", c);
4255 }
61cbdc4b
LP
4256 }
4257
4258 printf("\n");
4259 }
4260
17bb7382 4261 if (i->status_text)
856323c9 4262 printf(" Status: \"%s\"\n", i->status_text);
b4af5a80
LP
4263 if (i->status_errno > 0)
4264 printf(" Error: %i (%s)\n", i->status_errno, strerror(i->status_errno));
17bb7382 4265
0e97c93f
DM
4266 if (i->ip_ingress_bytes != (uint64_t) -1 && i->ip_egress_bytes != (uint64_t) -1) {
4267 char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
4268
4269 printf(" IP: %s in, %s out\n",
4270 format_bytes(buf_in, sizeof(buf_in), i->ip_ingress_bytes),
4271 format_bytes(buf_out, sizeof(buf_out), i->ip_egress_bytes));
4272 }
4273
03a7b521
LP
4274 if (i->tasks_current != (uint64_t) -1) {
4275 printf(" Tasks: %" PRIu64, i->tasks_current);
4276
4277 if (i->tasks_max != (uint64_t) -1)
2a6736dd 4278 printf(" (limit: %" PRIu64 ")\n", i->tasks_max);
03a7b521
LP
4279 else
4280 printf("\n");
4281 }
4282
934277fe
LP
4283 if (i->memory_current != (uint64_t) -1) {
4284 char buf[FORMAT_BYTES_MAX];
4285
4286 printf(" Memory: %s", format_bytes(buf, sizeof(buf), i->memory_current));
4287
96e131ea
WC
4288 if (i->memory_low > 0 || i->memory_high != CGROUP_LIMIT_MAX ||
4289 i->memory_max != CGROUP_LIMIT_MAX || i->memory_swap_max != CGROUP_LIMIT_MAX ||
da4d897e
TH
4290 i->memory_limit != CGROUP_LIMIT_MAX) {
4291 const char *prefix = "";
4292
4293 printf(" (");
4294 if (i->memory_low > 0) {
4295 printf("%slow: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_low));
4296 prefix = " ";
4297 }
4298 if (i->memory_high != CGROUP_LIMIT_MAX) {
4299 printf("%shigh: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_high));
4300 prefix = " ";
4301 }
4302 if (i->memory_max != CGROUP_LIMIT_MAX) {
4303 printf("%smax: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_max));
4304 prefix = " ";
4305 }
96e131ea
WC
4306 if (i->memory_swap_max != CGROUP_LIMIT_MAX) {
4307 printf("%sswap max: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_swap_max));
4308 prefix = " ";
4309 }
da4d897e
TH
4310 if (i->memory_limit != CGROUP_LIMIT_MAX) {
4311 printf("%slimit: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_limit));
4312 prefix = " ";
4313 }
4314 printf(")");
4315 }
4316 printf("\n");
934277fe
LP
4317 }
4318
5ad096b3
LP
4319 if (i->cpu_usage_nsec != (uint64_t) -1) {
4320 char buf[FORMAT_TIMESPAN_MAX];
4321 printf(" CPU: %s\n", format_timespan(buf, sizeof(buf), i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC));
4322 }
4323
51e22f88 4324 if (i->control_group) {
291d565a
LP
4325 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4326 static const char prefix[] = " ";
ab35fb1b
LP
4327 unsigned c;
4328
51e22f88
LP
4329 printf(" CGroup: %s\n", i->control_group);
4330
291d565a
LP
4331 c = columns();
4332 if (c > sizeof(prefix) - 1)
4333 c -= sizeof(prefix) - 1;
4334 else
4335 c = 0;
ab35fb1b 4336
291d565a
LP
4337 r = unit_show_processes(bus, i->id, i->control_group, prefix, c, get_output_flags(), &error);
4338 if (r == -EBADR) {
b69d29ce
LP
4339 unsigned k = 0;
4340 pid_t extra[2];
4341
291d565a 4342 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
ab35fb1b 4343
b69d29ce
LP
4344 if (i->main_pid > 0)
4345 extra[k++] = i->main_pid;
4346
4347 if (i->control_pid > 0)
4348 extra[k++] = i->control_pid;
4349
0ff308c8 4350 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, i->control_group, prefix, c, extra, k, get_output_flags());
291d565a
LP
4351 } else if (r < 0)
4352 log_warning_errno(r, "Failed to dump process list, ignoring: %s", bus_error_message(&error, r));
c59760ee 4353 }
45fb0699 4354
ece174c5 4355 if (i->id && arg_transport == BUS_TRANSPORT_LOCAL)
3c756001
LP
4356 show_journal_by_unit(
4357 stdout,
4358 i->id,
4359 arg_output,
4360 0,
4361 i->inactive_exit_timestamp_monotonic,
4362 arg_lines,
4363 getuid(),
4364 get_output_flags() | OUTPUT_BEGIN_NEWLINE,
4365 SD_JOURNAL_LOCAL_ONLY,
4366 arg_scope == UNIT_FILE_SYSTEM,
4367 ellipsized);
86aa7ba4 4368
45fb0699 4369 if (i->need_daemon_reload)
3f36991e 4370 warn_unit_file_changed(i->id);
61cbdc4b
LP
4371}
4372
b43f208f 4373static void show_unit_help(UnitStatusInfo *i) {
256425cc
LP
4374 char **p;
4375
4376 assert(i);
4377
4378 if (!i->documentation) {
4379 log_info("Documentation for %s not known.", i->id);
4380 return;
4381 }
4382
78002a67
ZJS
4383 STRV_FOREACH(p, i->documentation)
4384 if (startswith(*p, "man:"))
4385 show_man_page(*p + 4, false);
4386 else
0315fe37 4387 log_info("Can't show: %s", *p);
256425cc
LP
4388}
4389
4679a8c3
YW
4390static int map_main_pid(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4391 UnitStatusInfo *i = userdata;
4392 uint32_t u;
f459b602 4393 int r;
61cbdc4b 4394
4679a8c3
YW
4395 r = sd_bus_message_read(m, "u", &u);
4396 if (r < 0)
4397 return r;
61cbdc4b 4398
4679a8c3
YW
4399 i->main_pid = (pid_t) u;
4400 i->running = u > 0;
b8131a87 4401
4679a8c3
YW
4402 return 0;
4403}
b8131a87 4404
4679a8c3
YW
4405static int map_load_error(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4406 const char *n, *message;
4407 const char **p = userdata;
4408 int r;
b8131a87 4409
4679a8c3
YW
4410 r = sd_bus_message_read(m, "(ss)", &n, &message);
4411 if (r < 0)
4412 return r;
b8131a87 4413
4679a8c3
YW
4414 if (!isempty(message))
4415 *p = message;
61cbdc4b 4416
4679a8c3
YW
4417 return 0;
4418}
61cbdc4b 4419
4679a8c3
YW
4420static int map_listen(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4421 const char *type, *path;
4422 char ***p = userdata;
4423 int r;
61cbdc4b 4424
4679a8c3
YW
4425 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4426 if (r < 0)
4427 return r;
61cbdc4b 4428
4679a8c3 4429 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0) {
61cbdc4b 4430
4679a8c3 4431 r = strv_extend(p, type);
f459b602 4432 if (r < 0)
4679a8c3 4433 return r;
61cbdc4b 4434
4679a8c3 4435 r = strv_extend(p, path);
f459b602 4436 if (r < 0)
4679a8c3 4437 return r;
61cbdc4b 4438 }
4679a8c3
YW
4439 if (r < 0)
4440 return r;
582a507f 4441
4679a8c3
YW
4442 r = sd_bus_message_exit_container(m);
4443 if (r < 0)
4444 return r;
49dbfa7b 4445
4679a8c3
YW
4446 return 0;
4447}
52990c2e 4448
4679a8c3
YW
4449static int map_conditions(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4450 UnitStatusInfo *i = userdata;
4451 const char *cond, *param;
4452 int trigger, negate;
4453 int32_t state;
4454 int r;
52990c2e 4455
4679a8c3
YW
4456 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4457 if (r < 0)
4458 return r;
f459b602 4459
4679a8c3
YW
4460 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4461 _cleanup_(unit_condition_freep) UnitCondition *c = NULL;
d5db7fe6 4462
4679a8c3
YW
4463 c = new0(UnitCondition, 1);
4464 if (!c)
4465 return -ENOMEM;
d5db7fe6 4466
4679a8c3
YW
4467 c->name = strdup(cond);
4468 c->param = strdup(param);
4469 if (!c->name || !c->param)
4470 return -ENOMEM;
d5db7fe6 4471
4679a8c3
YW
4472 c->trigger = trigger;
4473 c->negate = negate;
4474 c->tristate = state;
d5db7fe6 4475
4679a8c3
YW
4476 LIST_PREPEND(conditions, i->conditions, c);
4477 c = NULL;
4478 }
4479 if (r < 0)
4480 return r;
d5db7fe6 4481
4679a8c3
YW
4482 r = sd_bus_message_exit_container(m);
4483 if (r < 0)
4484 return r;
59fccdc5 4485
4679a8c3
YW
4486 return 0;
4487}
59fccdc5 4488
4679a8c3
YW
4489static int map_asserts(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4490 UnitStatusInfo *i = userdata;
4491 const char *cond, *param;
4492 int trigger, negate;
4493 int32_t state;
4494 int r;
59fccdc5 4495
4679a8c3
YW
4496 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sbbsi)");
4497 if (r < 0)
4498 return r;
59fccdc5 4499
4679a8c3
YW
4500 while ((r = sd_bus_message_read(m, "(sbbsi)", &cond, &trigger, &negate, &param, &state)) > 0) {
4501 if (state < 0 && (!trigger || !i->failed_assert)) {
4502 i->failed_assert = cond;
4503 i->failed_assert_trigger = trigger;
4504 i->failed_assert_negate = negate;
4505 i->failed_assert_parameter = param;
4506 }
4507 }
4508 if (r < 0)
4509 return r;
f459b602 4510
4679a8c3
YW
4511 r = sd_bus_message_exit_container(m);
4512 if (r < 0)
4513 return r;
f459b602 4514
4679a8c3
YW
4515 return 0;
4516}
582a507f 4517
4679a8c3
YW
4518static int map_exec(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
4519 _cleanup_free_ ExecStatusInfo *info = NULL;
4520 UnitStatusInfo *i = userdata;
4521 int r;
9f39404c 4522
4679a8c3
YW
4523 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sasbttttuii)");
4524 if (r < 0)
4525 return r;
9f39404c 4526
4679a8c3
YW
4527 info = new0(ExecStatusInfo, 1);
4528 if (!info)
4529 return -ENOMEM;
9f39404c 4530
4679a8c3 4531 while ((r = exec_status_info_deserialize(m, info)) > 0) {
9f39404c 4532
4679a8c3
YW
4533 info->name = strdup(member);
4534 if (!info->name)
4535 return -ENOMEM;
9f39404c 4536
4679a8c3 4537 LIST_PREPEND(exec, i->exec, info);
f459b602 4538
4679a8c3
YW
4539 info = new0(ExecStatusInfo, 1);
4540 if (!info)
4541 return -ENOMEM;
9f39404c 4542 }
4679a8c3
YW
4543 if (r < 0)
4544 return r;
f459b602 4545
4679a8c3 4546 r = sd_bus_message_exit_container(m);
f459b602 4547 if (r < 0)
4679a8c3 4548 return r;
61cbdc4b
LP
4549
4550 return 0;
4551}
4552
4f9a9105
ZJS
4553#define print_prop(name, fmt, ...) \
4554 do { \
4555 if (arg_value) \
4556 printf(fmt "\n", __VA_ARGS__); \
4557 else \
4558 printf("%s=" fmt "\n", name, __VA_ARGS__); \
508f63b4 4559 } while (0)
4f9a9105 4560
07636114
YW
4561static int print_property(const char *name, sd_bus_message *m, bool value, bool all) {
4562 char bus_type;
4563 const char *contents;
f459b602
MAP
4564 int r;
4565
48220598 4566 assert(name);
f459b602 4567 assert(m);
48220598 4568
61cbdc4b
LP
4569 /* This is a low-level property printer, see
4570 * print_status_info() for the nicer output */
4571
07636114
YW
4572 r = sd_bus_message_peek_type(m, &bus_type, &contents);
4573 if (r < 0)
852c1b4d 4574 return r;
48220598 4575
07636114 4576 switch (bus_type) {
48220598 4577
07636114 4578 case SD_BUS_TYPE_STRUCT:
48220598 4579
07636114 4580 if (contents[0] == SD_BUS_TYPE_UINT32 && streq(name, "Job")) {
48220598
LP
4581 uint32_t u;
4582
f459b602
MAP
4583 r = sd_bus_message_read(m, "(uo)", &u, NULL);
4584 if (r < 0)
4585 return bus_log_parse_error(r);
48220598 4586
f459b602 4587 if (u > 0)
4f9a9105 4588 print_prop(name, "%"PRIu32, u);
07636114 4589 else if (all)
4f9a9105 4590 print_prop(name, "%s", "");
48220598 4591
07636114 4592 return 1;
f459b602 4593
07636114 4594 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "Unit")) {
48220598
LP
4595 const char *s;
4596
f459b602
MAP
4597 r = sd_bus_message_read(m, "(so)", &s, NULL);
4598 if (r < 0)
4599 return bus_log_parse_error(r);
48220598 4600
07636114 4601 if (all || !isempty(s))
4f9a9105 4602 print_prop(name, "%s", s);
48220598 4603
07636114 4604 return 1;
f459b602 4605
07636114 4606 } else if (contents[0] == SD_BUS_TYPE_STRING && streq(name, "LoadError")) {
9f39404c
LP
4607 const char *a = NULL, *b = NULL;
4608
f459b602
MAP
4609 r = sd_bus_message_read(m, "(ss)", &a, &b);
4610 if (r < 0)
4611 return bus_log_parse_error(r);
9f39404c 4612
07636114 4613 if (all || !isempty(a) || !isempty(b))
4f9a9105 4614 print_prop(name, "%s \"%s\"", strempty(a), strempty(b));
f786e80d 4615
07636114 4616 return 1;
57183d11
LP
4617 } else if (streq_ptr(name, "SystemCallFilter")) {
4618 _cleanup_strv_free_ char **l = NULL;
4619 int whitelist;
4620
4621 r = sd_bus_message_enter_container(m, 'r', "bas");
4622 if (r < 0)
4623 return bus_log_parse_error(r);
4624
4625 r = sd_bus_message_read(m, "b", &whitelist);
4626 if (r < 0)
4627 return bus_log_parse_error(r);
4628
4629 r = sd_bus_message_read_strv(m, &l);
4630 if (r < 0)
4631 return bus_log_parse_error(r);
4632
4633 r = sd_bus_message_exit_container(m);
4634 if (r < 0)
4635 return bus_log_parse_error(r);
4636
07636114 4637 if (all || whitelist || !strv_isempty(l)) {
57183d11
LP
4638 bool first = true;
4639 char **i;
4640
07636114 4641 if (!value) {
4f9a9105
ZJS
4642 fputs(name, stdout);
4643 fputc('=', stdout);
4644 }
57183d11
LP
4645
4646 if (!whitelist)
4647 fputc('~', stdout);
4648
4649 STRV_FOREACH(i, l) {
4650 if (first)
4651 first = false;
4652 else
4653 fputc(' ', stdout);
4654
4655 fputs(*i, stdout);
4656 }
4657 fputc('\n', stdout);
4658 }
4659
07636114 4660 return 1;
48220598
LP
4661 }
4662
4663 break;
48220598 4664
f459b602 4665 case SD_BUS_TYPE_ARRAY:
48220598 4666
07636114 4667 if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "EnvironmentFiles")) {
f459b602
MAP
4668 const char *path;
4669 int ignore;
8c7be95e 4670
f459b602
MAP
4671 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sb)");
4672 if (r < 0)
4673 return bus_log_parse_error(r);
8c7be95e 4674
f459b602 4675 while ((r = sd_bus_message_read(m, "(sb)", &path, &ignore)) > 0)
009192bb 4676 print_prop(name, "%s (ignore_errors=%s)", path, yes_no(ignore));
8c7be95e 4677
f459b602
MAP
4678 if (r < 0)
4679 return bus_log_parse_error(r);
8c7be95e 4680
f459b602
MAP
4681 r = sd_bus_message_exit_container(m);
4682 if (r < 0)
4683 return bus_log_parse_error(r);
8c7be95e 4684
07636114 4685 return 1;
8c7be95e 4686
07636114 4687 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Paths")) {
f459b602 4688 const char *type, *path;
67419600 4689
f459b602
MAP
4690 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4691 if (r < 0)
4692 return bus_log_parse_error(r);
ebf57b80 4693
f459b602 4694 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
c7366cf1 4695 print_prop(name, "%s (%s)", path, type);
f459b602
MAP
4696 if (r < 0)
4697 return bus_log_parse_error(r);
ebf57b80 4698
f459b602
MAP
4699 r = sd_bus_message_exit_container(m);
4700 if (r < 0)
4701 return bus_log_parse_error(r);
ebf57b80 4702
07636114 4703 return 1;
582a507f 4704
07636114 4705 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Listen")) {
f459b602 4706 const char *type, *path;
67419600 4707
f459b602
MAP
4708 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4709 if (r < 0)
4710 return bus_log_parse_error(r);
67419600 4711
f459b602 4712 while ((r = sd_bus_message_read(m, "(ss)", &type, &path)) > 0)
eabc13c7 4713 print_prop(name, "%s (%s)", path, type);
f459b602
MAP
4714 if (r < 0)
4715 return bus_log_parse_error(r);
67419600 4716
f459b602
MAP
4717 r = sd_bus_message_exit_container(m);
4718 if (r < 0)
4719 return bus_log_parse_error(r);
67419600 4720
07636114 4721 return 1;
67419600 4722
07636114 4723 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersMonotonic")) {
f459b602 4724 const char *base;
07636114 4725 uint64_t v, next_elapse;
707e5e52 4726
f459b602
MAP
4727 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(stt)");
4728 if (r < 0)
4729 return bus_log_parse_error(r);
552e4331 4730
07636114 4731 while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0) {
f459b602 4732 char timespan1[FORMAT_TIMESPAN_MAX], timespan2[FORMAT_TIMESPAN_MAX];
fe68089d 4733
fa6dee52 4734 print_prop(name, "{ %s=%s ; next_elapse=%s }", base,
07636114 4735 format_timespan(timespan1, sizeof(timespan1), v, 0),
4f9a9105 4736 format_timespan(timespan2, sizeof(timespan2), next_elapse, 0));
fe68089d 4737 }
f459b602
MAP
4738 if (r < 0)
4739 return bus_log_parse_error(r);
4740
4741 r = sd_bus_message_exit_container(m);
4742 if (r < 0)
4743 return bus_log_parse_error(r);
fe68089d 4744
07636114 4745 return 1;
fe68089d 4746
07636114 4747 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "TimersCalendar")) {
fa6dee52
YW
4748 const char *base, *spec;
4749 uint64_t next_elapse;
4750
4751 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sst)");
4752 if (r < 0)
4753 return bus_log_parse_error(r);
4754
4755 while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0) {
4756 char timestamp[FORMAT_TIMESTAMP_MAX];
4757
4758 print_prop(name, "{ %s=%s ; next_elapse=%s }", base, spec,
4759 format_timestamp(timestamp, sizeof(timestamp), next_elapse));
4760 }
4761 if (r < 0)
4762 return bus_log_parse_error(r);
4763
4764 r = sd_bus_message_exit_container(m);
4765 if (r < 0)
4766 return bus_log_parse_error(r);
4767
07636114 4768 return 1;
fa6dee52 4769
07636114 4770 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && startswith(name, "Exec")) {
f459b602
MAP
4771 ExecStatusInfo info = {};
4772
4773 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sasbttttuii)");
4774 if (r < 0)
4775 return bus_log_parse_error(r);
4776
4777 while ((r = exec_status_info_deserialize(m, &info)) > 0) {
4778 char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
4779 _cleanup_free_ char *tt;
4780
4781 tt = strv_join(info.argv, " ");
4782
4f9a9105
ZJS
4783 print_prop(name,
4784 "{ path=%s ; argv[]=%s ; ignore_errors=%s ; start_time=[%s] ; stop_time=[%s] ; pid="PID_FMT" ; code=%s ; status=%i%s%s }",
4785 strna(info.path),
4786 strna(tt),
4787 yes_no(info.ignore),
4788 strna(format_timestamp(timestamp1, sizeof(timestamp1), info.start_timestamp)),
4789 strna(format_timestamp(timestamp2, sizeof(timestamp2), info.exit_timestamp)),
4790 info.pid,
4791 sigchld_code_to_string(info.code),
4792 info.status,
4793 info.code == CLD_EXITED ? "" : "/",
4794 strempty(info.code == CLD_EXITED ? NULL : signal_to_string(info.status)));
fe68089d 4795
582a507f
LP
4796 free(info.path);
4797 strv_free(info.argv);
f459b602 4798 zero(info);
707e5e52
LP
4799 }
4800
f459b602
MAP
4801 r = sd_bus_message_exit_container(m);
4802 if (r < 0)
4803 return bus_log_parse_error(r);
4804
07636114 4805 return 1;
4ad49000 4806
07636114 4807 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "DeviceAllow")) {
f459b602 4808 const char *path, *rwm;
4ad49000 4809
f459b602
MAP
4810 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(ss)");
4811 if (r < 0)
4812 return bus_log_parse_error(r);
4ad49000 4813
f459b602 4814 while ((r = sd_bus_message_read(m, "(ss)", &path, &rwm)) > 0)
4f9a9105 4815 print_prop(name, "%s %s", strna(path), strna(rwm));
f459b602
MAP
4816 if (r < 0)
4817 return bus_log_parse_error(r);
4ad49000 4818
f459b602
MAP
4819 r = sd_bus_message_exit_container(m);
4820 if (r < 0)
4821 return bus_log_parse_error(r);
4ad49000 4822
07636114 4823 return 1;
4ad49000 4824
07636114 4825 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
72240b52 4826 STR_IN_SET(name, "IODeviceWeight", "BlockIODeviceWeight")) {
f459b602
MAP
4827 const char *path;
4828 uint64_t weight;
b8ab2dc6 4829
f459b602
MAP
4830 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
4831 if (r < 0)
4832 return bus_log_parse_error(r);
b8ab2dc6 4833
f459b602 4834 while ((r = sd_bus_message_read(m, "(st)", &path, &weight)) > 0)
4f9a9105 4835 print_prop(name, "%s %"PRIu64, strna(path), weight);
f459b602
MAP
4836 if (r < 0)
4837 return bus_log_parse_error(r);
b8ab2dc6 4838
f459b602
MAP
4839 r = sd_bus_message_exit_container(m);
4840 if (r < 0)
4841 return bus_log_parse_error(r);
b8ab2dc6 4842
07636114 4843 return 1;
b8ab2dc6 4844
07636114 4845 } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
72240b52
ZJS
4846 (cgroup_io_limit_type_from_string(name) >= 0 ||
4847 STR_IN_SET(name, "BlockIOReadBandwidth", "BlockIOWriteBandwidth"))) {
f459b602
MAP
4848 const char *path;
4849 uint64_t bandwidth;
4ad49000 4850
f459b602
MAP
4851 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(st)");
4852 if (r < 0)
4853 return bus_log_parse_error(r);
4ad49000 4854
f459b602 4855 while ((r = sd_bus_message_read(m, "(st)", &path, &bandwidth)) > 0)
4f9a9105 4856 print_prop(name, "%s %"PRIu64, strna(path), bandwidth);
f459b602
MAP
4857 if (r < 0)
4858 return bus_log_parse_error(r);
4ad49000 4859
f459b602
MAP
4860 r = sd_bus_message_exit_container(m);
4861 if (r < 0)
4862 return bus_log_parse_error(r);
4ad49000 4863
07636114 4864 return 1;
08f3be7a 4865
07636114 4866 } else if (contents[0] == SD_BUS_TYPE_BYTE && streq(name, "StandardInputData")) {
08f3be7a
LP
4867 _cleanup_free_ char *h = NULL;
4868 const void *p;
4869 size_t sz;
4870 ssize_t n;
4871
4872 r = sd_bus_message_read_array(m, 'y', &p, &sz);
4873 if (r < 0)
4874 return bus_log_parse_error(r);
4875
4876 n = base64mem(p, sz, &h);
4877 if (n < 0)
4878 return log_oom();
4879
4880 print_prop(name, "%s", h);
4881
07636114 4882 return 1;
48220598
LP
4883 }
4884
4885 break;
4886 }
4887
48220598
LP
4888 return 0;
4889}
4890
8559e61d
YW
4891typedef enum SystemctlShowMode{
4892 SYSTEMCTL_SHOW_PROPERTIES,
4893 SYSTEMCTL_SHOW_STATUS,
4894 SYSTEMCTL_SHOW_HELP,
4895 _SYSTEMCTL_SHOW_MODE_MAX,
4896 _SYSTEMCTL_SHOW_MODE_INVALID = -1,
4897} SystemctlShowMode;
4898
4899static const char* const systemctl_show_mode_table[] = {
4900 [SYSTEMCTL_SHOW_PROPERTIES] = "show",
4901 [SYSTEMCTL_SHOW_STATUS] = "status",
4902 [SYSTEMCTL_SHOW_HELP] = "help",
4903};
4904
4905DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(systemctl_show_mode, SystemctlShowMode);
4906
f459b602 4907static int show_one(
f459b602
MAP
4908 sd_bus *bus,
4909 const char *path,
3dced37b 4910 const char *unit,
8559e61d 4911 SystemctlShowMode show_mode,
f459b602
MAP
4912 bool *new_line,
4913 bool *ellipsized) {
4914
3dced37b 4915 static const struct bus_properties_map property_map[] = {
4679a8c3
YW
4916 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
4917 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
4918 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
4919 {}
4920 }, status_map[] = {
4921 { "Id", "s", NULL, offsetof(UnitStatusInfo, id) },
4922 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
4923 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
4924 { "SubState", "s", NULL, offsetof(UnitStatusInfo, sub_state) },
4925 { "UnitFileState", "s", NULL, offsetof(UnitStatusInfo, unit_file_state) },
4926 { "UnitFilePreset", "s", NULL, offsetof(UnitStatusInfo, unit_file_preset) },
4927 { "Description", "s", NULL, offsetof(UnitStatusInfo, description) },
4928 { "Following", "s", NULL, offsetof(UnitStatusInfo, following) },
4929 { "Documentation", "as", NULL, offsetof(UnitStatusInfo, documentation) },
4930 { "FragmentPath", "s", NULL, offsetof(UnitStatusInfo, fragment_path) },
4931 { "SourcePath", "s", NULL, offsetof(UnitStatusInfo, source_path) },
4932 { "ControlGroup", "s", NULL, offsetof(UnitStatusInfo, control_group) },
4933 { "DropInPaths", "as", NULL, offsetof(UnitStatusInfo, dropin_paths) },
4934 { "LoadError", "(ss)", map_load_error, offsetof(UnitStatusInfo, load_error) },
4935 { "Result", "s", NULL, offsetof(UnitStatusInfo, result) },
4936 { "InactiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp) },
4937 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(UnitStatusInfo, inactive_exit_timestamp_monotonic) },
4938 { "ActiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_enter_timestamp) },
4939 { "ActiveExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, active_exit_timestamp) },
4940 { "InactiveEnterTimestamp", "t", NULL, offsetof(UnitStatusInfo, inactive_enter_timestamp) },
4941 { "NeedDaemonReload", "b", NULL, offsetof(UnitStatusInfo, need_daemon_reload) },
4942 { "Transient", "b", NULL, offsetof(UnitStatusInfo, transient) },
4943 { "ExecMainPID", "u", NULL, offsetof(UnitStatusInfo, main_pid) },
4944 { "MainPID", "u", map_main_pid, 0 },
4945 { "ControlPID", "u", NULL, offsetof(UnitStatusInfo, control_pid) },
4946 { "StatusText", "s", NULL, offsetof(UnitStatusInfo, status_text) },
4947 { "PIDFile", "s", NULL, offsetof(UnitStatusInfo, pid_file) },
4948 { "StatusErrno", "i", NULL, offsetof(UnitStatusInfo, status_errno) },
4949 { "ExecMainStartTimestamp", "t", NULL, offsetof(UnitStatusInfo, start_timestamp) },
4950 { "ExecMainExitTimestamp", "t", NULL, offsetof(UnitStatusInfo, exit_timestamp) },
4951 { "ExecMainCode", "i", NULL, offsetof(UnitStatusInfo, exit_code) },
4952 { "ExecMainStatus", "i", NULL, offsetof(UnitStatusInfo, exit_status) },
4953 { "ConditionTimestamp", "t", NULL, offsetof(UnitStatusInfo, condition_timestamp) },
4954 { "ConditionResult", "b", NULL, offsetof(UnitStatusInfo, condition_result) },
4955 { "Conditions", "a(sbbsi)", map_conditions, 0 },
4956 { "AssertTimestamp", "t", NULL, offsetof(UnitStatusInfo, assert_timestamp) },
4957 { "AssertResult", "b", NULL, offsetof(UnitStatusInfo, assert_result) },
4958 { "Asserts", "a(sbbsi)", map_asserts, 0 },
4959 { "NextElapseUSecRealtime", "t", NULL, offsetof(UnitStatusInfo, next_elapse_real) },
4960 { "NextElapseUSecMonotonic", "t", NULL, offsetof(UnitStatusInfo, next_elapse_monotonic) },
4961 { "NAccepted", "u", NULL, offsetof(UnitStatusInfo, n_accepted) },
4962 { "NConnections", "u", NULL, offsetof(UnitStatusInfo, n_connections) },
4963 { "Accept", "b", NULL, offsetof(UnitStatusInfo, accept) },
4964 { "Listen", "a(ss)", map_listen, offsetof(UnitStatusInfo, listen) },
4965 { "SysFSPath", "s", NULL, offsetof(UnitStatusInfo, sysfs_path) },
4966 { "Where", "s", NULL, offsetof(UnitStatusInfo, where) },
4967 { "What", "s", NULL, offsetof(UnitStatusInfo, what) },
4968 { "MemoryCurrent", "t", NULL, offsetof(UnitStatusInfo, memory_current) },
4969 { "MemoryLow", "t", NULL, offsetof(UnitStatusInfo, memory_low) },
4970 { "MemoryHigh", "t", NULL, offsetof(UnitStatusInfo, memory_high) },
4971 { "MemoryMax", "t", NULL, offsetof(UnitStatusInfo, memory_max) },
4972 { "MemorySwapMax", "t", NULL, offsetof(UnitStatusInfo, memory_swap_max) },
4973 { "MemoryLimit", "t", NULL, offsetof(UnitStatusInfo, memory_limit) },
4974 { "CPUUsageNSec", "t", NULL, offsetof(UnitStatusInfo, cpu_usage_nsec) },
4975 { "TasksCurrent", "t", NULL, offsetof(UnitStatusInfo, tasks_current) },
4976 { "TasksMax", "t", NULL, offsetof(UnitStatusInfo, tasks_max) },
4977 { "IPIngressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_ingress_bytes) },
4978 { "IPEgressBytes", "t", NULL, offsetof(UnitStatusInfo, ip_egress_bytes) },
4979 { "ExecStartPre", "a(sasbttttuii)", map_exec, 0 },
4980 { "ExecStart", "a(sasbttttuii)", map_exec, 0 },
4981 { "ExecStartPost", "a(sasbttttuii)", map_exec, 0 },
4982 { "ExecReload", "a(sasbttttuii)", map_exec, 0 },
4983 { "ExecStopPre", "a(sasbttttuii)", map_exec, 0 },
4984 { "ExecStop", "a(sasbttttuii)", map_exec, 0 },
4985 { "ExecStopPost", "a(sasbttttuii)", map_exec, 0 },
3dced37b
LP
4986 {}
4987 };
4988
4afd3348
LP
4989 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4990 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3dced37b 4991 _cleanup_set_free_ Set *found_properties = NULL;
a7335518 4992 _cleanup_(unit_status_info_free) UnitStatusInfo info = {
934277fe 4993 .memory_current = (uint64_t) -1,
da4d897e
TH
4994 .memory_high = CGROUP_LIMIT_MAX,
4995 .memory_max = CGROUP_LIMIT_MAX,
96e131ea 4996 .memory_swap_max = CGROUP_LIMIT_MAX,
934277fe 4997 .memory_limit = (uint64_t) -1,
5ad096b3 4998 .cpu_usage_nsec = (uint64_t) -1,
03a7b521
LP
4999 .tasks_current = (uint64_t) -1,
5000 .tasks_max = (uint64_t) -1,
0e97c93f
DM
5001 .ip_ingress_bytes = (uint64_t) -1,
5002 .ip_egress_bytes = (uint64_t) -1,
934277fe 5003 };
4679a8c3 5004 char **pp;
f459b602 5005 int r;
48220598 5006
48220598 5007 assert(path);
61cbdc4b 5008 assert(new_line);
48220598 5009
e3e0314b
ZJS
5010 log_debug("Showing one %s", path);
5011
4679a8c3 5012 r = bus_map_all_properties(
f22f08cd
SP
5013 bus,
5014 "org.freedesktop.systemd1",
5015 path,
4679a8c3 5016 show_mode == SYSTEMCTL_SHOW_STATUS ? status_map : property_map,
a7e4861c 5017 BUS_MAP_BOOLEAN_AS_BOOL,
f459b602 5018 &error,
f22f08cd 5019 &reply,
4679a8c3 5020 &info);
4c3e8e39
LP
5021 if (r < 0)
5022 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
48220598 5023
4679a8c3
YW
5024 if (unit && streq_ptr(info.load_state, "not-found") && streq_ptr(info.active_state, "inactive")) {
5025 log_full(show_mode == SYSTEMCTL_SHOW_STATUS ? LOG_ERR : LOG_DEBUG,
5026 "Unit %s could not be found.", unit);
e33a06a1 5027
4679a8c3
YW
5028 if (show_mode == SYSTEMCTL_SHOW_STATUS)
5029 return EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN;
5030 else if (show_mode == SYSTEMCTL_SHOW_HELP)
5031 return -ENOENT;
5032 }
e33a06a1 5033
4679a8c3
YW
5034 if (*new_line)
5035 printf("\n");
3dced37b 5036
4679a8c3
YW
5037 *new_line = true;
5038
5039 if (show_mode == SYSTEMCTL_SHOW_STATUS) {
5040 print_status_info(bus, &info, ellipsized);
5041
5042 if (info.active_state && !STR_IN_SET(info.active_state, "active", "reloading"))
5043 return EXIT_PROGRAM_NOT_RUNNING;
5044
5045 return EXIT_PROGRAM_RUNNING_OR_SERVICE_OK;
5046
5047 } else if (show_mode == SYSTEMCTL_SHOW_HELP) {
5048 show_unit_help(&info);
5049 return 0;
3dced37b 5050 }
e33a06a1 5051
4679a8c3
YW
5052 r = sd_bus_message_rewind(reply, true);
5053 if (r < 0)
5054 return log_error_errno(r, "Failed to rewind: %s", bus_error_message(&error, r));
5055
07636114 5056 r = bus_message_print_all_properties(reply, print_property, arg_properties, arg_value, arg_all, &found_properties);
f459b602
MAP
5057 if (r < 0)
5058 return bus_log_parse_error(r);
48220598 5059
4679a8c3
YW
5060 STRV_FOREACH(pp, arg_properties)
5061 if (!set_contains(found_properties, *pp))
5062 log_debug("Property %s does not exist.", *pp);
3dced37b 5063
4679a8c3 5064 return 0;
48220598
LP
5065}
5066
f74294c1 5067static int get_unit_dbus_path_by_pid(
f459b602
MAP
5068 sd_bus *bus,
5069 uint32_t pid,
f74294c1 5070 char **unit) {
f459b602 5071
4afd3348
LP
5072 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5073 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
373d32c9 5074 char *u;
a223b325
MS
5075 int r;
5076
f459b602 5077 r = sd_bus_call_method(
f22f08cd
SP
5078 bus,
5079 "org.freedesktop.systemd1",
5080 "/org/freedesktop/systemd1",
5081 "org.freedesktop.systemd1.Manager",
5082 "GetUnitByPID",
f459b602 5083 &error,
f22f08cd 5084 &reply,
f459b602 5085 "u", pid);
691395d8
LP
5086 if (r < 0)
5087 return log_error_errno(r, "Failed to get unit for PID %"PRIu32": %s", pid, bus_error_message(&error, r));
a223b325 5088
373d32c9 5089 r = sd_bus_message_read(reply, "o", &u);
f459b602
MAP
5090 if (r < 0)
5091 return bus_log_parse_error(r);
5092
373d32c9
LP
5093 u = strdup(u);
5094 if (!u)
5095 return log_oom();
5096
5097 *unit = u;
f74294c1 5098 return 0;
a223b325
MS
5099}
5100
f459b602 5101static int show_all(
f459b602 5102 sd_bus *bus,
f459b602
MAP
5103 bool *new_line,
5104 bool *ellipsized) {
5105
4afd3348 5106 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602
MAP
5107 _cleanup_free_ UnitInfo *unit_infos = NULL;
5108 const UnitInfo *u;
5109 unsigned c;
5bb75bc7 5110 int r, ret = 0;
265a7a2a 5111
1238ee09 5112 r = get_unit_list(bus, NULL, NULL, &unit_infos, 0, &reply);
265a7a2a
ZJS
5113 if (r < 0)
5114 return r;
5115
ee5324aa 5116 (void) pager_open(arg_no_pager, false);
dbed408b 5117
f459b602
MAP
5118 c = (unsigned) r;
5119
5120 qsort_safe(unit_infos, c, sizeof(UnitInfo), compare_unit_info);
991f2a39 5121
265a7a2a 5122 for (u = unit_infos; u < unit_infos + c; u++) {
7fd1b19b 5123 _cleanup_free_ char *p = NULL;
265a7a2a 5124
265a7a2a
ZJS
5125 p = unit_dbus_path_from_name(u->id);
5126 if (!p)
5127 return log_oom();
5128
8559e61d 5129 r = show_one(bus, p, u->id, SYSTEMCTL_SHOW_STATUS, new_line, ellipsized);
3df538da 5130 if (r < 0)
265a7a2a 5131 return r;
5bb75bc7
ZJS
5132 else if (r > 0 && ret == 0)
5133 ret = r;
265a7a2a
ZJS
5134 }
5135
5bb75bc7 5136 return ret;
265a7a2a
ZJS
5137}
5138
8fcf784d
LP
5139static int show_system_status(sd_bus *bus) {
5140 char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
f9e0eefc 5141 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
e7e55dbd 5142 _cleanup_(machine_info_clear) struct machine_info mi = {};
f9e0eefc 5143 _cleanup_free_ char *hn = NULL;
8fcf784d
LP
5144 const char *on, *off;
5145 int r;
5146
5147 hn = gethostname_malloc();
5148 if (!hn)
5149 return log_oom();
5150
a7e4861c
YW
5151 r = bus_map_all_properties(
5152 bus,
5153 "org.freedesktop.systemd1",
5154 "/org/freedesktop/systemd1",
5155 machine_info_property_map,
5156 BUS_MAP_STRDUP,
5157 &error,
5158 NULL,
5159 &mi);
f647962d 5160 if (r < 0)
f9e0eefc 5161 return log_error_errno(r, "Failed to read server status: %s", bus_error_message(&error, r));
8fcf784d 5162
8fcf784d
LP
5163 if (streq_ptr(mi.state, "degraded")) {
5164 on = ansi_highlight_red();
1fc464f6 5165 off = ansi_normal();
92f34a9c
JR
5166 } else if (streq_ptr(mi.state, "running")) {
5167 on = ansi_highlight_green();
5168 off = ansi_normal();
5169 } else {
8fcf784d 5170 on = ansi_highlight_yellow();
1fc464f6 5171 off = ansi_normal();
92f34a9c 5172 }
8fcf784d 5173
323b7dc9 5174 printf("%s%s%s %s\n", on, special_glyph(BLACK_CIRCLE), off, arg_host ? arg_host : hn);
b0d14c69 5175
8fcf784d
LP
5176 printf(" State: %s%s%s\n",
5177 on, strna(mi.state), off);
5178
c6ba5b80
MP
5179 printf(" Jobs: %" PRIu32 " queued\n", mi.n_jobs);
5180 printf(" Failed: %" PRIu32 " units\n", mi.n_failed_units);
8fcf784d
LP
5181
5182 printf(" Since: %s; %s\n",
5183 format_timestamp(since2, sizeof(since2), mi.timestamp),
5184 format_timestamp_relative(since1, sizeof(since1), mi.timestamp));
5185
5186 printf(" CGroup: %s\n", mi.control_group ?: "/");
4c315c2c
IS
5187 if (IN_SET(arg_transport,
5188 BUS_TRANSPORT_LOCAL,
5189 BUS_TRANSPORT_MACHINE)) {
8fcf784d
LP
5190 static const char prefix[] = " ";
5191 unsigned c;
5192
5193 c = columns();
5194 if (c > sizeof(prefix) - 1)
5195 c -= sizeof(prefix) - 1;
5196 else
5197 c = 0;
5198
0ff308c8 5199 show_cgroup(SYSTEMD_CGROUP_CONTROLLER, strempty(mi.control_group), prefix, c, get_output_flags());
8fcf784d
LP
5200 }
5201
8fcf784d
LP
5202 return 0;
5203}
5204
e449de87 5205static int show(int argc, char *argv[], void *userdata) {
8559e61d
YW
5206 bool new_line = false, ellipsized = false;
5207 SystemctlShowMode show_mode;
e3e0314b 5208 int r, ret = 0;
4fbd7192 5209 sd_bus *bus;
48220598 5210
e449de87 5211 assert(argv);
48220598 5212
8559e61d
YW
5213 show_mode = systemctl_show_mode_from_string(argv[0]);
5214 if (show_mode < 0) {
5215 log_error("Invalid argument.");
5216 return -EINVAL;
5217 }
e449de87 5218
8559e61d 5219 if (show_mode == SYSTEMCTL_SHOW_HELP && argc <= 1) {
e449de87
LP
5220 log_error("This command expects one or more unit names. Did you mean --help?");
5221 return -EINVAL;
5222 }
61cbdc4b 5223
d2ad7e1b
ZJS
5224 r = acquire_bus(BUS_MANAGER, &bus);
5225 if (r < 0)
5226 return r;
5227
ee5324aa 5228 (void) pager_open(arg_no_pager, false);
ec14911e 5229
8559e61d 5230 if (show_mode == SYSTEMCTL_SHOW_STATUS)
40acc203
ZJS
5231 /* Increase max number of open files to 16K if we can, we
5232 * might needs this when browsing journal files, which might
5233 * be split up into many files. */
5234 setrlimit_closest(RLIMIT_NOFILE, &RLIMIT_MAKE_CONST(16384));
5235
4fbd7192 5236 /* If no argument is specified inspect the manager itself */
8559e61d
YW
5237 if (show_mode == SYSTEMCTL_SHOW_PROPERTIES && argc <= 1)
5238 return show_one(bus, "/org/freedesktop/systemd1", NULL, show_mode, &new_line, &ellipsized);
48220598 5239
8559e61d 5240 if (show_mode == SYSTEMCTL_SHOW_STATUS && argc <= 1) {
8fcf784d 5241
8fcf784d
LP
5242 show_system_status(bus);
5243 new_line = true;
5244
5245 if (arg_all)
8559e61d 5246 ret = show_all(bus, &new_line, &ellipsized);
8fcf784d 5247 } else {
e3e0314b
ZJS
5248 _cleanup_free_ char **patterns = NULL;
5249 char **name;
5250
e449de87 5251 STRV_FOREACH(name, strv_skip(argv, 1)) {
3dced37b 5252 _cleanup_free_ char *path = NULL, *unit = NULL;
94e0bd7d 5253 uint32_t id;
48220598 5254
94e0bd7d 5255 if (safe_atou32(*name, &id) < 0) {
e3e0314b 5256 if (strv_push(&patterns, *name) < 0)
94e0bd7d 5257 return log_oom();
48220598 5258
e3e0314b 5259 continue;
8559e61d 5260 } else if (show_mode == SYSTEMCTL_SHOW_PROPERTIES) {
94e0bd7d 5261 /* Interpret as job id */
3dced37b 5262 if (asprintf(&path, "/org/freedesktop/systemd1/job/%u", id) < 0)
94e0bd7d 5263 return log_oom();
48220598 5264
94e0bd7d
ZJS
5265 } else {
5266 /* Interpret as PID */
3dced37b 5267 r = get_unit_dbus_path_by_pid(bus, id, &path);
373d32c9 5268 if (r < 0) {
94e0bd7d 5269 ret = r;
373d32c9
LP
5270 continue;
5271 }
3dced37b
LP
5272
5273 r = unit_name_from_dbus_path(path, &unit);
5274 if (r < 0)
5275 return log_oom();
94e0bd7d 5276 }
f74294c1 5277
8559e61d 5278 r = show_one(bus, path, unit, show_mode, &new_line, &ellipsized);
5bb75bc7
ZJS
5279 if (r < 0)
5280 return r;
5281 else if (r > 0 && ret == 0)
5282 ret = r;
48220598 5283 }
94e0bd7d 5284
e3e0314b
ZJS
5285 if (!strv_isempty(patterns)) {
5286 _cleanup_strv_free_ char **names = NULL;
5287
5288 r = expand_names(bus, patterns, NULL, &names);
5289 if (r < 0)
691395d8 5290 return log_error_errno(r, "Failed to expand names: %m");
e3e0314b
ZJS
5291
5292 STRV_FOREACH(name, names) {
3dced37b 5293 _cleanup_free_ char *path;
e3e0314b 5294
3dced37b
LP
5295 path = unit_dbus_path_from_name(*name);
5296 if (!path)
e3e0314b
ZJS
5297 return log_oom();
5298
8559e61d 5299 r = show_one(bus, path, *name, show_mode, &new_line, &ellipsized);
5bb75bc7
ZJS
5300 if (r < 0)
5301 return r;
3dced37b 5302 if (r > 0 && ret == 0)
5bb75bc7 5303 ret = r;
e3e0314b
ZJS
5304 }
5305 }
5306 }
5307
94e0bd7d
ZJS
5308 if (ellipsized && !arg_quiet)
5309 printf("Hint: Some lines were ellipsized, use -l to show in full.\n");
48220598 5310
22f4096c 5311 return ret;
0183528f
LP
5312}
5313
e449de87 5314static int cat(int argc, char *argv[], void *userdata) {
8e766630 5315 _cleanup_(lookup_paths_free) LookupPaths lp = {};
15ef1144
LP
5316 _cleanup_strv_free_ char **names = NULL;
5317 char **name;
4fbd7192
LP
5318 sd_bus *bus;
5319 bool first = true;
25586912 5320 int r;
15ef1144 5321
3e7eed84 5322 if (arg_transport != BUS_TRANSPORT_LOCAL) {
4fbd7192 5323 log_error("Cannot remotely cat units.");
3e495a66
ZJS
5324 return -EINVAL;
5325 }
5326
4943d143 5327 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
ad2a0358 5328 if (r < 0)
c51932be 5329 return log_error_errno(r, "Failed to determine unit paths: %m");
ad2a0358 5330
4fbd7192 5331 r = acquire_bus(BUS_MANAGER, &bus);
15ef1144 5332 if (r < 0)
4fbd7192 5333 return r;
15ef1144 5334
e449de87 5335 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
4fbd7192
LP
5336 if (r < 0)
5337 return log_error_errno(r, "Failed to expand names: %m");
ad2a0358 5338
ee5324aa 5339 (void) pager_open(arg_no_pager, false);
15ef1144
LP
5340
5341 STRV_FOREACH(name, names) {
ad2a0358 5342 _cleanup_free_ char *fragment_path = NULL;
15ef1144 5343 _cleanup_strv_free_ char **dropin_paths = NULL;
15ef1144 5344
4fbd7192 5345 r = unit_find_paths(bus, *name, &lp, &fragment_path, &dropin_paths);
ad2a0358
ZJS
5346 if (r < 0)
5347 return r;
b5e6a600
IS
5348 else if (r == 0)
5349 return -ENOENT;
15ef1144
LP
5350
5351 if (first)
5352 first = false;
5353 else
5354 puts("");
5355
5b9635d1 5356 if (need_daemon_reload(bus, *name) > 0) /* ignore errors (<0), this is informational output */
e100155d
LW
5357 fprintf(stderr,
5358 "%s# Warning: %s changed on disk, the version systemd has loaded is outdated.\n"
5359 "%s# This output shows the current version of the unit's original fragment and drop-in files.\n"
5360 "%s# If fragments or drop-ins were added or removed, they are not properly reflected in this output.\n"
5361 "%s# Run 'systemctl%s daemon-reload' to reload units.%s\n",
5362 ansi_highlight_red(),
5363 *name,
5364 ansi_highlight_red(),
5365 ansi_highlight_red(),
5366 ansi_highlight_red(),
5367 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user",
5368 ansi_normal());
5369
854a42fb 5370 r = cat_files(fragment_path, dropin_paths, 0);
81f5e513
ZJS
5371 if (r < 0)
5372 return r;
15ef1144
LP
5373 }
5374
25586912 5375 return 0;
15ef1144
LP
5376}
5377
e449de87 5378static int set_property(int argc, char *argv[], void *userdata) {
4afd3348
LP
5379 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
5380 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
68372da6 5381 _cleanup_free_ char *n = NULL;
89ada3ba 5382 UnitType t;
4fbd7192 5383 sd_bus *bus;
8e2af478
LP
5384 int r;
5385
4fbd7192
LP
5386 r = acquire_bus(BUS_MANAGER, &bus);
5387 if (r < 0)
5388 return r;
5389
8a4b13c5 5390 polkit_agent_open_maybe();
d2ad7e1b 5391
f459b602
MAP
5392 r = sd_bus_message_new_method_call(
5393 bus,
151b9b96 5394 &m,
8e2af478
LP
5395 "org.freedesktop.systemd1",
5396 "/org/freedesktop/systemd1",
5397 "org.freedesktop.systemd1.Manager",
151b9b96 5398 "SetUnitProperties");
f459b602
MAP
5399 if (r < 0)
5400 return bus_log_create_error(r);
8e2af478 5401
37cbc1d5 5402 r = unit_name_mangle(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, &n);
7410616c
LP
5403 if (r < 0)
5404 return log_error_errno(r, "Failed to mangle unit name: %m");
68372da6 5405
89ada3ba
YW
5406 t = unit_name_to_type(n);
5407 if (t < 0) {
5408 log_error("Invalid unit type: %s", n);
5409 return -EINVAL;
5410 }
5411
f459b602
MAP
5412 r = sd_bus_message_append(m, "sb", n, arg_runtime);
5413 if (r < 0)
5414 return bus_log_create_error(r);
8e2af478 5415
f459b602
MAP
5416 r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, "(sv)");
5417 if (r < 0)
5418 return bus_log_create_error(r);
8e2af478 5419
89ada3ba 5420 r = bus_append_unit_property_assignment_many(m, t, strv_skip(argv, 2));
8673cf13
LP
5421 if (r < 0)
5422 return r;
8e2af478 5423
f459b602
MAP
5424 r = sd_bus_message_close_container(m);
5425 if (r < 0)
5426 return bus_log_create_error(r);
8e2af478 5427
c49b30a2 5428 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
5429 if (r < 0)
5430 return log_error_errno(r, "Failed to set unit properties on %s: %s", n, bus_error_message(&error, r));
8e2af478
LP
5431
5432 return 0;
5433}
5434
e449de87 5435static int daemon_reload(int argc, char *argv[], void *userdata) {
4afd3348 5436 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2853b60a 5437 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
7e4249b9 5438 const char *method;
4fbd7192 5439 sd_bus *bus;
f459b602 5440 int r;
7e4249b9 5441
4fbd7192
LP
5442 r = acquire_bus(BUS_MANAGER, &bus);
5443 if (r < 0)
5444 return r;
5445
8a4b13c5 5446 polkit_agent_open_maybe();
d2ad7e1b 5447
2853b60a
LP
5448 switch (arg_action) {
5449
5450 case ACTION_RELOAD:
e4b61340 5451 method = "Reload";
2853b60a
LP
5452 break;
5453
5454 case ACTION_REEXEC:
e4b61340 5455 method = "Reexecute";
2853b60a
LP
5456 break;
5457
5458 case ACTION_SYSTEMCTL:
5459 method = streq(argv[0], "daemon-reexec") ? "Reexecute" :
5460 /* "daemon-reload" */ "Reload";
5461 break;
e4b61340 5462
2853b60a
LP
5463 default:
5464 assert_not_reached("Unexpected action");
e4b61340 5465 }
7e4249b9 5466
2853b60a
LP
5467 r = sd_bus_message_new_method_call(
5468 bus,
5469 &m,
5470 "org.freedesktop.systemd1",
5471 "/org/freedesktop/systemd1",
5472 "org.freedesktop.systemd1.Manager",
5473 method);
5474 if (r < 0)
5475 return bus_log_create_error(r);
5476
5477 /* Note we use an extra-long timeout here. This is because a reload or reexec means generators are rerun which
5478 * are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can have
5479 * their timeout, and for everything else there's the same time budget in place. */
5480
5481 r = sd_bus_call(bus, m, DEFAULT_TIMEOUT_USEC * 2, &error, NULL);
5482
5483 /* On reexecution, we expect a disconnect, not a reply */
5484 if (IN_SET(r, -ETIMEDOUT, -ECONNRESET) && streq(method, "Reexecute"))
5485 r = 0;
5486
5487 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
5488 return log_error_errno(r, "Failed to reload daemon: %s", bus_error_message(&error, r));
5489
5490 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
5491 * old ways of doing things, hence don't log any error in that case here. */
5492
5493 return r < 0 ? r : 0;
5494}
5495
5496static int trivial_method(int argc, char *argv[], void *userdata) {
5497 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5498 const char *method;
5499 sd_bus *bus;
5500 int r;
5501
1ae17672
ZJS
5502 if (arg_dry_run)
5503 return 0;
5504
2853b60a
LP
5505 r = acquire_bus(BUS_MANAGER, &bus);
5506 if (r < 0)
5507 return r;
5508
8a4b13c5 5509 polkit_agent_open_maybe();
d2ad7e1b 5510
2853b60a
LP
5511 method =
5512 streq(argv[0], "clear-jobs") ||
5513 streq(argv[0], "cancel") ? "ClearJobs" :
5514 streq(argv[0], "reset-failed") ? "ResetFailed" :
5515 streq(argv[0], "halt") ? "Halt" :
5516 streq(argv[0], "reboot") ? "Reboot" :
5517 streq(argv[0], "kexec") ? "KExec" :
5518 streq(argv[0], "exit") ? "Exit" :
5519 /* poweroff */ "PowerOff";
5520
6e646d22 5521 r = sd_bus_call_method(
f22f08cd
SP
5522 bus,
5523 "org.freedesktop.systemd1",
5524 "/org/freedesktop/systemd1",
5525 "org.freedesktop.systemd1.Manager",
6e646d22
LP
5526 method,
5527 &error,
5528 NULL,
5529 NULL);
2853b60a
LP
5530 if (r < 0 && arg_action == ACTION_SYSTEMCTL)
5531 return log_error_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r));
5532
5533 /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support fallbacks to the
5534 * old ways of doing things, hence don't log any error in that case here. */
7e4249b9 5535
0a9776c2 5536 return r < 0 ? r : 0;
7e4249b9
LP
5537}
5538
e449de87 5539static int reset_failed(int argc, char *argv[], void *userdata) {
e3e0314b 5540 _cleanup_strv_free_ char **names = NULL;
4fbd7192 5541 sd_bus *bus;
f84190d8 5542 char **name;
e3e0314b 5543 int r, q;
5632e374 5544
e449de87 5545 if (argc <= 1)
2853b60a 5546 return trivial_method(argc, argv, userdata);
5632e374 5547
4fbd7192
LP
5548 r = acquire_bus(BUS_MANAGER, &bus);
5549 if (r < 0)
5550 return r;
5551
8a4b13c5 5552 polkit_agent_open_maybe();
d2ad7e1b 5553
e449de87 5554 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
e3e0314b 5555 if (r < 0)
691395d8 5556 return log_error_errno(r, "Failed to expand names: %m");
f84190d8 5557
e3e0314b 5558 STRV_FOREACH(name, names) {
4afd3348 5559 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
342641fb 5560
6e646d22 5561 q = sd_bus_call_method(
f22f08cd 5562 bus,
b0193f1c
LP
5563 "org.freedesktop.systemd1",
5564 "/org/freedesktop/systemd1",
5565 "org.freedesktop.systemd1.Manager",
6e646d22
LP
5566 "ResetFailedUnit",
5567 &error,
5568 NULL,
5569 "s", *name);
e3e0314b 5570 if (q < 0) {
691395d8 5571 log_error_errno(q, "Failed to reset failed state of unit %s: %s", *name, bus_error_message(&error, q));
e3e0314b
ZJS
5572 if (r == 0)
5573 r = q;
f459b602 5574 }
5632e374
LP
5575 }
5576
e3e0314b 5577 return r;
5632e374
LP
5578}
5579
804ee07c
ZJS
5580static int print_variable(const char *s) {
5581 const char *sep;
5582 _cleanup_free_ char *esc = NULL;
5583
5584 sep = strchr(s, '=');
5585 if (!sep) {
5586 log_error("Invalid environment block");
5587 return -EUCLEAN;
5588 }
5589
5590 esc = shell_maybe_quote(sep + 1, ESCAPE_POSIX);
5591 if (!esc)
5592 return log_oom();
5593
5594 printf("%.*s=%s\n", (int)(sep-s), s, esc);
5595 return 0;
5596}
5597
e449de87 5598static int show_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
5599 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5600 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
f459b602 5601 const char *text;
4fbd7192 5602 sd_bus *bus;
7e4249b9 5603 int r;
7e4249b9 5604
4fbd7192
LP
5605 r = acquire_bus(BUS_MANAGER, &bus);
5606 if (r < 0)
5607 return r;
5608
ee5324aa 5609 (void) pager_open(arg_no_pager, false);
d2ad7e1b 5610
f459b602 5611 r = sd_bus_get_property(
f22f08cd
SP
5612 bus,
5613 "org.freedesktop.systemd1",
5614 "/org/freedesktop/systemd1",
f459b602
MAP
5615 "org.freedesktop.systemd1.Manager",
5616 "Environment",
5617 &error,
f22f08cd 5618 &reply,
f459b602 5619 "as");
691395d8
LP
5620 if (r < 0)
5621 return log_error_errno(r, "Failed to get environment: %s", bus_error_message(&error, r));
7e4249b9 5622
f459b602
MAP
5623 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
5624 if (r < 0)
5625 return bus_log_parse_error(r);
7e4249b9 5626
804ee07c
ZJS
5627 while ((r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &text)) > 0) {
5628 r = print_variable(text);
5629 if (r < 0)
5630 return r;
5631 }
f459b602
MAP
5632 if (r < 0)
5633 return bus_log_parse_error(r);
7e4249b9 5634
f459b602
MAP
5635 r = sd_bus_message_exit_container(reply);
5636 if (r < 0)
5637 return bus_log_parse_error(r);
7e4249b9 5638
f84190d8 5639 return 0;
7e4249b9
LP
5640}
5641
e449de87 5642static int switch_root(int argc, char *argv[], void *userdata) {
4afd3348 5643 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f39d4a08
HH
5644 _cleanup_free_ char *cmdline_init = NULL;
5645 const char *root, *init;
4fbd7192 5646 sd_bus *bus;
f459b602 5647 int r;
957eb8ca 5648
4fbd7192
LP
5649 if (arg_transport != BUS_TRANSPORT_LOCAL) {
5650 log_error("Cannot switch root remotely.");
5651 return -EINVAL;
5652 }
5653
e449de87 5654 if (argc < 2 || argc > 3) {
957eb8ca
LP
5655 log_error("Wrong number of arguments.");
5656 return -EINVAL;
5657 }
5658
e449de87 5659 root = argv[1];
13068da8 5660
e449de87
LP
5661 if (argc >= 3)
5662 init = argv[2];
13068da8 5663 else {
1a5a177e 5664 r = parse_env_file(NULL, "/proc/cmdline", WHITESPACE,
f39d4a08
HH
5665 "init", &cmdline_init,
5666 NULL);
5667 if (r < 0)
da927ba9 5668 log_debug_errno(r, "Failed to parse /proc/cmdline: %m");
13068da8 5669
f39d4a08 5670 init = cmdline_init;
13068da8 5671 }
f459b602 5672
3c6f7c34 5673 init = empty_to_null(init);
f39d4a08
HH
5674 if (init) {
5675 const char *root_systemd_path = NULL, *root_init_path = NULL;
5676
63c372cb
LP
5677 root_systemd_path = strjoina(root, "/" SYSTEMD_BINARY_PATH);
5678 root_init_path = strjoina(root, "/", init);
f39d4a08
HH
5679
5680 /* If the passed init is actually the same as the
5681 * systemd binary, then let's suppress it. */
e3f791a2 5682 if (files_same(root_init_path, root_systemd_path, 0) > 0)
f39d4a08
HH
5683 init = NULL;
5684 }
13068da8 5685
acc28e2e 5686 /* Instruct PID1 to exclude us from its killing spree applied during
b3ad0ff4
ZJS
5687 * the transition. Otherwise we would exit with a failure status even
5688 * though the switch to the new root has succeed. */
5689 argv_cmdline[0] = '@';
acc28e2e 5690
4fbd7192
LP
5691 r = acquire_bus(BUS_MANAGER, &bus);
5692 if (r < 0)
5693 return r;
5694
8a7a9cea
ZJS
5695 /* If we are slow to exit after the root switch, the new systemd instance
5696 * will send us a signal to terminate. Just ignore it and exit normally.
5697 * This way the unit does not end up as failed.
5698 */
5699 r = ignore_signals(SIGTERM, -1);
5700 if (r < 0)
5701 log_warning_errno(r, "Failed to change disposition of SIGTERM to ignore: %m");
5702
f39d4a08 5703 log_debug("Switching root - root: %s; init: %s", root, strna(init));
957eb8ca 5704
f459b602 5705 r = sd_bus_call_method(
f22f08cd 5706 bus,
957eb8ca
LP
5707 "org.freedesktop.systemd1",
5708 "/org/freedesktop/systemd1",
5709 "org.freedesktop.systemd1.Manager",
f22f08cd 5710 "SwitchRoot",
f459b602 5711 &error,
f22f08cd 5712 NULL,
f459b602 5713 "ss", root, init);
8a7a9cea
ZJS
5714 if (r < 0) {
5715 (void) default_signals(SIGTERM, -1);
5716
691395d8 5717 return log_error_errno(r, "Failed to switch root: %s", bus_error_message(&error, r));
8a7a9cea 5718 }
f459b602
MAP
5719
5720 return 0;
957eb8ca
LP
5721}
5722
e449de87 5723static int set_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
5724 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5725 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
7e4249b9 5726 const char *method;
4fbd7192 5727 sd_bus *bus;
31e767f7
LP
5728 int r;
5729
e449de87
LP
5730 assert(argc > 1);
5731 assert(argv);
7e4249b9 5732
4fbd7192
LP
5733 r = acquire_bus(BUS_MANAGER, &bus);
5734 if (r < 0)
5735 return r;
5736
8a4b13c5 5737 polkit_agent_open_maybe();
d2ad7e1b 5738
e449de87 5739 method = streq(argv[0], "set-environment")
7e4249b9
LP
5740 ? "SetEnvironment"
5741 : "UnsetEnvironment";
5742
f459b602
MAP
5743 r = sd_bus_message_new_method_call(
5744 bus,
151b9b96 5745 &m,
31e767f7
LP
5746 "org.freedesktop.systemd1",
5747 "/org/freedesktop/systemd1",
5748 "org.freedesktop.systemd1.Manager",
151b9b96 5749 method);
f459b602
MAP
5750 if (r < 0)
5751 return bus_log_create_error(r);
7e4249b9 5752
e449de87 5753 r = sd_bus_message_append_strv(m, strv_skip(argv, 1));
31e767f7 5754 if (r < 0)
f459b602 5755 return bus_log_create_error(r);
7e4249b9 5756
c49b30a2 5757 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
5758 if (r < 0)
5759 return log_error_errno(r, "Failed to set environment: %s", bus_error_message(&error, r));
7e4249b9 5760
f84190d8 5761 return 0;
7e4249b9
LP
5762}
5763
e449de87 5764static int import_environment(int argc, char *argv[], void *userdata) {
4afd3348
LP
5765 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5766 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
4fbd7192 5767 sd_bus *bus;
ac3efa8a
LP
5768 int r;
5769
4fbd7192
LP
5770 r = acquire_bus(BUS_MANAGER, &bus);
5771 if (r < 0)
5772 return r;
5773
8a4b13c5 5774 polkit_agent_open_maybe();
d2ad7e1b 5775
ac3efa8a
LP
5776 r = sd_bus_message_new_method_call(
5777 bus,
151b9b96 5778 &m,
ac3efa8a
LP
5779 "org.freedesktop.systemd1",
5780 "/org/freedesktop/systemd1",
5781 "org.freedesktop.systemd1.Manager",
151b9b96 5782 "SetEnvironment");
ac3efa8a
LP
5783 if (r < 0)
5784 return bus_log_create_error(r);
5785
e449de87 5786 if (argc < 2)
ac3efa8a
LP
5787 r = sd_bus_message_append_strv(m, environ);
5788 else {
5789 char **a, **b;
5790
5791 r = sd_bus_message_open_container(m, 'a', "s");
5792 if (r < 0)
5793 return bus_log_create_error(r);
5794
e449de87 5795 STRV_FOREACH(a, strv_skip(argv, 1)) {
ac3efa8a
LP
5796
5797 if (!env_name_is_valid(*a)) {
5798 log_error("Not a valid environment variable name: %s", *a);
5799 return -EINVAL;
5800 }
5801
5802 STRV_FOREACH(b, environ) {
5803 const char *eq;
5804
5805 eq = startswith(*b, *a);
5806 if (eq && *eq == '=') {
5807
5808 r = sd_bus_message_append(m, "s", *b);
5809 if (r < 0)
5810 return bus_log_create_error(r);
5811
5812 break;
5813 }
5814 }
5815 }
5816
5817 r = sd_bus_message_close_container(m);
5818 }
5819 if (r < 0)
5820 return bus_log_create_error(r);
5821
5822 r = sd_bus_call(bus, m, 0, &error, NULL);
691395d8
LP
5823 if (r < 0)
5824 return log_error_errno(r, "Failed to import environment: %s", bus_error_message(&error, r));
ac3efa8a
LP
5825
5826 return 0;
5827}
5828
cbb13b2a 5829static int enable_sysv_units(const char *verb, char **args) {
729e3769 5830 int r = 0;
ee5762e3 5831
349cc4a5 5832#if HAVE_SYSV_COMPAT
8e766630 5833 _cleanup_(lookup_paths_free) LookupPaths paths = {};
e735decc
LP
5834 unsigned f = 0;
5835
5836 /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */
ee5762e3 5837
729e3769
LP
5838 if (arg_scope != UNIT_FILE_SYSTEM)
5839 return 0;
ee5762e3 5840
b41b9d2a
LP
5841 if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0)
5842 return 0;
5843
4c315c2c
IS
5844 if (!STR_IN_SET(verb,
5845 "enable",
5846 "disable",
5847 "is-enabled"))
729e3769 5848 return 0;
ee5762e3 5849
4943d143 5850 r = lookup_paths_init(&paths, arg_scope, LOOKUP_PATHS_EXCLUDE_GENERATED, arg_root);
729e3769
LP
5851 if (r < 0)
5852 return r;
ee5762e3 5853
729e3769 5854 r = 0;
a644abed 5855 while (args[f]) {
e735decc
LP
5856
5857 const char *argv[] = {
5858 ROOTLIBEXECDIR "/systemd-sysv-install",
5859 NULL,
5860 NULL,
5861 NULL,
5862 NULL,
5863 };
5864
05cae7f3 5865 _cleanup_free_ char *p = NULL, *q = NULL, *l = NULL;
729e3769 5866 bool found_native = false, found_sysv;
e735decc 5867 const char *name;
729e3769 5868 unsigned c = 1;
729e3769 5869 pid_t pid;
e735decc 5870 int j;
ee5762e3 5871
a644abed 5872 name = args[f++];
ee5762e3 5873
729e3769
LP
5874 if (!endswith(name, ".service"))
5875 continue;
ee5762e3 5876
729e3769
LP
5877 if (path_is_absolute(name))
5878 continue;
ee5762e3 5879
e735decc 5880 j = unit_file_exists(arg_scope, &paths, name);
76ec966f 5881 if (j < 0 && !IN_SET(j, -ELOOP, -ERFKILL, -EADDRNOTAVAIL))
e735decc 5882 return log_error_errno(j, "Failed to lookup unit file state: %m");
3c6d8e57 5883 found_native = j != 0;
ee5762e3 5884
e735decc
LP
5885 /* If we have both a native unit and a SysV script, enable/disable them both (below); for is-enabled,
5886 * prefer the native unit */
355ff449 5887 if (found_native && streq(verb, "is-enabled"))
729e3769 5888 continue;
ee5762e3 5889
0c6ea3a4
ZJS
5890 p = path_join(arg_root, SYSTEM_SYSVINIT_PATH, name);
5891 if (!p)
60731f32 5892 return log_oom();
ee5762e3 5893
fbd0b64f 5894 p[strlen(p) - STRLEN(".service")] = 0;
729e3769 5895 found_sysv = access(p, F_OK) >= 0;
4b6756a8 5896 if (!found_sysv)
729e3769 5897 continue;
71fad675 5898
689e4e6a
CR
5899 if (!arg_quiet) {
5900 if (found_native)
5901 log_info("Synchronizing state of %s with SysV service script with %s.", name, argv[0]);
5902 else
5903 log_info("%s is not a native service, redirecting to systemd-sysv-install.", name);
5904 }
ee5762e3 5905
729e3769
LP
5906 if (!isempty(arg_root))
5907 argv[c++] = q = strappend("--root=", arg_root);
ee5762e3 5908
0f0467e6 5909 argv[c++] = verb;
2b6bf07d 5910 argv[c++] = basename(p);
729e3769 5911 argv[c] = NULL;
ee5762e3 5912
729e3769 5913 l = strv_join((char**)argv, " ");
60731f32
ZJS
5914 if (!l)
5915 return log_oom();
ee5762e3 5916
8ecc68f4
LP
5917 if (!arg_quiet)
5918 log_info("Executing: %s", l);
ee5762e3 5919
d2e0ac3d 5920 j = safe_fork("(sysv-install)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
4c253ed1 5921 if (j < 0)
b6e1fff1 5922 return j;
4c253ed1 5923 if (j == 0) {
729e3769 5924 /* Child */
729e3769 5925 execv(argv[0], (char**) argv);
cc7cb0ca 5926 log_error_errno(errno, "Failed to execute %s: %m", argv[0]);
729e3769
LP
5927 _exit(EXIT_FAILURE);
5928 }
ee5762e3 5929
2e87a1fd 5930 j = wait_for_terminate_and_check("sysv-install", pid, WAIT_LOG_ABNORMAL);
d710aaf7 5931 if (j < 0)
2e87a1fd
LP
5932 return j;
5933 if (streq(verb, "is-enabled")) {
b4a34311 5934 if (j == EXIT_SUCCESS) {
2e87a1fd
LP
5935 if (!arg_quiet)
5936 puts("enabled");
5937 r = 1;
5938 } else {
5939 if (!arg_quiet)
5940 puts("disabled");
5941 }
ee5762e3 5942
b4a34311 5943 } else if (j != EXIT_SUCCESS)
2e87a1fd 5944 return -EBADE; /* We don't warn here, under the assumption the script already showed an explanation */
ee5762e3 5945
355ff449
MP
5946 if (found_native)
5947 continue;
5948
a644abed 5949 /* Remove this entry, so that we don't try enabling it as native unit */
aba84331
LP
5950 assert(f > 0);
5951 f--;
5952 assert(args[f] == name);
5953 strv_remove(args, name);
729e3769 5954 }
ee5762e3 5955
729e3769
LP
5956#endif
5957 return r;
5958}
ee5762e3 5959
37370d0c 5960static int mangle_names(char **original_names, char ***mangled_names) {
a33fdebb 5961 char **i, **l, **name;
7410616c 5962 int r;
37370d0c 5963
7410616c 5964 l = i = new(char*, strv_length(original_names) + 1);
a33fdebb 5965 if (!l)
37370d0c
VP
5966 return log_oom();
5967
37370d0c 5968 STRV_FOREACH(name, original_names) {
44386fc1
LN
5969
5970 /* When enabling units qualified path names are OK,
5971 * too, hence allow them explicitly. */
5972
7410616c 5973 if (is_path(*name)) {
44386fc1 5974 *i = strdup(*name);
7410616c
LP
5975 if (!*i) {
5976 strv_free(l);
5977 return log_oom();
5978 }
5979 } else {
37cbc1d5 5980 r = unit_name_mangle(*name, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, i);
7410616c 5981 if (r < 0) {
523f8cde 5982 *i = NULL;
7410616c
LP
5983 strv_free(l);
5984 return log_error_errno(r, "Failed to mangle unit name: %m");
5985 }
a33fdebb
LP
5986 }
5987
5988 i++;
37370d0c 5989 }
a33fdebb
LP
5990
5991 *i = NULL;
5992 *mangled_names = l;
37370d0c
VP
5993
5994 return 0;
5995}
5996
decd7982
JR
5997static int normalize_filenames(char **names) {
5998 char **u;
5999 int r;
6000
6001 STRV_FOREACH(u, names)
6002 if (!path_is_absolute(*u)) {
6003 char* normalized_path;
6004
6005 if (!isempty(arg_root)) {
6006 log_error("Non-absolute paths are not allowed when --root is used: %s", *u);
6007 return -EINVAL;
6008 }
6009
6010 if (!strchr(*u,'/')) {
6011 log_error("Link argument does contain at least one directory separator: %s", *u);
6012 return -EINVAL;
6013 }
6014
6015 r = path_make_absolute_cwd(*u, &normalized_path);
6016 if (r < 0)
6017 return r;
6018
6019 free_and_replace(*u, normalized_path);
6020 }
6021
6022 return 0;
6023}
6024
1d3c86c0
MS
6025static int normalize_names(char **names, bool warn_if_path) {
6026 char **u;
6027 bool was_path = false;
6028
6029 STRV_FOREACH(u, names) {
6030 int r;
6031
6032 if (!is_path(*u))
6033 continue;
6034
6035 r = free_and_strdup(u, basename(*u));
6036 if (r < 0)
6037 return log_error_errno(r, "Failed to normalize unit file path: %m");
6038
6039 was_path = true;
6040 }
6041
6042 if (warn_if_path && was_path)
6043 log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name.");
6044
6045 return 0;
6046}
6047
173471b7 6048static int unit_exists(LookupPaths *lp, const char *unit) {
d6568222 6049 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f37f8a61 6050 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
d6568222
SS
6051 _cleanup_free_ char *path = NULL;
6052 static const struct bus_properties_map property_map[] = {
f37f8a61
YW
6053 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
6054 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state)},
d6568222
SS
6055 {},
6056 };
6057 UnitStatusInfo info = {};
6058 sd_bus *bus;
6059 int r;
6060
173471b7
ZJS
6061 if (unit_name_is_valid(unit, UNIT_NAME_TEMPLATE))
6062 return unit_find_template_path(unit, lp, NULL, NULL);
6063
d6568222
SS
6064 path = unit_dbus_path_from_name(unit);
6065 if (!path)
6066 return log_oom();
6067
6068 r = acquire_bus(BUS_MANAGER, &bus);
6069 if (r < 0)
6070 return r;
6071
a7e4861c 6072 r = bus_map_all_properties(bus, "org.freedesktop.systemd1", path, property_map, 0, &error, &m, &info);
d6568222
SS
6073 if (r < 0)
6074 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
6075
d6568222
SS
6076 return !streq_ptr(info.load_state, "not-found") || !streq_ptr(info.active_state, "inactive");
6077}
6078
e449de87 6079static int enable_unit(int argc, char *argv[], void *userdata) {
e3e0314b 6080 _cleanup_strv_free_ char **names = NULL;
e449de87 6081 const char *verb = argv[0];
729e3769 6082 UnitFileChange *changes = NULL;
da6053d0 6083 size_t n_changes = 0;
729e3769 6084 int carries_install_info = -1;
35b132e8 6085 bool ignore_carries_install_info = arg_quiet;
729e3769 6086 int r;
ee5762e3 6087
e449de87 6088 if (!argv[1])
ab5919fa
MS
6089 return 0;
6090
e449de87 6091 r = mangle_names(strv_skip(argv, 1), &names);
3a05c0f9 6092 if (r < 0)
cbb13b2a
VP
6093 return r;
6094
e3e0314b 6095 r = enable_sysv_units(verb, names);
cbb13b2a
VP
6096 if (r < 0)
6097 return r;
3a05c0f9 6098
c61b443d 6099 /* If the operation was fully executed by the SysV compat, let's finish early */
823e5fab
FB
6100 if (strv_isempty(names)) {
6101 if (arg_no_reload || install_client_side())
6102 return 0;
6103 return daemon_reload(argc, argv, userdata);
6104 }
67d66210 6105
1d3c86c0
MS
6106 if (streq(verb, "disable")) {
6107 r = normalize_names(names, true);
6108 if (r < 0)
6109 return r;
6110 }
6111
decd7982
JR
6112 if (streq(verb, "link")) {
6113 r = normalize_filenames(names);
6114 if (r < 0)
6115 return r;
6116 }
6117
4fbd7192 6118 if (install_client_side()) {
b3796dd8
JS
6119 UnitFileFlags flags;
6120
6121 flags = args_to_flags();
729e3769 6122 if (streq(verb, "enable")) {
b3796dd8 6123 r = unit_file_enable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769
LP
6124 carries_install_info = r;
6125 } else if (streq(verb, "disable"))
b3796dd8 6126 r = unit_file_disable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6127 else if (streq(verb, "reenable")) {
b3796dd8 6128 r = unit_file_reenable(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769
LP
6129 carries_install_info = r;
6130 } else if (streq(verb, "link"))
b3796dd8 6131 r = unit_file_link(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6132 else if (streq(verb, "preset")) {
b3796dd8 6133 r = unit_file_preset(arg_scope, flags, arg_root, names, arg_preset_mode, &changes, &n_changes);
729e3769 6134 } else if (streq(verb, "mask"))
b3796dd8 6135 r = unit_file_mask(arg_scope, flags, arg_root, names, &changes, &n_changes);
729e3769 6136 else if (streq(verb, "unmask"))
b3796dd8 6137 r = unit_file_unmask(arg_scope, flags, arg_root, names, &changes, &n_changes);
344ca755
LP
6138 else if (streq(verb, "revert"))
6139 r = unit_file_revert(arg_scope, arg_root, names, &changes, &n_changes);
729e3769
LP
6140 else
6141 assert_not_reached("Unknown verb");
ee5762e3 6142
af3d8113 6143 unit_file_dump_changes(r, verb, changes, n_changes, arg_quiet);
d073dea0 6144 if (r < 0)
85b78539 6145 goto finish;
df77cdf0 6146 r = 0;
729e3769 6147 } else {
4afd3348
LP
6148 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6149 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
39207373 6150 bool expect_carries_install_info = false;
344ca755 6151 bool send_runtime = true, send_force = true, send_preset_mode = false;
718db961 6152 const char *method;
4fbd7192 6153 sd_bus *bus;
729e3769 6154
d6568222 6155 if (STR_IN_SET(verb, "mask", "unmask")) {
f8d6cb48 6156 char **name;
8e766630 6157 _cleanup_(lookup_paths_free) LookupPaths lp = {};
173471b7
ZJS
6158
6159 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
d6568222
SS
6160 if (r < 0)
6161 return r;
f8d6cb48
ZJS
6162
6163 STRV_FOREACH(name, names) {
173471b7 6164 r = unit_exists(&lp, *name);
f8d6cb48
ZJS
6165 if (r < 0)
6166 return r;
6167 if (r == 0)
6168 log_notice("Unit %s does not exist, proceeding anyway.", *names);
6169 }
d6568222
SS
6170 }
6171
4fbd7192
LP
6172 r = acquire_bus(BUS_MANAGER, &bus);
6173 if (r < 0)
6174 return r;
6175
8a4b13c5 6176 polkit_agent_open_maybe();
d2ad7e1b 6177
729e3769
LP
6178 if (streq(verb, "enable")) {
6179 method = "EnableUnitFiles";
6180 expect_carries_install_info = true;
6181 } else if (streq(verb, "disable")) {
6182 method = "DisableUnitFiles";
6183 send_force = false;
6184 } else if (streq(verb, "reenable")) {
6185 method = "ReenableUnitFiles";
6186 expect_carries_install_info = true;
6187 } else if (streq(verb, "link"))
6188 method = "LinkUnitFiles";
6189 else if (streq(verb, "preset")) {
d309c1c3
LP
6190
6191 if (arg_preset_mode != UNIT_FILE_PRESET_FULL) {
6192 method = "PresetUnitFilesWithMode";
6193 send_preset_mode = true;
6194 } else
6195 method = "PresetUnitFiles";
6196
729e3769 6197 expect_carries_install_info = true;
39207373 6198 ignore_carries_install_info = true;
729e3769
LP
6199 } else if (streq(verb, "mask"))
6200 method = "MaskUnitFiles";
6201 else if (streq(verb, "unmask")) {
6202 method = "UnmaskUnitFiles";
6203 send_force = false;
344ca755
LP
6204 } else if (streq(verb, "revert")) {
6205 method = "RevertUnitFiles";
6206 send_runtime = send_force = false;
729e3769
LP
6207 } else
6208 assert_not_reached("Unknown verb");
6209
f459b602
MAP
6210 r = sd_bus_message_new_method_call(
6211 bus,
151b9b96 6212 &m,
729e3769
LP
6213 "org.freedesktop.systemd1",
6214 "/org/freedesktop/systemd1",
6215 "org.freedesktop.systemd1.Manager",
151b9b96 6216 method);
f459b602
MAP
6217 if (r < 0)
6218 return bus_log_create_error(r);
ee5762e3 6219
e3e0314b 6220 r = sd_bus_message_append_strv(m, names);
f459b602
MAP
6221 if (r < 0)
6222 return bus_log_create_error(r);
ee5762e3 6223
d309c1c3
LP
6224 if (send_preset_mode) {
6225 r = sd_bus_message_append(m, "s", unit_file_preset_mode_to_string(arg_preset_mode));
6226 if (r < 0)
6227 return bus_log_create_error(r);
6228 }
6229
344ca755
LP
6230 if (send_runtime) {
6231 r = sd_bus_message_append(m, "b", arg_runtime);
6232 if (r < 0)
6233 return bus_log_create_error(r);
6234 }
ee5762e3 6235
729e3769 6236 if (send_force) {
f459b602
MAP
6237 r = sd_bus_message_append(m, "b", arg_force);
6238 if (r < 0)
6239 return bus_log_create_error(r);
ee5762e3
LP
6240 }
6241
c49b30a2 6242 r = sd_bus_call(bus, m, 0, &error, &reply);
691395d8 6243 if (r < 0)
af3d8113 6244 return log_error_errno(r, "Failed to %s unit: %s", verb, bus_error_message(&error, r));
be394c48 6245
729e3769 6246 if (expect_carries_install_info) {
f459b602
MAP
6247 r = sd_bus_message_read(reply, "b", &carries_install_info);
6248 if (r < 0)
6249 return bus_log_parse_error(r);
ee5762e3
LP
6250 }
6251
57ab2eab 6252 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
f459b602 6253 if (r < 0)
85b78539 6254 goto finish;
b77398f7 6255
93c941e3 6256 /* Try to reload if enabled */
d6cb60c7 6257 if (!arg_no_reload)
e449de87 6258 r = daemon_reload(argc, argv, userdata);
f459b602
MAP
6259 else
6260 r = 0;
b647f10d 6261 }
3d3961f2 6262
39207373 6263 if (carries_install_info == 0 && !ignore_carries_install_info)
fe4aede9
ZJS
6264 log_warning("The unit files have no installation config (WantedBy, RequiredBy, Also, Alias\n"
6265 "settings in the [Install] section, and DefaultInstance for template units).\n"
6266 "This means they are not meant to be enabled using systemctl.\n"
416389f7
LP
6267 "Possible reasons for having this kind of units are:\n"
6268 "1) A unit may be statically enabled by being symlinked from another unit's\n"
6269 " .wants/ or .requires/ directory.\n"
6270 "2) A unit's purpose may be to act as a helper for some other unit which has\n"
6271 " a requirement dependency on it.\n"
6272 "3) A unit may be started when needed via activation (socket, path, timer,\n"
fe4aede9
ZJS
6273 " D-Bus, udev, scripted systemctl call, ...).\n"
6274 "4) In case of template units, the unit is meant to be enabled with some\n"
6275 " instance name specified.");
ee5762e3 6276
6bc30691 6277 if (arg_now && STR_IN_SET(argv[0], "enable", "disable", "mask")) {
4fbd7192 6278 sd_bus *bus;
da6053d0 6279 size_t len, i;
57ab2eab 6280
4fbd7192
LP
6281 r = acquire_bus(BUS_MANAGER, &bus);
6282 if (r < 0)
d073dea0 6283 goto finish;
4fbd7192 6284
6bc30691
JS
6285 len = strv_length(names);
6286 {
6287 char *new_args[len + 2];
57ab2eab 6288
6bc30691
JS
6289 new_args[0] = (char*) (streq(argv[0], "enable") ? "start" : "stop");
6290 for (i = 0; i < len; i++)
6291 new_args[i + 1] = basename(names[i]);
6292 new_args[i + 1] = NULL;
6293
6294 r = start_unit(len + 1, new_args, userdata);
6295 }
57ab2eab
JS
6296 }
6297
729e3769 6298finish:
729e3769 6299 unit_file_changes_free(changes, n_changes);
ee5762e3 6300
729e3769 6301 return r;
ee5762e3
LP
6302}
6303
e449de87 6304static int add_dependency(int argc, char *argv[], void *userdata) {
e94937df
LN
6305 _cleanup_strv_free_ char **names = NULL;
6306 _cleanup_free_ char *target = NULL;
e449de87 6307 const char *verb = argv[0];
acc0269c 6308 UnitFileChange *changes = NULL;
da6053d0 6309 size_t n_changes = 0;
e94937df
LN
6310 UnitDependency dep;
6311 int r = 0;
6312
e449de87 6313 if (!argv[1])
e94937df
LN
6314 return 0;
6315
37cbc1d5 6316 r = unit_name_mangle_with_suffix(argv[1], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".target", &target);
7410616c
LP
6317 if (r < 0)
6318 return log_error_errno(r, "Failed to mangle unit name: %m");
e94937df 6319
e449de87 6320 r = mangle_names(strv_skip(argv, 2), &names);
e94937df
LN
6321 if (r < 0)
6322 return r;
6323
6324 if (streq(verb, "add-wants"))
6325 dep = UNIT_WANTS;
6326 else if (streq(verb, "add-requires"))
6327 dep = UNIT_REQUIRES;
6328 else
6329 assert_not_reached("Unknown verb");
6330
4fbd7192 6331 if (install_client_side()) {
b3796dd8 6332 r = unit_file_add_dependency(arg_scope, args_to_flags(), arg_root, names, target, dep, &changes, &n_changes);
af3d8113 6333 unit_file_dump_changes(r, "add dependency on", changes, n_changes, arg_quiet);
5f056378
CH
6334
6335 if (r > 0)
6336 r = 0;
e94937df 6337 } else {
4afd3348
LP
6338 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL;
6339 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 6340 sd_bus *bus;
e94937df 6341
4fbd7192
LP
6342 r = acquire_bus(BUS_MANAGER, &bus);
6343 if (r < 0)
6344 return r;
6345
8a4b13c5 6346 polkit_agent_open_maybe();
d2ad7e1b 6347
e94937df
LN
6348 r = sd_bus_message_new_method_call(
6349 bus,
6350 &m,
6351 "org.freedesktop.systemd1",
6352 "/org/freedesktop/systemd1",
6353 "org.freedesktop.systemd1.Manager",
6354 "AddDependencyUnitFiles");
6355 if (r < 0)
6356 return bus_log_create_error(r);
6357
342641fb 6358 r = sd_bus_message_append_strv(m, names);
e94937df
LN
6359 if (r < 0)
6360 return bus_log_create_error(r);
6361
342641fb 6362 r = sd_bus_message_append(m, "ssbb", target, unit_dependency_to_string(dep), arg_runtime, arg_force);
e94937df
LN
6363 if (r < 0)
6364 return bus_log_create_error(r);
6365
6366 r = sd_bus_call(bus, m, 0, &error, &reply);
691395d8 6367 if (r < 0)
af3d8113 6368 return log_error_errno(r, "Failed to add dependency: %s", bus_error_message(&error, r));
e94937df 6369
acc0269c 6370 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
e94937df 6371 if (r < 0)
acc0269c 6372 goto finish;
e94937df 6373
acc0269c
CH
6374 if (arg_no_reload) {
6375 r = 0;
6376 goto finish;
6377 }
6378
6379 r = daemon_reload(argc, argv, userdata);
e94937df 6380 }
acc0269c
CH
6381
6382finish:
6383 unit_file_changes_free(changes, n_changes);
6384
6385 return r;
e94937df
LN
6386}
6387
e449de87 6388static int preset_all(int argc, char *argv[], void *userdata) {
acc0269c 6389 UnitFileChange *changes = NULL;
da6053d0 6390 size_t n_changes = 0;
d309c1c3
LP
6391 int r;
6392
4fbd7192 6393 if (install_client_side()) {
b3796dd8 6394 r = unit_file_preset_all(arg_scope, args_to_flags(), arg_root, arg_preset_mode, &changes, &n_changes);
af3d8113 6395 unit_file_dump_changes(r, "preset", changes, n_changes, arg_quiet);
5f056378
CH
6396
6397 if (r > 0)
6398 r = 0;
d309c1c3 6399 } else {
4afd3348
LP
6400 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6401 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4fbd7192 6402 sd_bus *bus;
d309c1c3 6403
4fbd7192
LP
6404 r = acquire_bus(BUS_MANAGER, &bus);
6405 if (r < 0)
6406 return r;
6407
8a4b13c5 6408 polkit_agent_open_maybe();
d2ad7e1b 6409
6e646d22 6410 r = sd_bus_call_method(
d309c1c3
LP
6411 bus,
6412 "org.freedesktop.systemd1",
6413 "/org/freedesktop/systemd1",
6414 "org.freedesktop.systemd1.Manager",
6e646d22
LP
6415 "PresetAllUnitFiles",
6416 &error,
6417 &reply,
d309c1c3
LP
6418 "sbb",
6419 unit_file_preset_mode_to_string(arg_preset_mode),
6420 arg_runtime,
6421 arg_force);
691395d8 6422 if (r < 0)
af3d8113 6423 return log_error_errno(r, "Failed to preset all units: %s", bus_error_message(&error, r));
d309c1c3 6424
acc0269c 6425 r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet, &changes, &n_changes);
d309c1c3 6426 if (r < 0)
acc0269c 6427 goto finish;
d309c1c3 6428
acc0269c
CH
6429 if (arg_no_reload) {
6430 r = 0;
6431 goto finish;
6432 }
6433
6434 r = daemon_reload(argc, argv, userdata);
d309c1c3 6435 }
acc0269c
CH
6436
6437finish:
6438 unit_file_changes_free(changes, n_changes);
6439
6440 return r;
d309c1c3
LP
6441}
6442
3b3557c4
JS
6443static int show_installation_targets_client_side(const char *name) {
6444 UnitFileChange *changes = NULL;
da6053d0 6445 size_t n_changes = 0, i;
3b3557c4
JS
6446 UnitFileFlags flags;
6447 char **p;
6448 int r;
6449
6450 p = STRV_MAKE(name);
6451 flags = UNIT_FILE_DRY_RUN |
6452 (arg_runtime ? UNIT_FILE_RUNTIME : 0);
6453
6454 r = unit_file_disable(UNIT_FILE_SYSTEM, flags, NULL, p, &changes, &n_changes);
6455 if (r < 0)
6456 return log_error_errno(r, "Failed to get file links for %s: %m", name);
6457
6458 for (i = 0; i < n_changes; i++)
6459 if (changes[i].type == UNIT_FILE_UNLINK)
6460 printf(" %s\n", changes[i].path);
6461
6462 return 0;
6463}
6464
6465static int show_installation_targets(sd_bus *bus, const char *name) {
6466 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
6467 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6468 const char *link;
6469 int r;
6470
6471 r = sd_bus_call_method(
6472 bus,
6473 "org.freedesktop.systemd1",
6474 "/org/freedesktop/systemd1",
6475 "org.freedesktop.systemd1.Manager",
6476 "GetUnitFileLinks",
6477 &error,
6478 &reply,
6479 "sb", name, arg_runtime);
6480 if (r < 0)
6481 return log_error_errno(r, "Failed to get unit file links for %s: %s", name, bus_error_message(&error, r));
6482
6483 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s");
6484 if (r < 0)
6485 return bus_log_parse_error(r);
6486
6487 while ((r = sd_bus_message_read(reply, "s", &link)) > 0)
6488 printf(" %s\n", link);
6489
6490 if (r < 0)
6491 return bus_log_parse_error(r);
6492
6493 r = sd_bus_message_exit_container(reply);
6494 if (r < 0)
6495 return bus_log_parse_error(r);
6496
6497 return 0;
6498}
6499
e449de87 6500static int unit_is_enabled(int argc, char *argv[], void *userdata) {
e3e0314b 6501 _cleanup_strv_free_ char **names = NULL;
729e3769
LP
6502 bool enabled;
6503 char **name;
f459b602 6504 int r;
ee5762e3 6505
e449de87 6506 r = mangle_names(strv_skip(argv, 1), &names);
cbb13b2a
VP
6507 if (r < 0)
6508 return r;
6509
e449de87 6510 r = enable_sysv_units(argv[0], names);
729e3769
LP
6511 if (r < 0)
6512 return r;
ee5762e3 6513
729e3769 6514 enabled = r > 0;
ee5762e3 6515
4fbd7192 6516 if (install_client_side()) {
e3e0314b 6517 STRV_FOREACH(name, names) {
729e3769 6518 UnitFileState state;
ee5762e3 6519
0ec0deaa
LP
6520 r = unit_file_get_state(arg_scope, arg_root, *name, &state);
6521 if (r < 0)
c5024cd0 6522 return log_error_errno(r, "Failed to get unit file state for %s: %m", *name);
ee5762e3 6523
4c315c2c
IS
6524 if (IN_SET(state,
6525 UNIT_FILE_ENABLED,
6526 UNIT_FILE_ENABLED_RUNTIME,
6527 UNIT_FILE_STATIC,
f4139308
LP
6528 UNIT_FILE_INDIRECT,
6529 UNIT_FILE_GENERATED))
729e3769
LP
6530 enabled = true;
6531
3b3557c4 6532 if (!arg_quiet) {
729e3769 6533 puts(unit_file_state_to_string(state));
3b3557c4
JS
6534 if (arg_full) {
6535 r = show_installation_targets_client_side(*name);
6536 if (r < 0)
6537 return r;
6538 }
6539 }
71fad675 6540 }
ee5762e3 6541
5f056378 6542 r = 0;
729e3769 6543 } else {
4afd3348 6544 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192
LP
6545 sd_bus *bus;
6546
6547 r = acquire_bus(BUS_MANAGER, &bus);
6548 if (r < 0)
6549 return r;
6550
e3e0314b 6551 STRV_FOREACH(name, names) {
4afd3348 6552 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
729e3769 6553 const char *s;
63a723f3 6554
f459b602 6555 r = sd_bus_call_method(
f22f08cd 6556 bus,
729e3769
LP
6557 "org.freedesktop.systemd1",
6558 "/org/freedesktop/systemd1",
6559 "org.freedesktop.systemd1.Manager",
f22f08cd 6560 "GetUnitFileState",
f459b602 6561 &error,
f22f08cd 6562 &reply,
04504f93 6563 "s", *name);
691395d8
LP
6564 if (r < 0)
6565 return log_error_errno(r, "Failed to get unit file state for %s: %s", *name, bus_error_message(&error, r));
ee5762e3 6566
f459b602
MAP
6567 r = sd_bus_message_read(reply, "s", &s);
6568 if (r < 0)
6569 return bus_log_parse_error(r);
ee5762e3 6570
f4139308 6571 if (STR_IN_SET(s, "enabled", "enabled-runtime", "static", "indirect", "generated"))
729e3769
LP
6572 enabled = true;
6573
3b3557c4 6574 if (!arg_quiet) {
729e3769 6575 puts(s);
3b3557c4
JS
6576 if (arg_full) {
6577 r = show_installation_targets(bus, *name);
6578 if (r < 0)
6579 return r;
6580 }
6581 }
560d8f23 6582 }
ee5762e3
LP
6583 }
6584
f4139308 6585 return enabled ? EXIT_SUCCESS : EXIT_FAILURE;
ee5762e3
LP
6586}
6587
e449de87 6588static int is_system_running(int argc, char *argv[], void *userdata) {
99813a19 6589 _cleanup_free_ char *state = NULL;
4fbd7192 6590 sd_bus *bus;
99813a19
LP
6591 int r;
6592
040524b4 6593 if (running_in_chroot() > 0 || (arg_transport == BUS_TRANSPORT_LOCAL && !sd_booted())) {
94f099d8
LP
6594 if (!arg_quiet)
6595 puts("offline");
6596 return EXIT_FAILURE;
6597 }
6598
4fbd7192
LP
6599 r = acquire_bus(BUS_MANAGER, &bus);
6600 if (r < 0)
6601 return r;
6602
99813a19
LP
6603 r = sd_bus_get_property_string(
6604 bus,
6605 "org.freedesktop.systemd1",
6606 "/org/freedesktop/systemd1",
6607 "org.freedesktop.systemd1.Manager",
6608 "SystemState",
6609 NULL,
6610 &state);
6611 if (r < 0) {
6612 if (!arg_quiet)
6613 puts("unknown");
6614 return 0;
6615 }
6616
6617 if (!arg_quiet)
6618 puts(state);
6619
6620 return streq(state, "running") ? EXIT_SUCCESS : EXIT_FAILURE;
6621}
6622
7d4fb3b1 6623static int create_edit_temp_file(const char *new_path, const char *original_path, char **ret_tmp_fn) {
45519fd6 6624 _cleanup_free_ char *t = NULL;
ae6c3cc0 6625 int r;
7d4fb3b1
RC
6626
6627 assert(new_path);
6628 assert(original_path);
6629 assert(ret_tmp_fn);
6630
14bcf25c 6631 r = tempfn_random(new_path, NULL, &t);
ae6c3cc0 6632 if (r < 0)
029009d4 6633 return log_error_errno(r, "Failed to determine temporary filename for \"%s\": %m", new_path);
7d4fb3b1
RC
6634
6635 r = mkdir_parents(new_path, 0755);
45519fd6 6636 if (r < 0)
691395d8 6637 return log_error_errno(r, "Failed to create directories for \"%s\": %m", new_path);
7d4fb3b1 6638
1c876927 6639 r = copy_file(original_path, t, 0, 0644, 0, COPY_REFLINK);
7d4fb3b1 6640 if (r == -ENOENT) {
45519fd6 6641
7d4fb3b1 6642 r = touch(t);
45519fd6
LP
6643 if (r < 0)
6644 return log_error_errno(r, "Failed to create temporary file \"%s\": %m", t);
6645
6646 } else if (r < 0)
39c38ce1 6647 return log_error_errno(r, "Failed to create temporary file for \"%s\": %m", new_path);
7d4fb3b1 6648
ae2a15bc 6649 *ret_tmp_fn = TAKE_PTR(t);
7d4fb3b1
RC
6650
6651 return 0;
6652}
6653
c51932be
LP
6654static int get_file_to_edit(
6655 const LookupPaths *paths,
6656 const char *name,
6657 char **ret_path) {
6658
6659 _cleanup_free_ char *path = NULL, *run = NULL;
7d4fb3b1 6660
45519fd6
LP
6661 assert(name);
6662 assert(ret_path);
6663
605405c6 6664 path = strjoin(paths->persistent_config, "/", name);
c51932be 6665 if (!path)
7d4fb3b1
RC
6666 return log_oom();
6667
c51932be 6668 if (arg_runtime) {
605405c6 6669 run = strjoin(paths->runtime_config, "/", name);
c51932be
LP
6670 if (!run)
6671 return log_oom();
6672 }
6673
bc854dc7 6674 if (arg_runtime) {
691395d8
LP
6675 if (access(path, F_OK) >= 0) {
6676 log_error("Refusing to create \"%s\" because it would be overridden by \"%s\" anyway.", run, path);
6677 return -EEXIST;
6678 }
6679
ae2a15bc
LP
6680 *ret_path = TAKE_PTR(run);
6681 } else
6682 *ret_path = TAKE_PTR(path);
7d4fb3b1
RC
6683
6684 return 0;
6685}
6686
39c38ce1 6687static int unit_file_create_new(
c51932be
LP
6688 const LookupPaths *paths,
6689 const char *unit_name,
39c38ce1 6690 const char *suffix,
c51932be
LP
6691 char **ret_new_path,
6692 char **ret_tmp_path) {
6693
45519fd6 6694 char *tmp_new_path, *tmp_tmp_path, *ending;
7d4fb3b1
RC
6695 int r;
6696
6697 assert(unit_name);
6698 assert(ret_new_path);
6699 assert(ret_tmp_path);
6700
39c38ce1 6701 ending = strjoina(unit_name, suffix);
c51932be 6702 r = get_file_to_edit(paths, ending, &tmp_new_path);
7d4fb3b1
RC
6703 if (r < 0)
6704 return r;
6705
6706 r = create_edit_temp_file(tmp_new_path, tmp_new_path, &tmp_tmp_path);
6707 if (r < 0) {
6708 free(tmp_new_path);
6709 return r;
6710 }
6711
6712 *ret_new_path = tmp_new_path;
6713 *ret_tmp_path = tmp_tmp_path;
6714
6715 return 0;
6716}
6717
1cfa9a4c 6718static int unit_file_create_copy(
c51932be 6719 const LookupPaths *paths,
1cfa9a4c
LP
6720 const char *unit_name,
6721 const char *fragment_path,
1cfa9a4c
LP
6722 char **ret_new_path,
6723 char **ret_tmp_path) {
6724
45519fd6 6725 char *tmp_new_path, *tmp_tmp_path;
7d4fb3b1
RC
6726 int r;
6727
6728 assert(fragment_path);
6729 assert(unit_name);
6730 assert(ret_new_path);
6731 assert(ret_tmp_path);
6732
c51932be 6733 r = get_file_to_edit(paths, unit_name, &tmp_new_path);
7d4fb3b1
RC
6734 if (r < 0)
6735 return r;
6736
6737 if (!path_equal(fragment_path, tmp_new_path) && access(tmp_new_path, F_OK) == 0) {
6738 char response;
6739
029009d4 6740 r = ask_char(&response, "yn", "\"%s\" already exists. Overwrite with \"%s\"? [(y)es, (n)o] ", tmp_new_path, fragment_path);
7d4fb3b1
RC
6741 if (r < 0) {
6742 free(tmp_new_path);
6743 return r;
6744 }
6745 if (response != 'y') {
6746 log_warning("%s ignored", unit_name);
6747 free(tmp_new_path);
dbf43a1b 6748 return -EKEYREJECTED;
7d4fb3b1
RC
6749 }
6750 }
6751
6752 r = create_edit_temp_file(tmp_new_path, fragment_path, &tmp_tmp_path);
6753 if (r < 0) {
7d4fb3b1
RC
6754 free(tmp_new_path);
6755 return r;
6756 }
6757
6758 *ret_new_path = tmp_new_path;
6759 *ret_tmp_path = tmp_tmp_path;
6760
6761 return 0;
6762}
6763
6764static int run_editor(char **paths) {
7d4fb3b1
RC
6765 int r;
6766
6767 assert(paths);
6768
1f5d1e02 6769 r = safe_fork("(editor)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT, NULL);
4c253ed1 6770 if (r < 0)
b6e1fff1 6771 return r;
4c253ed1 6772 if (r == 0) {
7d4fb3b1 6773 const char **args;
9ef5d8f2 6774 char *editor, **editor_args = NULL;
1cfa9a4c 6775 char **tmp_path, **original_path, *p;
da6053d0 6776 size_t n_editor_args = 0, i = 1;
7d4fb3b1
RC
6777 size_t argc;
6778
6779 argc = strv_length(paths)/2 + 1;
7d4fb3b1
RC
6780
6781 /* SYSTEMD_EDITOR takes precedence over EDITOR which takes precedence over VISUAL
6782 * If neither SYSTEMD_EDITOR nor EDITOR nor VISUAL are present,
6783 * we try to execute well known editors
6784 */
6785 editor = getenv("SYSTEMD_EDITOR");
6786 if (!editor)
6787 editor = getenv("EDITOR");
6788 if (!editor)
6789 editor = getenv("VISUAL");
6790
6791 if (!isempty(editor)) {
9ef5d8f2
JS
6792 editor_args = strv_split(editor, WHITESPACE);
6793 if (!editor_args) {
6794 (void) log_oom();
6795 _exit(EXIT_FAILURE);
6796 }
6797 n_editor_args = strv_length(editor_args);
6798 argc += n_editor_args - 1;
6799 }
6800 args = newa(const char*, argc + 1);
6801
6802 if (n_editor_args > 0) {
6803 args[0] = editor_args[0];
6804 for (; i < n_editor_args; i++)
6805 args[i] = editor_args[i];
6806 }
6807
6808 STRV_FOREACH_PAIR(original_path, tmp_path, paths) {
6809 args[i] = *tmp_path;
6810 i++;
7d4fb3b1 6811 }
9ef5d8f2
JS
6812 args[i] = NULL;
6813
6814 if (n_editor_args > 0)
6815 execvp(args[0], (char* const*) args);
7d4fb3b1 6816
9391a1c3 6817 FOREACH_STRING(p, "editor", "nano", "vim", "vi") {
1cfa9a4c
LP
6818 args[0] = p;
6819 execvp(p, (char* const*) args);
7d4fb3b1
RC
6820 /* We do not fail if the editor doesn't exist
6821 * because we want to try each one of them before
6822 * failing.
6823 */
6824 if (errno != ENOENT) {
691395d8 6825 log_error_errno(errno, "Failed to execute %s: %m", editor);
7d4fb3b1
RC
6826 _exit(EXIT_FAILURE);
6827 }
6828 }
6829
1cfa9a4c 6830 log_error("Cannot edit unit(s), no editor available. Please set either $SYSTEMD_EDITOR, $EDITOR or $VISUAL.");
7d4fb3b1
RC
6831 _exit(EXIT_FAILURE);
6832 }
6833
45519fd6 6834 return 0;
7d4fb3b1
RC
6835}
6836
6837static int find_paths_to_edit(sd_bus *bus, char **names, char ***paths) {
8e766630 6838 _cleanup_(lookup_paths_free) LookupPaths lp = {};
7d4fb3b1
RC
6839 char **name;
6840 int r;
6841
6842 assert(names);
6843 assert(paths);
6844
4943d143 6845 r = lookup_paths_init(&lp, arg_scope, 0, arg_root);
5b013a2f 6846 if (r < 0)
8df18507 6847 return r;
7d4fb3b1 6848
e9e310f8 6849 STRV_FOREACH(name, names) {
b74df547
ZJS
6850 _cleanup_free_ char *path = NULL, *new_path = NULL, *tmp_path = NULL, *tmp_name = NULL;
6851 const char *unit_name;
7d4fb3b1 6852
4fbd7192 6853 r = unit_find_paths(bus, *name, &lp, &path, NULL);
e9e310f8
RC
6854 if (r < 0)
6855 return r;
b3734d98
ZJS
6856
6857 if (r == 0) {
6858 assert(!path);
6859
6860 if (!arg_force) {
0dcabf09
ZJS
6861 log_error("Run 'systemctl edit%s --force %s' to create a new unit.",
6862 arg_scope == UNIT_FILE_GLOBAL ? " --global" :
6863 arg_scope == UNIT_FILE_USER ? " --user" : "",
6864 *name);
39c38ce1
DC
6865 return -ENOENT;
6866 }
39c38ce1 6867
b3734d98
ZJS
6868 /* Create a new unit from scratch */
6869 unit_name = *name;
6870 r = unit_file_create_new(&lp, unit_name,
6871 arg_full ? NULL : ".d/override.conf",
6872 &new_path, &tmp_path);
6873 } else {
6874 assert(path);
b74df547 6875
b3734d98
ZJS
6876 unit_name = basename(path);
6877 /* We follow unit aliases, but we need to propagate the instance */
6878 if (unit_name_is_valid(*name, UNIT_NAME_INSTANCE) &&
6879 unit_name_is_valid(unit_name, UNIT_NAME_TEMPLATE)) {
6880 _cleanup_free_ char *instance = NULL;
b74df547 6881
b3734d98
ZJS
6882 r = unit_name_to_instance(*name, &instance);
6883 if (r < 0)
6884 return r;
b74df547 6885
b3734d98
ZJS
6886 r = unit_name_replace_instance(unit_name, instance, &tmp_name);
6887 if (r < 0)
6888 return r;
6889
6890 unit_name = tmp_name;
6891 }
b74df547 6892
39c38ce1 6893 if (arg_full)
b74df547 6894 r = unit_file_create_copy(&lp, unit_name, path, &new_path, &tmp_path);
39c38ce1 6895 else
b74df547 6896 r = unit_file_create_new(&lp, unit_name, ".d/override.conf", &new_path, &tmp_path);
b3734d98 6897 }
e9e310f8 6898 if (r < 0)
ad2a0358 6899 return r;
7d4fb3b1 6900
e9e310f8
RC
6901 r = strv_push_pair(paths, new_path, tmp_path);
6902 if (r < 0)
6903 return log_oom();
78df0edc 6904 new_path = tmp_path = NULL;
7d4fb3b1
RC
6905 }
6906
6907 return 0;
6908}
6909
e449de87 6910static int edit(int argc, char *argv[], void *userdata) {
7d4fb3b1
RC
6911 _cleanup_strv_free_ char **names = NULL;
6912 _cleanup_strv_free_ char **paths = NULL;
6913 char **original, **tmp;
4fbd7192 6914 sd_bus *bus;
7d4fb3b1
RC
6915 int r;
6916
7d4fb3b1 6917 if (!on_tty()) {
4fbd7192 6918 log_error("Cannot edit units if not on a tty.");
7d4fb3b1
RC
6919 return -EINVAL;
6920 }
6921
6922 if (arg_transport != BUS_TRANSPORT_LOCAL) {
4fbd7192 6923 log_error("Cannot edit units remotely.");
7d4fb3b1
RC
6924 return -EINVAL;
6925 }
6926
4fbd7192
LP
6927 r = acquire_bus(BUS_MANAGER, &bus);
6928 if (r < 0)
6929 return r;
6930
e449de87 6931 r = expand_names(bus, strv_skip(argv, 1), NULL, &names);
7d4fb3b1
RC
6932 if (r < 0)
6933 return log_error_errno(r, "Failed to expand names: %m");
6934
9d9dd746
ZJS
6935 STRV_FOREACH(tmp, names) {
6936 r = unit_is_masked(bus, *tmp);
6937 if (r < 0)
6938 return r;
6939
6940 if (r > 0) {
6941 log_error("Cannot edit %s: unit is masked.", *tmp);
6942 return -EINVAL;
6943 }
6944 }
6945
7d4fb3b1
RC
6946 r = find_paths_to_edit(bus, names, &paths);
6947 if (r < 0)
6948 return r;
6949
b5e6a600 6950 if (strv_isempty(paths))
7d4fb3b1 6951 return -ENOENT;
7d4fb3b1
RC
6952
6953 r = run_editor(paths);
6954 if (r < 0)
6955 goto end;
6956
6957 STRV_FOREACH_PAIR(original, tmp, paths) {
9d9dd746
ZJS
6958 /* If the temporary file is empty we ignore it.
6959 * This allows the user to cancel the modification.
7d4fb3b1
RC
6960 */
6961 if (null_or_empty_path(*tmp)) {
45519fd6 6962 log_warning("Editing \"%s\" canceled: temporary file is empty.", *original);
7d4fb3b1
RC
6963 continue;
6964 }
45519fd6 6965
7d4fb3b1
RC
6966 r = rename(*tmp, *original);
6967 if (r < 0) {
029009d4 6968 r = log_error_errno(errno, "Failed to rename \"%s\" to \"%s\": %m", *tmp, *original);
7d4fb3b1
RC
6969 goto end;
6970 }
6971 }
6972
45519fd6
LP
6973 r = 0;
6974
6975 if (!arg_no_reload && !install_client_side())
e449de87 6976 r = daemon_reload(argc, argv, userdata);
7d4fb3b1
RC
6977
6978end:
5f18271e 6979 STRV_FOREACH_PAIR(original, tmp, paths) {
45519fd6 6980 (void) unlink(*tmp);
7d4fb3b1 6981
5f18271e
RC
6982 /* Removing empty dropin dirs */
6983 if (!arg_full) {
043717f9
RC
6984 _cleanup_free_ char *dir;
6985
6986 dir = dirname_malloc(*original);
6987 if (!dir)
6988 return log_oom();
6989
5f18271e
RC
6990 /* no need to check if the dir is empty, rmdir
6991 * does nothing if it is not the case.
6992 */
6993 (void) rmdir(dir);
6994 }
6995 }
6996
7d4fb3b1
RC
6997 return r;
6998}
6999
601185b4 7000static void systemctl_help(void) {
ee5324aa 7001 (void) pager_open(arg_no_pager, false);
729e3769 7002
2e33c433 7003 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
729e3769 7004 "Query or send control commands to the systemd manager.\n\n"
8a0867d6
LP
7005 " -h --help Show this help\n"
7006 " --version Show package version\n"
f459b602
MAP
7007 " --system Connect to system manager\n"
7008 " --user Connect to user service manager\n"
7009 " -H --host=[USER@]HOST\n"
7010 " Operate on remote host\n"
7011 " -M --machine=CONTAINER\n"
7012 " Operate on local container\n"
3fb90db2
ZJS
7013 " -t --type=TYPE List units of a particular type\n"
7014 " --state=STATE List units with particular LOAD or SUB or ACTIVE state\n"
8a0867d6 7015 " -p --property=NAME Show only properties by this name\n"
2cdbbc9a
LP
7016 " -a --all Show all properties/all units currently in memory,\n"
7017 " including dead/empty ones. To list all units installed on\n"
7018 " the system, use the 'list-unit-files' command instead.\n"
bef19548 7019 " --failed Same as --state=failed\n"
98a6e132 7020 " -l --full Don't ellipsize unit names on output\n"
1238ee09 7021 " -r --recursive Show unit list of host and local containers\n"
4dc5b821
LP
7022 " --reverse Show reverse dependencies with 'list-dependencies'\n"
7023 " --job-mode=MODE Specify how to deal with already queued jobs, when\n"
7024 " queueing a new job\n"
a521ae4a 7025 " --show-types When showing sockets, explicitly show their type\n"
4f9a9105 7026 " --value When showing properties, only print the value\n"
b37844d3
LP
7027 " -i --ignore-inhibitors\n"
7028 " When shutting down or sleeping, ignore inhibitors\n"
a8f11321
LP
7029 " --kill-who=WHO Who to send signal to\n"
7030 " -s --signal=SIGNAL Which signal to send\n"
57ab2eab 7031 " --now Start or stop unit in addition to enabling or disabling it\n"
1ae17672 7032 " --dry-run Only print what would be done\n"
8a0867d6 7033 " -q --quiet Suppress output\n"
93a08841 7034 " --wait For (re)start, wait until service stopped again\n"
8a0867d6 7035 " --no-block Do not wait until operation finished\n"
8a0867d6 7036 " --no-wall Don't send wall message before halt/power-off/reboot\n"
3fb90db2 7037 " --no-reload Don't reload daemon after en-/dis-abling unit files\n"
ebed32bf 7038 " --no-legend Do not print a legend (column headers and hints)\n"
69fc152f 7039 " --no-pager Do not pipe output into a pager\n"
501fc174
LP
7040 " --no-ask-password\n"
7041 " Do not ask for system passwords\n"
4e93d369
LR
7042 " --global Enable/disable/mask unit files globally\n"
7043 " --runtime Enable/disable/mask unit files temporarily until next\n"
7044 " reboot\n"
8a0867d6
LP
7045 " -f --force When enabling unit files, override existing symlinks\n"
7046 " When shutting down, execute action immediately\n"
3fb90db2 7047 " --preset-mode= Apply only enable, only disable, or all presets\n"
4e93d369
LR
7048 " --root=PATH Enable/disable/mask unit files in the specified root\n"
7049 " directory\n"
76fdc966 7050 " -n --lines=INTEGER Number of journal entries to show\n"
584c6e70 7051 " -o --output=STRING Change journal output mode (short, short-precise,\n"
7e563bfc
IW
7052 " short-iso, short-iso-precise, short-full,\n"
7053 " short-monotonic, short-unix,\n"
584c6e70 7054 " verbose, export, json, json-pretty, json-sse, cat)\n"
5bdf2243 7055 " --firmware-setup Tell the firmware to show the setup menu on next boot\n"
815ebc54 7056 " --plain Print unit dependencies as a list instead of a tree\n\n"
34c4b47b 7057 "Unit Commands:\n"
fbf3283b
ZJS
7058 " list-units [PATTERN...] List units currently in memory\n"
7059 " list-sockets [PATTERN...] List socket units currently in memory,\n"
7060 " ordered by address\n"
7061 " list-timers [PATTERN...] List timer units currently in memory,\n"
7062 " ordered by next elapse\n"
7063 " start UNIT... Start (activate) one or more units\n"
7064 " stop UNIT... Stop (deactivate) one or more units\n"
7065 " reload UNIT... Reload one or more units\n"
7066 " restart UNIT... Start or restart one or more units\n"
7067 " try-restart UNIT... Restart one or more units if active\n"
7068 " reload-or-restart UNIT... Reload one or more units if possible,\n"
7069 " otherwise start or restart\n"
7070 " try-reload-or-restart UNIT... If active, reload one or more units,\n"
7071 " if supported, otherwise restart\n"
7072 " isolate UNIT Start one unit and stop all others\n"
7073 " kill UNIT... Send signal to processes of a unit\n"
7074 " is-active PATTERN... Check whether units are active\n"
7075 " is-failed PATTERN... Check whether units are failed\n"
7076 " status [PATTERN...|PID...] Show runtime status of one or more units\n"
7077 " show [PATTERN...|JOB...] Show properties of one or more\n"
7078 " units/jobs or the manager\n"
7079 " cat PATTERN... Show files and drop-ins of specified units\n"
7080 " set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit\n"
7081 " help PATTERN...|PID... Show manual for one or more units\n"
7082 " reset-failed [PATTERN...] Reset failed state for all, one, or more\n"
7083 " units\n"
7084 " list-dependencies [UNIT] Recursively show units which are required\n"
7085 " or wanted by this unit or by which this\n"
7086 " unit is required or wanted\n\n"
34c4b47b 7087 "Unit File Commands:\n"
fbf3283b
ZJS
7088 " list-unit-files [PATTERN...] List installed unit files\n"
7089 " enable [UNIT...|PATH...] Enable one or more unit files\n"
7090 " disable UNIT... Disable one or more unit files\n"
7091 " reenable UNIT... Reenable one or more unit files\n"
7092 " preset UNIT... Enable/disable one or more unit files\n"
7093 " based on preset configuration\n"
7094 " preset-all Enable/disable all unit files based on\n"
7095 " preset configuration\n"
7096 " is-enabled UNIT... Check whether unit files are enabled\n"
7097 " mask UNIT... Mask one or more units\n"
7098 " unmask UNIT... Unmask one or more units\n"
7099 " link PATH... Link one or more units files into\n"
7100 " the search path\n"
7101 " revert UNIT... Revert one or more unit files to vendor\n"
7102 " version\n"
7103 " add-wants TARGET UNIT... Add 'Wants' dependency for the target\n"
7104 " on specified one or more units\n"
7105 " add-requires TARGET UNIT... Add 'Requires' dependency for the target\n"
7106 " on specified one or more units\n"
7107 " edit UNIT... Edit one or more unit files\n"
7108 " get-default Get the name of the default target\n"
7109 " set-default TARGET Set the default target\n\n"
0d292f5e 7110 "Machine Commands:\n"
fbf3283b 7111 " list-machines [PATTERN...] List local containers and host\n\n"
34c4b47b 7112 "Job Commands:\n"
fbf3283b
ZJS
7113 " list-jobs [PATTERN...] List jobs\n"
7114 " cancel [JOB...] Cancel all, one, or more jobs\n\n"
34c4b47b 7115 "Environment Commands:\n"
fbf3283b 7116 " show-environment Dump environment\n"
135775c1
ZJS
7117 " set-environment VARIABLE=VALUE... Set one or more environment variables\n"
7118 " unset-environment VARIABLE... Unset one or more environment variables\n"
7119 " import-environment [VARIABLE...] Import all or some environment variables\n\n"
34c4b47b 7120 "Manager Lifecycle Commands:\n"
fbf3283b
ZJS
7121 " daemon-reload Reload systemd manager configuration\n"
7122 " daemon-reexec Reexecute systemd manager\n\n"
34c4b47b 7123 "System Commands:\n"
fbf3283b
ZJS
7124 " is-system-running Check whether system is fully running\n"
7125 " default Enter system default mode\n"
7126 " rescue Enter system rescue mode\n"
7127 " emergency Enter system emergency mode\n"
7128 " halt Shut down and halt the system\n"
7129 " poweroff Shut down and power-off the system\n"
7130 " reboot [ARG] Shut down and reboot the system\n"
7131 " kexec Shut down and reboot the system with kexec\n"
7132 " exit [EXIT_CODE] Request user instance or container exit\n"
7133 " switch-root ROOT [INIT] Change to a different root file system\n"
7134 " suspend Suspend the system\n"
7135 " hibernate Hibernate the system\n"
c58493c0 7136 " hybrid-sleep Hibernate and suspend the system\n"
e68c79db 7137 " suspend-then-hibernate Suspend the system, wake after a period of\n"
c58493c0 7138 " time and put it into hibernate\n",
5b6319dc 7139 program_invocation_short_name);
7e4249b9
LP
7140}
7141
601185b4 7142static void halt_help(void) {
37185ec8 7143 printf("%s [OPTIONS...]%s\n\n"
e4b61340
LP
7144 "%s the system.\n\n"
7145 " --help Show this help\n"
7146 " --halt Halt the machine\n"
7147 " -p --poweroff Switch off the machine\n"
7148 " --reboot Reboot the machine\n"
2e33c433
LP
7149 " -f --force Force immediate halt/power-off/reboot\n"
7150 " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n"
e4b61340 7151 " -d --no-wtmp Don't write wtmp record\n"
2e33c433 7152 " --no-wall Don't send wall message before halt/power-off/reboot\n",
e4b61340 7153 program_invocation_short_name,
37185ec8 7154 arg_action == ACTION_REBOOT ? " [ARG]" : "",
e4b61340
LP
7155 arg_action == ACTION_REBOOT ? "Reboot" :
7156 arg_action == ACTION_POWEROFF ? "Power off" :
7157 "Halt");
e4b61340
LP
7158}
7159
601185b4 7160static void shutdown_help(void) {
08e4b1c5 7161 printf("%s [OPTIONS...] [TIME] [WALL...]\n\n"
e4b61340
LP
7162 "Shut down the system.\n\n"
7163 " --help Show this help\n"
7164 " -H --halt Halt the machine\n"
7165 " -P --poweroff Power-off the machine\n"
7166 " -r --reboot Reboot the machine\n"
386da858 7167 " -h Equivalent to --poweroff, overridden by --halt\n"
2e33c433 7168 " -k Don't halt/power-off/reboot, just send warnings\n"
f6144808 7169 " --no-wall Don't send wall message before halt/power-off/reboot\n"
f6144808 7170 " -c Cancel a pending shutdown\n",
e4b61340 7171 program_invocation_short_name);
e4b61340
LP
7172}
7173
601185b4 7174static void telinit_help(void) {
2e33c433 7175 printf("%s [OPTIONS...] {COMMAND}\n\n"
514f4ef5
LP
7176 "Send control commands to the init daemon.\n\n"
7177 " --help Show this help\n"
2e33c433 7178 " --no-wall Don't send wall message before halt/power-off/reboot\n\n"
e4b61340
LP
7179 "Commands:\n"
7180 " 0 Power-off the machine\n"
7181 " 6 Reboot the machine\n"
514f4ef5
LP
7182 " 2, 3, 4, 5 Start runlevelX.target unit\n"
7183 " 1, s, S Enter rescue mode\n"
7184 " q, Q Reload init daemon configuration\n"
7185 " u, U Reexecute init daemon\n",
e4b61340 7186 program_invocation_short_name);
e4b61340
LP
7187}
7188
601185b4 7189static void runlevel_help(void) {
2e33c433 7190 printf("%s [OPTIONS...]\n\n"
e4b61340
LP
7191 "Prints the previous and current runlevel of the init system.\n\n"
7192 " --help Show this help\n",
7193 program_invocation_short_name);
e4b61340
LP
7194}
7195
b93312f5 7196static void help_types(void) {
b93312f5
ZJS
7197 if (!arg_no_legend)
7198 puts("Available unit types:");
5c828e66
LP
7199
7200 DUMP_STRING_TABLE(unit_type, UnitType, _UNIT_TYPE_MAX);
e16972e6
ZJS
7201}
7202
7203static void help_states(void) {
e16972e6
ZJS
7204 if (!arg_no_legend)
7205 puts("Available unit load states:");
5c828e66 7206 DUMP_STRING_TABLE(unit_load_state, UnitLoadState, _UNIT_LOAD_STATE_MAX);
e16972e6
ZJS
7207
7208 if (!arg_no_legend)
7209 puts("\nAvailable unit active states:");
5c828e66 7210 DUMP_STRING_TABLE(unit_active_state, UnitActiveState, _UNIT_ACTIVE_STATE_MAX);
7e55de3b
ZJS
7211
7212 if (!arg_no_legend)
7213 puts("\nAvailable automount unit substates:");
5c828e66 7214 DUMP_STRING_TABLE(automount_state, AutomountState, _AUTOMOUNT_STATE_MAX);
7e55de3b 7215
7e55de3b
ZJS
7216 if (!arg_no_legend)
7217 puts("\nAvailable device unit substates:");
5c828e66 7218 DUMP_STRING_TABLE(device_state, DeviceState, _DEVICE_STATE_MAX);
7e55de3b
ZJS
7219
7220 if (!arg_no_legend)
7221 puts("\nAvailable mount unit substates:");
5c828e66 7222 DUMP_STRING_TABLE(mount_state, MountState, _MOUNT_STATE_MAX);
7e55de3b
ZJS
7223
7224 if (!arg_no_legend)
7225 puts("\nAvailable path unit substates:");
5c828e66 7226 DUMP_STRING_TABLE(path_state, PathState, _PATH_STATE_MAX);
7e55de3b
ZJS
7227
7228 if (!arg_no_legend)
7229 puts("\nAvailable scope unit substates:");
5c828e66 7230 DUMP_STRING_TABLE(scope_state, ScopeState, _SCOPE_STATE_MAX);
7e55de3b
ZJS
7231
7232 if (!arg_no_legend)
7233 puts("\nAvailable service unit substates:");
5c828e66 7234 DUMP_STRING_TABLE(service_state, ServiceState, _SERVICE_STATE_MAX);
7e55de3b
ZJS
7235
7236 if (!arg_no_legend)
7237 puts("\nAvailable slice unit substates:");
5c828e66 7238 DUMP_STRING_TABLE(slice_state, SliceState, _SLICE_STATE_MAX);
7e55de3b 7239
7e55de3b
ZJS
7240 if (!arg_no_legend)
7241 puts("\nAvailable socket unit substates:");
5c828e66 7242 DUMP_STRING_TABLE(socket_state, SocketState, _SOCKET_STATE_MAX);
7e55de3b
ZJS
7243
7244 if (!arg_no_legend)
7245 puts("\nAvailable swap unit substates:");
5c828e66 7246 DUMP_STRING_TABLE(swap_state, SwapState, _SWAP_STATE_MAX);
7e55de3b
ZJS
7247
7248 if (!arg_no_legend)
7249 puts("\nAvailable target unit substates:");
5c828e66 7250 DUMP_STRING_TABLE(target_state, TargetState, _TARGET_STATE_MAX);
7e55de3b
ZJS
7251
7252 if (!arg_no_legend)
7253 puts("\nAvailable timer unit substates:");
5c828e66 7254 DUMP_STRING_TABLE(timer_state, TimerState, _TIMER_STATE_MAX);
45c0c61d
ZJS
7255}
7256
e4b61340 7257static int systemctl_parse_argv(int argc, char *argv[]) {
7e4249b9 7258 enum {
90d473a1 7259 ARG_FAIL = 0x100,
afba4199
ZJS
7260 ARG_REVERSE,
7261 ARG_AFTER,
7262 ARG_BEFORE,
1ae17672 7263 ARG_DRY_RUN,
991f2a39 7264 ARG_SHOW_TYPES,
23ade460 7265 ARG_IRREVERSIBLE,
e67c3609 7266 ARG_IGNORE_DEPENDENCIES,
4f9a9105 7267 ARG_VALUE,
35df8f27 7268 ARG_VERSION,
af2d49f7 7269 ARG_USER,
7e4249b9 7270 ARG_SYSTEM,
ee5762e3 7271 ARG_GLOBAL,
6e905d93 7272 ARG_NO_BLOCK,
ebed32bf 7273 ARG_NO_LEGEND,
611efaac 7274 ARG_NO_PAGER,
4445a875 7275 ARG_NO_WALL,
be394c48 7276 ARG_ROOT,
ee5762e3 7277 ARG_NO_RELOAD,
501fc174 7278 ARG_KILL_WHO,
30732560 7279 ARG_NO_ASK_PASSWORD,
729e3769 7280 ARG_FAILED,
df50185b 7281 ARG_RUNTIME,
9b9b3d36 7282 ARG_PLAIN,
4dc5b821 7283 ARG_STATE,
d309c1c3
LP
7284 ARG_JOB_MODE,
7285 ARG_PRESET_MODE,
5bdf2243 7286 ARG_FIRMWARE_SETUP,
57ab2eab 7287 ARG_NOW,
9ef15026 7288 ARG_MESSAGE,
93a08841 7289 ARG_WAIT,
7e4249b9
LP
7290 };
7291
7292 static const struct option options[] = {
9ea9d4cf
LP
7293 { "help", no_argument, NULL, 'h' },
7294 { "version", no_argument, NULL, ARG_VERSION },
7295 { "type", required_argument, NULL, 't' },
7296 { "property", required_argument, NULL, 'p' },
7297 { "all", no_argument, NULL, 'a' },
7298 { "reverse", no_argument, NULL, ARG_REVERSE },
7299 { "after", no_argument, NULL, ARG_AFTER },
7300 { "before", no_argument, NULL, ARG_BEFORE },
7301 { "show-types", no_argument, NULL, ARG_SHOW_TYPES },
7302 { "failed", no_argument, NULL, ARG_FAILED }, /* compatibility only */
7303 { "full", no_argument, NULL, 'l' },
4dc5b821
LP
7304 { "job-mode", required_argument, NULL, ARG_JOB_MODE },
7305 { "fail", no_argument, NULL, ARG_FAIL }, /* compatibility only */
7306 { "irreversible", no_argument, NULL, ARG_IRREVERSIBLE }, /* compatibility only */
7307 { "ignore-dependencies", no_argument, NULL, ARG_IGNORE_DEPENDENCIES }, /* compatibility only */
9ea9d4cf 7308 { "ignore-inhibitors", no_argument, NULL, 'i' },
4f9a9105 7309 { "value", no_argument, NULL, ARG_VALUE },
9ea9d4cf
LP
7310 { "user", no_argument, NULL, ARG_USER },
7311 { "system", no_argument, NULL, ARG_SYSTEM },
7312 { "global", no_argument, NULL, ARG_GLOBAL },
93a08841 7313 { "wait", no_argument, NULL, ARG_WAIT },
9ea9d4cf
LP
7314 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
7315 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
7316 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
7317 { "no-wall", no_argument, NULL, ARG_NO_WALL },
1ae17672 7318 { "dry-run", no_argument, NULL, ARG_DRY_RUN },
9ea9d4cf
LP
7319 { "quiet", no_argument, NULL, 'q' },
7320 { "root", required_argument, NULL, ARG_ROOT },
68da321f 7321 { "force", no_argument, NULL, 'f' },
9ea9d4cf
LP
7322 { "no-reload", no_argument, NULL, ARG_NO_RELOAD },
7323 { "kill-who", required_argument, NULL, ARG_KILL_WHO },
7324 { "signal", required_argument, NULL, 's' },
7325 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
7326 { "host", required_argument, NULL, 'H' },
f459b602 7327 { "machine", required_argument, NULL, 'M' },
9ea9d4cf
LP
7328 { "runtime", no_argument, NULL, ARG_RUNTIME },
7329 { "lines", required_argument, NULL, 'n' },
7330 { "output", required_argument, NULL, 'o' },
7331 { "plain", no_argument, NULL, ARG_PLAIN },
7332 { "state", required_argument, NULL, ARG_STATE },
1238ee09 7333 { "recursive", no_argument, NULL, 'r' },
d309c1c3 7334 { "preset-mode", required_argument, NULL, ARG_PRESET_MODE },
5bdf2243 7335 { "firmware-setup", no_argument, NULL, ARG_FIRMWARE_SETUP },
57ab2eab 7336 { "now", no_argument, NULL, ARG_NOW },
9ef15026 7337 { "message", required_argument, NULL, ARG_MESSAGE },
eb9da376 7338 {}
7e4249b9
LP
7339 };
7340
5ab22f33 7341 const char *p;
0f03c2a4 7342 int c, r;
7e4249b9 7343
e4b61340 7344 assert(argc >= 0);
7e4249b9
LP
7345 assert(argv);
7346
16f017fa
IS
7347 /* we default to allowing interactive authorization only in systemctl (not in the legacy commands) */
7348 arg_ask_password = true;
7349
601185b4 7350 while ((c = getopt_long(argc, argv, "ht:p:alqfs:H:M:n:o:ir", options, NULL)) >= 0)
7e4249b9
LP
7351
7352 switch (c) {
7353
7354 case 'h':
601185b4
ZJS
7355 systemctl_help();
7356 return 0;
35df8f27
LP
7357
7358 case ARG_VERSION:
3f6fd1ba 7359 return version();
7e4249b9 7360
20b3f379 7361 case 't': {
bf409580 7362 if (isempty(optarg)) {
10ab1831 7363 log_error("--type= requires arguments.");
bf409580
TA
7364 return -EINVAL;
7365 }
45c0c61d 7366
c58bd76a 7367 for (p = optarg;;) {
5ab22f33 7368 _cleanup_free_ char *type = NULL;
20b3f379 7369
5ab22f33
SS
7370 r = extract_first_word(&p, &type, ",", 0);
7371 if (r < 0)
7372 return log_error_errno(r, "Failed to parse type: %s", optarg);
5ab22f33
SS
7373 if (r == 0)
7374 break;
20b3f379
ZJS
7375
7376 if (streq(type, "help")) {
7377 help_types();
7378 return 0;
7379 }
7380
7381 if (unit_type_from_string(type) >= 0) {
7e9d36e0 7382 if (strv_push(&arg_types, type) < 0)
20b3f379
ZJS
7383 return log_oom();
7384 type = NULL;
7385 continue;
7386 }
7387
9b9b3d36
MW
7388 /* It's much nicer to use --state= for
7389 * load states, but let's support this
7390 * in --types= too for compatibility
7391 * with old versions */
7e9d36e0 7392 if (unit_load_state_from_string(type) >= 0) {
9b9b3d36 7393 if (strv_push(&arg_states, type) < 0)
20b3f379
ZJS
7394 return log_oom();
7395 type = NULL;
7396 continue;
7397 }
7398
ab06eef8 7399 log_error("Unknown unit type or load state '%s'.", type);
20b3f379
ZJS
7400 log_info("Use -t help to see a list of allowed values.");
7401 return -EINVAL;
c147dc42 7402 }
20b3f379
ZJS
7403
7404 break;
7405 }
7406
ea4a240d 7407 case 'p': {
033a842c
ZJS
7408 /* Make sure that if the empty property list
7409 was specified, we won't show any properties. */
20b3f379 7410 if (isempty(optarg) && !arg_properties) {
cbc9fbd1 7411 arg_properties = new0(char*, 1);
20b3f379
ZJS
7412 if (!arg_properties)
7413 return log_oom();
c58bd76a
ZJS
7414 } else
7415 for (p = optarg;;) {
5ab22f33 7416 _cleanup_free_ char *prop = NULL;
033a842c 7417
5ab22f33
SS
7418 r = extract_first_word(&p, &prop, ",", 0);
7419 if (r < 0)
7420 return log_error_errno(r, "Failed to parse property: %s", optarg);
5ab22f33
SS
7421 if (r == 0)
7422 break;
ea4a240d 7423
5ab22f33 7424 if (strv_push(&arg_properties, prop) < 0)
20b3f379 7425 return log_oom();
5ab22f33
SS
7426
7427 prop = NULL;
20b3f379 7428 }
48220598
LP
7429
7430 /* If the user asked for a particular
7431 * property, show it to him, even if it is
7432 * empty. */
7433 arg_all = true;
033a842c 7434
48220598 7435 break;
ea4a240d 7436 }
48220598 7437
7e4249b9
LP
7438 case 'a':
7439 arg_all = true;
7440 break;
7441
afba4199
ZJS
7442 case ARG_REVERSE:
7443 arg_dependency = DEPENDENCY_REVERSE;
7444 break;
7445
7446 case ARG_AFTER:
7447 arg_dependency = DEPENDENCY_AFTER;
82948f6c 7448 arg_jobs_after = true;
afba4199
ZJS
7449 break;
7450
7451 case ARG_BEFORE:
7452 arg_dependency = DEPENDENCY_BEFORE;
82948f6c 7453 arg_jobs_before = true;
afba4199
ZJS
7454 break;
7455
991f2a39
ZJS
7456 case ARG_SHOW_TYPES:
7457 arg_show_types = true;
7458 break;
7459
4f9a9105
ZJS
7460 case ARG_VALUE:
7461 arg_value = true;
7462 break;
7463
4dc5b821
LP
7464 case ARG_JOB_MODE:
7465 arg_job_mode = optarg;
7466 break;
7467
90d473a1 7468 case ARG_FAIL:
e67c3609
LP
7469 arg_job_mode = "fail";
7470 break;
7471
23ade460
MS
7472 case ARG_IRREVERSIBLE:
7473 arg_job_mode = "replace-irreversibly";
7474 break;
7475
e67c3609
LP
7476 case ARG_IGNORE_DEPENDENCIES:
7477 arg_job_mode = "ignore-dependencies";
7e4249b9
LP
7478 break;
7479
af2d49f7 7480 case ARG_USER:
729e3769 7481 arg_scope = UNIT_FILE_USER;
7e4249b9
LP
7482 break;
7483
7484 case ARG_SYSTEM:
729e3769
LP
7485 arg_scope = UNIT_FILE_SYSTEM;
7486 break;
7487
7488 case ARG_GLOBAL:
7489 arg_scope = UNIT_FILE_GLOBAL;
7e4249b9
LP
7490 break;
7491
93a08841
MP
7492 case ARG_WAIT:
7493 arg_wait = true;
7494 break;
7495
6e905d93
LP
7496 case ARG_NO_BLOCK:
7497 arg_no_block = true;
7e4249b9
LP
7498 break;
7499
ebed32bf
MS
7500 case ARG_NO_LEGEND:
7501 arg_no_legend = true;
7502 break;
7503
611efaac
LP
7504 case ARG_NO_PAGER:
7505 arg_no_pager = true;
7506 break;
0736af98 7507
514f4ef5
LP
7508 case ARG_NO_WALL:
7509 arg_no_wall = true;
7510 break;
7511
be394c48 7512 case ARG_ROOT:
bac75eb3 7513 r = parse_path_argument_and_warn(optarg, false, &arg_root);
0f03c2a4
LP
7514 if (r < 0)
7515 return r;
be394c48
FC
7516 break;
7517
98a6e132 7518 case 'l':
8fe914ec
LP
7519 arg_full = true;
7520 break;
7521
30732560 7522 case ARG_FAILED:
9b9b3d36
MW
7523 if (strv_extend(&arg_states, "failed") < 0)
7524 return log_oom();
7525
30732560
LP
7526 break;
7527
1ae17672
ZJS
7528 case ARG_DRY_RUN:
7529 arg_dry_run = true;
7530 break;
7531
0183528f
LP
7532 case 'q':
7533 arg_quiet = true;
7534 break;
7535
b4f27ccc 7536 case 'f':
313cefa1 7537 arg_force++;
ee5762e3
LP
7538 break;
7539
7540 case ARG_NO_RELOAD:
7541 arg_no_reload = true;
7542 break;
7543
8a0867d6
LP
7544 case ARG_KILL_WHO:
7545 arg_kill_who = optarg;
7546 break;
7547
8a0867d6 7548 case 's':
5c828e66
LP
7549 if (streq(optarg, "help")) {
7550 DUMP_STRING_TABLE(signal, int, _NSIG);
7551 return 0;
7552 }
7553
29a3db75 7554 arg_signal = signal_from_string(optarg);
691395d8 7555 if (arg_signal < 0) {
8a0867d6
LP
7556 log_error("Failed to parse signal string %s.", optarg);
7557 return -EINVAL;
7558 }
7559 break;
7560
501fc174
LP
7561 case ARG_NO_ASK_PASSWORD:
7562 arg_ask_password = false;
7563 break;
7564
f459b602
MAP
7565 case 'H':
7566 arg_transport = BUS_TRANSPORT_REMOTE;
7567 arg_host = optarg;
a8f11321
LP
7568 break;
7569
f459b602 7570 case 'M':
de33fc62 7571 arg_transport = BUS_TRANSPORT_MACHINE;
f459b602 7572 arg_host = optarg;
a8f11321
LP
7573 break;
7574
729e3769
LP
7575 case ARG_RUNTIME:
7576 arg_runtime = true;
7577 break;
7578
df50185b
LP
7579 case 'n':
7580 if (safe_atou(optarg, &arg_lines) < 0) {
7581 log_error("Failed to parse lines '%s'", optarg);
7582 return -EINVAL;
7583 }
7584 break;
7585
df50185b 7586 case 'o':
5c828e66
LP
7587 if (streq(optarg, "help")) {
7588 DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
7589 return 0;
7590 }
7591
df50185b
LP
7592 arg_output = output_mode_from_string(optarg);
7593 if (arg_output < 0) {
7594 log_error("Unknown output '%s'.", optarg);
7595 return -EINVAL;
7596 }
7597 break;
7598
b37844d3
LP
7599 case 'i':
7600 arg_ignore_inhibitors = true;
7601 break;
7602
5d0c05e5
LN
7603 case ARG_PLAIN:
7604 arg_plain = true;
7605 break;
7606
5bdf2243
JJ
7607 case ARG_FIRMWARE_SETUP:
7608 arg_firmware_setup = true;
7609 break;
7610
9b9b3d36 7611 case ARG_STATE: {
bf409580 7612 if (isempty(optarg)) {
10ab1831 7613 log_error("--state= requires arguments.");
bf409580
TA
7614 return -EINVAL;
7615 }
9b9b3d36 7616
c58bd76a 7617 for (p = optarg;;) {
bc6c18fe 7618 _cleanup_free_ char *s = NULL;
9b9b3d36 7619
5ab22f33
SS
7620 r = extract_first_word(&p, &s, ",", 0);
7621 if (r < 0)
6862111e 7622 return log_error_errno(r, "Failed to parse state: %s", optarg);
5ab22f33
SS
7623 if (r == 0)
7624 break;
9b9b3d36 7625
e16972e6
ZJS
7626 if (streq(s, "help")) {
7627 help_states();
7628 return 0;
7629 }
7630
7e9d36e0 7631 if (strv_push(&arg_states, s) < 0)
9b9b3d36 7632 return log_oom();
7e9d36e0
LP
7633
7634 s = NULL;
9b9b3d36
MW
7635 }
7636 break;
7637 }
7638
1238ee09
LP
7639 case 'r':
7640 if (geteuid() != 0) {
f1721625 7641 log_error("--recursive requires root privileges.");
1238ee09
LP
7642 return -EPERM;
7643 }
7644
7645 arg_recursive = true;
7646 break;
7647
d309c1c3 7648 case ARG_PRESET_MODE:
5c828e66
LP
7649 if (streq(optarg, "help")) {
7650 DUMP_STRING_TABLE(unit_file_preset_mode, UnitFilePresetMode, _UNIT_FILE_PRESET_MAX);
7651 return 0;
7652 }
d309c1c3
LP
7653
7654 arg_preset_mode = unit_file_preset_mode_from_string(optarg);
7655 if (arg_preset_mode < 0) {
7656 log_error("Failed to parse preset mode: %s.", optarg);
7657 return -EINVAL;
7658 }
7659
7660 break;
7661
57ab2eab
JS
7662 case ARG_NOW:
7663 arg_now = true;
7664 break;
7665
9ef15026
JS
7666 case ARG_MESSAGE:
7667 if (strv_extend(&arg_wall, optarg) < 0)
7668 return log_oom();
7669 break;
7670
7e4249b9
LP
7671 case '?':
7672 return -EINVAL;
7673
7674 default:
eb9da376 7675 assert_not_reached("Unhandled option");
7e4249b9 7676 }
7e4249b9 7677
f459b602 7678 if (arg_transport != BUS_TRANSPORT_LOCAL && arg_scope != UNIT_FILE_SYSTEM) {
a8f11321
LP
7679 log_error("Cannot access user instance remotely.");
7680 return -EINVAL;
7681 }
7682
93a08841
MP
7683 if (arg_wait && arg_no_block) {
7684 log_error("--wait may not be combined with --no-block.");
7685 return -EINVAL;
7686 }
7687
7e4249b9
LP
7688 return 1;
7689}
7690
e4b61340 7691static int halt_parse_argv(int argc, char *argv[]) {
e4b61340
LP
7692 enum {
7693 ARG_HELP = 0x100,
7694 ARG_HALT,
514f4ef5
LP
7695 ARG_REBOOT,
7696 ARG_NO_WALL
e4b61340
LP
7697 };
7698
7699 static const struct option options[] = {
7700 { "help", no_argument, NULL, ARG_HELP },
7701 { "halt", no_argument, NULL, ARG_HALT },
7702 { "poweroff", no_argument, NULL, 'p' },
7703 { "reboot", no_argument, NULL, ARG_REBOOT },
7704 { "force", no_argument, NULL, 'f' },
7705 { "wtmp-only", no_argument, NULL, 'w' },
7706 { "no-wtmp", no_argument, NULL, 'd' },
f3f054f0 7707 { "no-sync", no_argument, NULL, 'n' },
514f4ef5 7708 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 7709 {}
e4b61340
LP
7710 };
7711
37185ec8 7712 int c, r, runlevel;
e4b61340
LP
7713
7714 assert(argc >= 0);
7715 assert(argv);
7716
7717 if (utmp_get_runlevel(&runlevel, NULL) >= 0)
4c701096 7718 if (IN_SET(runlevel, '0', '6'))
65491fd8 7719 arg_force = 2;
e4b61340 7720
601185b4 7721 while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0)
e4b61340
LP
7722 switch (c) {
7723
7724 case ARG_HELP:
601185b4
ZJS
7725 halt_help();
7726 return 0;
e4b61340
LP
7727
7728 case ARG_HALT:
7729 arg_action = ACTION_HALT;
7730 break;
7731
7732 case 'p':
a042efad
MS
7733 if (arg_action != ACTION_REBOOT)
7734 arg_action = ACTION_POWEROFF;
e4b61340
LP
7735 break;
7736
7737 case ARG_REBOOT:
7738 arg_action = ACTION_REBOOT;
7739 break;
7740
7741 case 'f':
65491fd8 7742 arg_force = 2;
e4b61340
LP
7743 break;
7744
7745 case 'w':
1ae17672 7746 arg_dry_run = true;
e4b61340
LP
7747 break;
7748
7749 case 'd':
7750 arg_no_wtmp = true;
7751 break;
7752
f3f054f0
TB
7753 case 'n':
7754 arg_no_sync = true;
7755 break;
7756
514f4ef5
LP
7757 case ARG_NO_WALL:
7758 arg_no_wall = true;
7759 break;
7760
e4b61340
LP
7761 case 'i':
7762 case 'h':
7763 /* Compatibility nops */
7764 break;
7765
7766 case '?':
7767 return -EINVAL;
7768
7769 default:
eb9da376 7770 assert_not_reached("Unhandled option");
e4b61340 7771 }
e4b61340 7772
c5220a94 7773 if (arg_action == ACTION_REBOOT && (argc == optind || argc == optind + 1)) {
27c06cb5 7774 r = update_reboot_parameter_and_warn(argc == optind + 1 ? argv[optind] : NULL);
c5220a94 7775 if (r < 0)
37185ec8 7776 return r;
37185ec8 7777 } else if (optind < argc) {
e4b61340
LP
7778 log_error("Too many arguments.");
7779 return -EINVAL;
7780 }
7781
7782 return 1;
7783}
7784
2cc7b0a2 7785static int parse_shutdown_time_spec(const char *t, usec_t *_u) {
f6144808
LP
7786 assert(t);
7787 assert(_u);
7788
7789 if (streq(t, "now"))
7790 *_u = 0;
1a639877 7791 else if (!strchr(t, ':')) {
f6144808
LP
7792 uint64_t u;
7793
1a639877 7794 if (safe_atou64(t, &u) < 0)
f6144808
LP
7795 return -EINVAL;
7796
7797 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
7798 } else {
7799 char *e = NULL;
7800 long hour, minute;
b92bea5d 7801 struct tm tm = {};
f6144808
LP
7802 time_t s;
7803 usec_t n;
7804
7805 errno = 0;
7806 hour = strtol(t, &e, 10);
8333c77e 7807 if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
f6144808
LP
7808 return -EINVAL;
7809
7810 minute = strtol(e+1, &e, 10);
8333c77e 7811 if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
f6144808
LP
7812 return -EINVAL;
7813
7814 n = now(CLOCK_REALTIME);
08e4b1c5
LP
7815 s = (time_t) (n / USEC_PER_SEC);
7816
f6144808
LP
7817 assert_se(localtime_r(&s, &tm));
7818
7819 tm.tm_hour = (int) hour;
7820 tm.tm_min = (int) minute;
08e4b1c5 7821 tm.tm_sec = 0;
f6144808
LP
7822
7823 assert_se(s = mktime(&tm));
7824
7825 *_u = (usec_t) s * USEC_PER_SEC;
7826
7827 while (*_u <= n)
7828 *_u += USEC_PER_DAY;
7829 }
7830
7831 return 0;
7832}
7833
e4b61340 7834static int shutdown_parse_argv(int argc, char *argv[]) {
e4b61340
LP
7835 enum {
7836 ARG_HELP = 0x100,
514f4ef5 7837 ARG_NO_WALL
e4b61340
LP
7838 };
7839
7840 static const struct option options[] = {
7841 { "help", no_argument, NULL, ARG_HELP },
7842 { "halt", no_argument, NULL, 'H' },
7843 { "poweroff", no_argument, NULL, 'P' },
7844 { "reboot", no_argument, NULL, 'r' },
04ebb595 7845 { "kexec", no_argument, NULL, 'K' }, /* not documented extension */
514f4ef5 7846 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 7847 {}
e4b61340
LP
7848 };
7849
172d7abf 7850 char **wall = NULL;
f6144808 7851 int c, r;
e4b61340
LP
7852
7853 assert(argc >= 0);
7854 assert(argv);
7855
b068c6f5 7856 while ((c = getopt_long(argc, argv, "HPrhkKat:fFc", options, NULL)) >= 0)
e4b61340
LP
7857 switch (c) {
7858
7859 case ARG_HELP:
601185b4
ZJS
7860 shutdown_help();
7861 return 0;
e4b61340
LP
7862
7863 case 'H':
7864 arg_action = ACTION_HALT;
7865 break;
7866
7867 case 'P':
7868 arg_action = ACTION_POWEROFF;
7869 break;
7870
7871 case 'r':
5622dde3
KS
7872 if (kexec_loaded())
7873 arg_action = ACTION_KEXEC;
7874 else
7875 arg_action = ACTION_REBOOT;
e4b61340
LP
7876 break;
7877
04ebb595
LP
7878 case 'K':
7879 arg_action = ACTION_KEXEC;
7880 break;
7881
e4b61340
LP
7882 case 'h':
7883 if (arg_action != ACTION_HALT)
7884 arg_action = ACTION_POWEROFF;
7885 break;
7886
7887 case 'k':
1ae17672 7888 arg_dry_run = true;
e4b61340
LP
7889 break;
7890
514f4ef5
LP
7891 case ARG_NO_WALL:
7892 arg_no_wall = true;
7893 break;
7894
e4b61340 7895 case 'a':
b068c6f5 7896 case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */
75836b9d
JS
7897 case 'f':
7898 case 'F':
e4b61340
LP
7899 /* Compatibility nops */
7900 break;
7901
f6144808
LP
7902 case 'c':
7903 arg_action = ACTION_CANCEL_SHUTDOWN;
7904 break;
7905
e4b61340
LP
7906 case '?':
7907 return -EINVAL;
7908
7909 default:
eb9da376 7910 assert_not_reached("Unhandled option");
e4b61340 7911 }
e4b61340 7912
dfcc5c33 7913 if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) {
2cc7b0a2 7914 r = parse_shutdown_time_spec(argv[optind], &arg_when);
7e59bfcb 7915 if (r < 0) {
f6144808
LP
7916 log_error("Failed to parse time specification: %s", argv[optind]);
7917 return r;
7918 }
6b5ad000 7919 } else
08e4b1c5 7920 arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE;
442b9094 7921
dfcc5c33
MS
7922 if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN)
7923 /* No time argument for shutdown cancel */
172d7abf 7924 wall = argv + optind;
dfcc5c33
MS
7925 else if (argc > optind + 1)
7926 /* We skip the time argument */
172d7abf
LP
7927 wall = argv + optind + 1;
7928
7929 if (wall) {
7930 arg_wall = strv_copy(wall);
7931 if (!arg_wall)
7932 return log_oom();
7933 }
e4b61340
LP
7934
7935 optind = argc;
7936
7937 return 1;
e4b61340
LP
7938}
7939
7940static int telinit_parse_argv(int argc, char *argv[]) {
e4b61340
LP
7941 enum {
7942 ARG_HELP = 0x100,
514f4ef5 7943 ARG_NO_WALL
e4b61340
LP
7944 };
7945
7946 static const struct option options[] = {
7947 { "help", no_argument, NULL, ARG_HELP },
514f4ef5 7948 { "no-wall", no_argument, NULL, ARG_NO_WALL },
eb9da376 7949 {}
e4b61340
LP
7950 };
7951
7952 static const struct {
7953 char from;
7954 enum action to;
7955 } table[] = {
7956 { '0', ACTION_POWEROFF },
7957 { '6', ACTION_REBOOT },
ef2f1067 7958 { '1', ACTION_RESCUE },
e4b61340
LP
7959 { '2', ACTION_RUNLEVEL2 },
7960 { '3', ACTION_RUNLEVEL3 },
7961 { '4', ACTION_RUNLEVEL4 },
7962 { '5', ACTION_RUNLEVEL5 },
7963 { 's', ACTION_RESCUE },
7964 { 'S', ACTION_RESCUE },
7965 { 'q', ACTION_RELOAD },
7966 { 'Q', ACTION_RELOAD },
7967 { 'u', ACTION_REEXEC },
7968 { 'U', ACTION_REEXEC }
7969 };
7970
7971 unsigned i;
7972 int c;
7973
7974 assert(argc >= 0);
7975 assert(argv);
7976
601185b4 7977 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
e4b61340
LP
7978 switch (c) {
7979
7980 case ARG_HELP:
601185b4
ZJS
7981 telinit_help();
7982 return 0;
e4b61340 7983
514f4ef5
LP
7984 case ARG_NO_WALL:
7985 arg_no_wall = true;
7986 break;
7987
e4b61340
LP
7988 case '?':
7989 return -EINVAL;
7990
7991 default:
eb9da376 7992 assert_not_reached("Unhandled option");
e4b61340 7993 }
e4b61340
LP
7994
7995 if (optind >= argc) {
691395d8 7996 log_error("%s: required argument missing.", program_invocation_short_name);
e4b61340
LP
7997 return -EINVAL;
7998 }
7999
8000 if (optind + 1 < argc) {
8001 log_error("Too many arguments.");
8002 return -EINVAL;
8003 }
8004
8005 if (strlen(argv[optind]) != 1) {
8006 log_error("Expected single character argument.");
8007 return -EINVAL;
8008 }
8009
8010 for (i = 0; i < ELEMENTSOF(table); i++)
8011 if (table[i].from == argv[optind][0])
8012 break;
8013
8014 if (i >= ELEMENTSOF(table)) {
b0193f1c 8015 log_error("Unknown command '%s'.", argv[optind]);
e4b61340
LP
8016 return -EINVAL;
8017 }
8018
8019 arg_action = table[i].to;
8020
313cefa1 8021 optind++;
e4b61340
LP
8022
8023 return 1;
8024}
8025
8026static int runlevel_parse_argv(int argc, char *argv[]) {
e4b61340
LP
8027 enum {
8028 ARG_HELP = 0x100,
8029 };
8030
8031 static const struct option options[] = {
8032 { "help", no_argument, NULL, ARG_HELP },
eb9da376 8033 {}
e4b61340
LP
8034 };
8035
8036 int c;
8037
8038 assert(argc >= 0);
8039 assert(argv);
8040
601185b4 8041 while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0)
e4b61340
LP
8042 switch (c) {
8043
8044 case ARG_HELP:
601185b4
ZJS
8045 runlevel_help();
8046 return 0;
e4b61340
LP
8047
8048 case '?':
8049 return -EINVAL;
8050
8051 default:
eb9da376 8052 assert_not_reached("Unhandled option");
e4b61340 8053 }
e4b61340
LP
8054
8055 if (optind < argc) {
8056 log_error("Too many arguments.");
8057 return -EINVAL;
8058 }
8059
8060 return 1;
8061}
8062
8063static int parse_argv(int argc, char *argv[]) {
8064 assert(argc >= 0);
8065 assert(argv);
8066
8067 if (program_invocation_short_name) {
8068
8069 if (strstr(program_invocation_short_name, "halt")) {
8070 arg_action = ACTION_HALT;
8071 return halt_parse_argv(argc, argv);
c54819ca 8072
e4b61340
LP
8073 } else if (strstr(program_invocation_short_name, "poweroff")) {
8074 arg_action = ACTION_POWEROFF;
8075 return halt_parse_argv(argc, argv);
c54819ca 8076
e4b61340 8077 } else if (strstr(program_invocation_short_name, "reboot")) {
5622dde3
KS
8078 if (kexec_loaded())
8079 arg_action = ACTION_KEXEC;
8080 else
8081 arg_action = ACTION_REBOOT;
e4b61340 8082 return halt_parse_argv(argc, argv);
c54819ca 8083
e4b61340
LP
8084 } else if (strstr(program_invocation_short_name, "shutdown")) {
8085 arg_action = ACTION_POWEROFF;
8086 return shutdown_parse_argv(argc, argv);
c54819ca 8087
e4b61340 8088 } else if (strstr(program_invocation_short_name, "init")) {
d5ca5f11 8089
c54819ca
LP
8090 /* Matches invocations as "init" as well as "telinit", which are synonymous when run as PID !=
8091 * 1 on SysV.
8092 *
8093 * On SysV "telinit" was the official command to communicate with PID 1, but "init" would
8094 * redirect itself to "telinit" if called with PID != 1. We follow the same logic here still,
8095 * though we add one level of indirection, as we implement "telinit" in "systemctl". Hence, for
8096 * us if you invoke "init" you get "systemd", but it will execve() "systemctl" immediately with
8097 * argv[] unmodified if PID is != 1. If you invoke "telinit" you directly get "systemctl". In
8098 * both cases we shall do the same thing, which is why we do strstr(p_i_s_n, "init") here, as a
8099 * quick way to match both.
8100 *
8101 * Also see redirect_telinit() in src/core/main.c. */
8102
d5ca5f11 8103 if (sd_booted() > 0) {
f459b602 8104 arg_action = _ACTION_INVALID;
d5ca5f11
LP
8105 return telinit_parse_argv(argc, argv);
8106 } else {
c54819ca
LP
8107 /* Hmm, so some other init system is running, we need to forward this request to
8108 * it. For now we simply guess that it is Upstart. */
d5ca5f11 8109
4ad61fd1 8110 execv(TELINIT, argv);
d5ca5f11
LP
8111
8112 log_error("Couldn't find an alternative telinit implementation to spawn.");
8113 return -EIO;
8114 }
8115
e4b61340
LP
8116 } else if (strstr(program_invocation_short_name, "runlevel")) {
8117 arg_action = ACTION_RUNLEVEL;
8118 return runlevel_parse_argv(argc, argv);
8119 }
8120 }
8121
8122 arg_action = ACTION_SYSTEMCTL;
8123 return systemctl_parse_argv(argc, argv);
8124}
8125
349cc4a5 8126#if HAVE_SYSV_COMPAT
44a6b1b6 8127_pure_ static int action_to_runlevel(void) {
eb22ac37
LP
8128 static const char table[_ACTION_MAX] = {
8129 [ACTION_HALT] = '0',
8130 [ACTION_POWEROFF] = '0',
8131 [ACTION_REBOOT] = '6',
8132 [ACTION_RUNLEVEL2] = '2',
8133 [ACTION_RUNLEVEL3] = '3',
8134 [ACTION_RUNLEVEL4] = '4',
8135 [ACTION_RUNLEVEL5] = '5',
8136 [ACTION_RESCUE] = '1'
8137 };
8138
78ca9099 8139 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
d55ae9e6
LP
8140
8141 return table[arg_action];
8142}
d2e79673 8143#endif
d55ae9e6 8144
d55ae9e6 8145static int talk_initctl(void) {
349cc4a5 8146#if HAVE_SYSV_COMPAT
cbc9fbd1
LP
8147 struct init_request request = {
8148 .magic = INIT_MAGIC,
8149 .sleeptime = 0,
8150 .cmd = INIT_CMD_RUNLVL
8151 };
8152
7fd1b19b 8153 _cleanup_close_ int fd = -1;
d55ae9e6 8154 char rl;
cbc9fbd1 8155 int r;
83c76e8c 8156 const char *p;
eb22ac37 8157
427b47c4
ZJS
8158 rl = action_to_runlevel();
8159 if (!rl)
eb22ac37
LP
8160 return 0;
8161
d55ae9e6
LP
8162 request.runlevel = rl;
8163
83c76e8c
MG
8164 FOREACH_STRING(p, "/run/initctl", "/dev/initctl") {
8165 fd = open(p, O_WRONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
8166 if (fd >= 0 || errno != ENOENT)
8167 break;
8168 }
427b47c4 8169 if (fd < 0) {
d55ae9e6
LP
8170 if (errno == ENOENT)
8171 return 0;
eb22ac37 8172
83c76e8c 8173 return log_error_errno(errno, "Failed to open initctl fifo: %m");
d55ae9e6 8174 }
eb22ac37 8175
553acb7b
ZJS
8176 r = loop_write(fd, &request, sizeof(request), false);
8177 if (r < 0)
83c76e8c 8178 return log_error_errno(r, "Failed to write to %s: %m", p);
eb22ac37
LP
8179
8180 return 1;
eca830be
LP
8181#else
8182 return 0;
8183#endif
e4b61340
LP
8184}
8185
e449de87 8186static int systemctl_main(int argc, char *argv[]) {
e449de87 8187 static const Verb verbs[] = {
c56d1e2c
CW
8188 { "list-units", VERB_ANY, VERB_ANY, VERB_DEFAULT|VERB_ONLINE_ONLY, list_units },
8189 { "list-unit-files", VERB_ANY, VERB_ANY, 0, list_unit_files },
8190 { "list-sockets", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_sockets },
8191 { "list-timers", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_timers },
8192 { "list-jobs", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, list_jobs },
8193 { "list-machines", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY|VERB_MUST_BE_ROOT, list_machines },
8194 { "clear-jobs", VERB_ANY, 1, VERB_ONLINE_ONLY, trivial_method },
8195 { "cancel", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, cancel_job },
8196 { "start", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8197 { "stop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8198 { "condstop", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8199 { "reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8200 { "restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8201 { "try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8202 { "reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8203 { "reload-or-try-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatbility with old systemctl <= 228 */
8204 { "try-reload-or-restart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit },
8205 { "force-reload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with SysV */
8206 { "condreload", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with ALTLinux */
8207 { "condrestart", 2, VERB_ANY, VERB_ONLINE_ONLY, start_unit }, /* For compatibility with RH */
8208 { "isolate", 2, 2, VERB_ONLINE_ONLY, start_unit },
8209 { "kill", 2, VERB_ANY, VERB_ONLINE_ONLY, kill_unit },
8210 { "is-active", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active },
3e7e587d 8211 { "check", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_active }, /* deprecated alias of is-active */
c56d1e2c
CW
8212 { "is-failed", 2, VERB_ANY, VERB_ONLINE_ONLY, check_unit_failed },
8213 { "show", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8214 { "cat", 2, VERB_ANY, VERB_ONLINE_ONLY, cat },
8215 { "status", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8216 { "help", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, show },
8217 { "daemon-reload", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8218 { "daemon-reexec", VERB_ANY, 1, VERB_ONLINE_ONLY, daemon_reload },
8219 { "show-environment", VERB_ANY, 1, VERB_ONLINE_ONLY, show_environment },
8220 { "set-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8221 { "unset-environment", 2, VERB_ANY, VERB_ONLINE_ONLY, set_environment },
8222 { "import-environment", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, import_environment },
8223 { "halt", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8224 { "poweroff", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8225 { "reboot", VERB_ANY, 2, VERB_ONLINE_ONLY, start_system_special },
8226 { "kexec", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8227 { "suspend", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8228 { "hibernate", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8229 { "hybrid-sleep", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
e68c79db 8230 { "suspend-then-hibernate",VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
c56d1e2c
CW
8231 { "default", VERB_ANY, 1, VERB_ONLINE_ONLY, start_special },
8232 { "rescue", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8233 { "emergency", VERB_ANY, 1, VERB_ONLINE_ONLY, start_system_special },
8234 { "exit", VERB_ANY, 2, VERB_ONLINE_ONLY, start_special },
8235 { "reset-failed", VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY, reset_failed },
8236 { "enable", 2, VERB_ANY, 0, enable_unit },
8237 { "disable", 2, VERB_ANY, 0, enable_unit },
8238 { "is-enabled", 2, VERB_ANY, 0, unit_is_enabled },
8239 { "reenable", 2, VERB_ANY, 0, enable_unit },
8240 { "preset", 2, VERB_ANY, 0, enable_unit },
8241 { "preset-all", VERB_ANY, 1, 0, preset_all },
8242 { "mask", 2, VERB_ANY, 0, enable_unit },
8243 { "unmask", 2, VERB_ANY, 0, enable_unit },
8244 { "link", 2, VERB_ANY, 0, enable_unit },
8245 { "revert", 2, VERB_ANY, 0, enable_unit },
8246 { "switch-root", 2, VERB_ANY, VERB_ONLINE_ONLY, switch_root },
8247 { "list-dependencies", VERB_ANY, 2, VERB_ONLINE_ONLY, list_dependencies },
8248 { "set-default", 2, 2, 0, set_default },
8249 { "get-default", VERB_ANY, 1, 0, get_default },
8250 { "set-property", 3, VERB_ANY, VERB_ONLINE_ONLY, set_property },
8251 { "is-system-running", VERB_ANY, 1, 0, is_system_running },
8252 { "add-wants", 3, VERB_ANY, 0, add_dependency },
8253 { "add-requires", 3, VERB_ANY, 0, add_dependency },
8254 { "edit", 2, VERB_ANY, VERB_ONLINE_ONLY, edit },
d08e75ed 8255 {}
e449de87 8256 };
7e4249b9 8257
e449de87 8258 return dispatch_verb(argc, argv, verbs, NULL);
e4b61340
LP
8259}
8260
4fbd7192 8261static int reload_with_fallback(void) {
4fbd7192 8262 /* First, try systemd via D-Bus. */
e449de87 8263 if (daemon_reload(0, NULL, NULL) >= 0)
4fbd7192 8264 return 0;
e4b61340
LP
8265
8266 /* Nothing else worked, so let's try signals */
2853b60a 8267 assert(IN_SET(arg_action, ACTION_RELOAD, ACTION_REEXEC));
e4b61340 8268
4a62c710
MS
8269 if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0)
8270 return log_error_errno(errno, "kill() failed: %m");
e4b61340
LP
8271
8272 return 0;
8273}
8274
4fbd7192 8275static int start_with_fallback(void) {
4fbd7192 8276 /* First, try systemd via D-Bus. */
e449de87 8277 if (start_unit(0, NULL, NULL) >= 0)
4fbd7192 8278 return 0;
e4b61340 8279
2853b60a 8280 /* Nothing else worked, so let's try /dev/initctl */
fbc43921 8281 if (talk_initctl() > 0)
48ec22bc 8282 return 0;
d55ae9e6
LP
8283
8284 log_error("Failed to talk to init daemon.");
8285 return -EIO;
e4b61340
LP
8286}
8287
477def80 8288static int halt_now(enum action a) {
c01dcddf
LP
8289 /* The kernel will automatically flush ATA disks and suchlike on reboot(), but the file systems need to be
8290 * synce'd explicitly in advance. */
1ae17672 8291 if (!arg_no_sync && !arg_dry_run)
f3f054f0 8292 (void) sync();
4a3ad399 8293
1ae17672
ZJS
8294 /* Make sure C-A-D is handled by the kernel from this point on... */
8295 if (!arg_dry_run)
8296 (void) reboot(RB_ENABLE_CAD);
e606bb61 8297
4c80c73c 8298 switch (a) {
e606bb61
LP
8299
8300 case ACTION_HALT:
60675884
LP
8301 if (!arg_quiet)
8302 log_info("Halting.");
1ae17672
ZJS
8303 if (arg_dry_run)
8304 return 0;
19578bb2 8305 (void) reboot(RB_HALT_SYSTEM);
477def80 8306 return -errno;
e606bb61
LP
8307
8308 case ACTION_POWEROFF:
60675884
LP
8309 if (!arg_quiet)
8310 log_info("Powering off.");
1ae17672
ZJS
8311 if (arg_dry_run)
8312 return 0;
19578bb2 8313 (void) reboot(RB_POWER_OFF);
477def80 8314 return -errno;
e606bb61 8315
98d52feb 8316 case ACTION_KEXEC:
c01dcddf
LP
8317 case ACTION_REBOOT:
8318 return reboot_with_parameter(REBOOT_FALLBACK |
8319 (arg_quiet ? 0 : REBOOT_LOG) |
8320 (arg_dry_run ? REBOOT_DRY_RUN : 0));
e606bb61 8321
477def80
LP
8322 default:
8323 assert_not_reached("Unknown action.");
8324 }
e606bb61
LP
8325}
8326
56a730fa
LP
8327static int logind_schedule_shutdown(void) {
8328
349cc4a5 8329#if ENABLE_LOGIND
4afd3348 8330 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
56a730fa
LP
8331 char date[FORMAT_TIMESTAMP_MAX];
8332 const char *action;
4fbd7192 8333 sd_bus *bus;
56a730fa
LP
8334 int r;
8335
4fbd7192 8336 r = acquire_bus(BUS_FULL, &bus);
56a730fa 8337 if (r < 0)
4fbd7192 8338 return r;
56a730fa
LP
8339
8340 switch (arg_action) {
8341 case ACTION_HALT:
8342 action = "halt";
8343 break;
8344 case ACTION_POWEROFF:
8345 action = "poweroff";
8346 break;
8347 case ACTION_KEXEC:
8348 action = "kexec";
8349 break;
a4420f7b
LP
8350 case ACTION_EXIT:
8351 action = "exit";
8352 break;
8353 case ACTION_REBOOT:
56a730fa
LP
8354 default:
8355 action = "reboot";
8356 break;
8357 }
8358
1ae17672 8359 if (arg_dry_run)
56a730fa
LP
8360 action = strjoina("dry-", action);
8361
d2ad7e1b
ZJS
8362 (void) logind_set_wall_message();
8363
56a730fa 8364 r = sd_bus_call_method(
4fbd7192 8365 bus,
56a730fa
LP
8366 "org.freedesktop.login1",
8367 "/org/freedesktop/login1",
8368 "org.freedesktop.login1.Manager",
8369 "ScheduleShutdown",
8370 &error,
8371 NULL,
8372 "st",
8373 action,
8374 arg_when);
8375 if (r < 0)
8376 return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r));
8377
60675884
LP
8378 if (!arg_quiet)
8379 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date, sizeof(date), arg_when));
56a730fa
LP
8380 return 0;
8381#else
8382 log_error("Cannot schedule shutdown without logind support, proceeding with immediate shutdown.");
8383 return -ENOSYS;
8384#endif
8385}
8386
4fbd7192 8387static int halt_main(void) {
e4b61340
LP
8388 int r;
8389
4fbd7192 8390 r = logind_check_inhibitors(arg_action);
748ebafa
LP
8391 if (r < 0)
8392 return r;
b37844d3 8393
7f96539d
LP
8394 if (arg_when > 0)
8395 return logind_schedule_shutdown();
8396
bc8c2f5c 8397 if (geteuid() != 0) {
1ae17672 8398 if (arg_dry_run || arg_force > 0) {
fba868fa 8399 (void) must_be_root();
2ac3930f
IS
8400 return -EPERM;
8401 }
8402
7e59bfcb
LP
8403 /* Try logind if we are a normal user and no special
8404 * mode applies. Maybe PolicyKit allows us to shutdown
8405 * the machine. */
36b69c31 8406 if (IN_SET(arg_action, ACTION_POWEROFF, ACTION_REBOOT, ACTION_HALT)) {
4fbd7192 8407 r = logind_reboot(arg_action);
4c80c73c
KS
8408 if (r >= 0)
8409 return r;
a9085ea3 8410 if (IN_SET(r, -EOPNOTSUPP, -EINPROGRESS))
7f96539d
LP
8411 /* requested operation is not
8412 * supported on the local system or
8413 * already in progress */
a9085ea3
IS
8414 return r;
8415 /* on all other errors, try low-level operation */
4c80c73c 8416 }
bc8c2f5c
LP
8417 }
8418
2955e0d4
GJ
8419 /* In order to minimize the difference between operation with and
8420 * without logind, we explicitly enable non-blocking mode for this,
8421 * as logind's shutdown operations are always non-blocking. */
8422 arg_no_block = true;
8423
1ae17672 8424 if (!arg_dry_run && !arg_force)
4fbd7192 8425 return start_with_fallback();
e4b61340 8426
2ac3930f
IS
8427 assert(geteuid() == 0);
8428
d90e1a30
LP
8429 if (!arg_no_wtmp) {
8430 if (sd_booted() > 0)
8431 log_debug("Not writing utmp record, assuming that systemd-update-utmp is used.");
7e59bfcb
LP
8432 else {
8433 r = utmp_put_shutdown();
8434 if (r < 0)
da927ba9 8435 log_warning_errno(r, "Failed to write utmp record: %m");
7e59bfcb 8436 }
d90e1a30 8437 }
e4b61340 8438
1ae17672 8439 if (arg_dry_run)
e4b61340
LP
8440 return 0;
8441
477def80 8442 r = halt_now(arg_action);
691395d8 8443 return log_error_errno(r, "Failed to reboot: %m");
e4b61340
LP
8444}
8445
8446static int runlevel_main(void) {
8447 int r, runlevel, previous;
8448
729e3769
LP
8449 r = utmp_get_runlevel(&runlevel, &previous);
8450 if (r < 0) {
8451 puts("unknown");
e4b61340
LP
8452 return r;
8453 }
8454
8455 printf("%c %c\n",
8456 previous <= 0 ? 'N' : previous,
8457 runlevel <= 0 ? 'N' : runlevel);
8458
8459 return 0;
8460}
8461
2cf05793 8462static int logind_cancel_shutdown(void) {
349cc4a5 8463#if ENABLE_LOGIND
4afd3348 8464 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4fbd7192 8465 sd_bus *bus;
949d9ce9
LP
8466 int r;
8467
4fbd7192 8468 r = acquire_bus(BUS_FULL, &bus);
949d9ce9 8469 if (r < 0)
4fbd7192 8470 return r;
949d9ce9 8471
4fbd7192 8472 (void) logind_set_wall_message();
949d9ce9
LP
8473
8474 r = sd_bus_call_method(
4fbd7192 8475 bus,
949d9ce9
LP
8476 "org.freedesktop.login1",
8477 "/org/freedesktop/login1",
8478 "org.freedesktop.login1.Manager",
8479 "CancelScheduledShutdown",
8480 &error,
8481 NULL, NULL);
8482 if (r < 0)
8483 return log_warning_errno(r, "Failed to talk to logind, shutdown hasn't been cancelled: %s", bus_error_message(&error, r));
8484
8485 return 0;
2cf05793
LP
8486#else
8487 log_error("Not compiled with logind support, cannot cancel scheduled shutdowns.");
8488 return -ENOSYS;
8489#endif
949d9ce9
LP
8490}
8491
e4b61340 8492int main(int argc, char*argv[]) {
f459b602 8493 int r;
e4b61340 8494
acc28e2e
FB
8495 argv_cmdline = argv[0];
8496
a9cdc94f 8497 setlocale(LC_ALL, "");
e4b61340 8498 log_parse_environment();
2396fb04 8499 log_open();
592705f2 8500 sigbus_install();
e4b61340 8501
184ecaf7
DR
8502 /* Explicitly not on_tty() to avoid setting cached value.
8503 * This becomes relevant for piping output which might be
8504 * ellipsized. */
8505 original_stdout_is_tty = isatty(STDOUT_FILENO);
8506
04ebb595 8507 r = parse_argv(argc, argv);
f459b602 8508 if (r <= 0)
e4b61340 8509 goto finish;
7e4249b9 8510
040524b4 8511 if (arg_action != ACTION_SYSTEMCTL && running_in_chroot() > 0) {
60675884
LP
8512
8513 if (!arg_quiet)
8514 log_info("Running in chroot, ignoring request.");
f459b602 8515 r = 0;
82e23ddd
LP
8516 goto finish;
8517 }
8518
41dd15e4
LP
8519 /* systemctl_main() will print an error message for the bus
8520 * connection, but only if it needs to */
e4b61340
LP
8521
8522 switch (arg_action) {
8523
22f4096c 8524 case ACTION_SYSTEMCTL:
e449de87 8525 r = systemctl_main(argc, argv);
e4b61340 8526 break;
e4b61340 8527
081dc638
AJ
8528 /* Legacy command aliases set arg_action. They provide some fallbacks,
8529 * e.g. to tell sysvinit to reboot after you have installed systemd
8530 * binaries. */
8531
e4b61340
LP
8532 case ACTION_HALT:
8533 case ACTION_POWEROFF:
8534 case ACTION_REBOOT:
5622dde3 8535 case ACTION_KEXEC:
4fbd7192 8536 r = halt_main();
e4b61340
LP
8537 break;
8538
e4b61340
LP
8539 case ACTION_RUNLEVEL2:
8540 case ACTION_RUNLEVEL3:
8541 case ACTION_RUNLEVEL4:
8542 case ACTION_RUNLEVEL5:
8543 case ACTION_RESCUE:
4fbd7192 8544 r = start_with_fallback();
e4b61340 8545 break;
7e4249b9 8546
e4b61340
LP
8547 case ACTION_RELOAD:
8548 case ACTION_REEXEC:
4fbd7192 8549 r = reload_with_fallback();
e4b61340
LP
8550 break;
8551
949d9ce9 8552 case ACTION_CANCEL_SHUTDOWN:
2cf05793 8553 r = logind_cancel_shutdown();
f6144808
LP
8554 break;
8555
eb22ac37 8556 case ACTION_RUNLEVEL:
4f16c1f4
LP
8557 r = runlevel_main();
8558 break;
8559
081dc638
AJ
8560 case ACTION_EXIT:
8561 case ACTION_SUSPEND:
8562 case ACTION_HIBERNATE:
8563 case ACTION_HYBRID_SLEEP:
e68c79db 8564 case ACTION_SUSPEND_THEN_HIBERNATE:
081dc638
AJ
8565 case ACTION_EMERGENCY:
8566 case ACTION_DEFAULT:
8567 /* systemctl verbs with no equivalent in the legacy commands.
8568 * These cannot appear in arg_action. Fall through. */
8569
f459b602 8570 case _ACTION_INVALID:
e4b61340
LP
8571 default:
8572 assert_not_reached("Unknown action");
8573 }
7e4249b9
LP
8574
8575finish:
cf647b69
LP
8576 release_busses();
8577
f459b602
MAP
8578 pager_close();
8579 ask_password_agent_close();
8580 polkit_agent_close();
7e4249b9 8581
20b3f379 8582 strv_free(arg_types);
9b9b3d36 8583 strv_free(arg_states);
20b3f379 8584 strv_free(arg_properties);
ea4a240d 8585
172d7abf 8586 strv_free(arg_wall);
0f03c2a4 8587 free(arg_root);
4bb2e9d4 8588 free(arg_esp_path);
172d7abf 8589
404f08d3 8590 /* Note that we return r here, not EXIT_SUCCESS, so that we can implement the LSB-like return codes */
9eb4a501 8591 return r < 0 ? EXIT_FAILURE : r;
7e4249b9 8592}