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