]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
build-sys: use #if Y instead of #ifdef Y everywhere
[thirdparty/systemd.git] / src / core / main.c
CommitLineData
a7334b09
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 14 Lesser General Public License for more details.
a7334b09 15
5430f7f2 16 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
60918275 20#include <errno.h>
3dfc9763 21#include <fcntl.h>
f170852a 22#include <getopt.h>
97c4f35c 23#include <signal.h>
3dfc9763
LP
24#include <stdio.h>
25#include <string.h>
664f88a7 26#include <sys/mount.h>
3dfc9763 27#include <sys/prctl.h>
b9e74c39 28#include <sys/reboot.h>
3dfc9763
LP
29#include <sys/stat.h>
30#include <unistd.h>
349cc4a5 31#if HAVE_SECCOMP
b64a3d86
LP
32#include <seccomp.h>
33#endif
349cc4a5 34#if HAVE_VALGRIND_VALGRIND_H
3dfc9763
LP
35#include <valgrind/valgrind.h>
36#endif
54b434b1 37
718db961 38#include "sd-bus.h"
cf0fbc49 39#include "sd-daemon.h"
3dfc9763 40
b5efdb8a 41#include "alloc-util.h"
d9d93745 42#include "architecture.h"
3dfc9763
LP
43#include "build.h"
44#include "bus-error.h"
45#include "bus-util.h"
430f0182 46#include "capability-util.h"
24efb112 47#include "clock-util.h"
3dfc9763 48#include "conf-parser.h"
618234a5 49#include "cpu-set-util.h"
3dfc9763
LP
50#include "dbus-manager.h"
51#include "def.h"
eee8b7ab 52#include "emergency-action.h"
3dfc9763 53#include "env-util.h"
3ffd4af2 54#include "fd-util.h"
3dfc9763 55#include "fdset.h"
718db961 56#include "fileio.h"
f97b34a6 57#include "format-util.h"
f4f15635 58#include "fs-util.h"
3dfc9763
LP
59#include "hostname-setup.h"
60#include "ima-setup.h"
61#include "killall.h"
62#include "kmod-setup.h"
d7b8eec7 63#include "load-fragment.h"
3dfc9763 64#include "log.h"
b6e66135 65#include "loopback-setup.h"
b6e66135 66#include "machine-id-setup.h"
3dfc9763
LP
67#include "manager.h"
68#include "missing.h"
69#include "mount-setup.h"
70#include "pager.h"
6bedfcbb 71#include "parse-util.h"
7d5ceb64 72#include "path-util.h"
4e731273 73#include "proc-cmdline.h"
3dfc9763 74#include "process-util.h"
8869a0b4 75#include "raw-clone.h"
78f22b97 76#include "rlimit-util.h"
349cc4a5 77#if HAVE_SECCOMP
83f12b27
FS
78#include "seccomp-util.h"
79#endif
b6e66135 80#include "selinux-setup.h"
3dfc9763
LP
81#include "selinux-util.h"
82#include "signal-util.h"
ffbd2c4d 83#include "smack-setup.h"
3dfc9763 84#include "special.h"
8fcde012 85#include "stat-util.h"
15a5e950 86#include "stdio-util.h"
3dfc9763
LP
87#include "strv.h"
88#include "switch-root.h"
89#include "terminal-util.h"
8612da97 90#include "umask-util.h"
b1d4f8e1 91#include "user-util.h"
3dfc9763
LP
92#include "virt.h"
93#include "watchdog.h"
b6e66135 94
f170852a
LP
95static enum {
96 ACTION_RUN,
e965d56d 97 ACTION_HELP,
9ba0bc4e 98 ACTION_VERSION,
e537352b 99 ACTION_TEST,
494294d6 100 ACTION_DUMP_CONFIGURATION_ITEMS
fa0f4d8a 101} arg_action = ACTION_RUN;
fa0f4d8a 102static char *arg_default_unit = NULL;
463d0d15 103static bool arg_system = false;
fa0f4d8a 104static bool arg_dump_core = true;
fa0f4d8a 105static int arg_crash_chvt = -1;
b9e74c39
LP
106static bool arg_crash_shell = false;
107static bool arg_crash_reboot = false;
7d5ceb64 108static char *arg_confirm_spawn = NULL;
b6e2f329 109static ShowStatus arg_show_status = _SHOW_STATUS_UNSET;
bf4df7c3 110static bool arg_switched_root = false;
ea4b98e6 111static bool arg_no_pager = false;
0c85a4f3 112static char ***arg_join_controllers = NULL;
706343f4 113static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
0a494f1f 114static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
1f19a534
OS
115static usec_t arg_default_restart_usec = DEFAULT_RESTART_USEC;
116static usec_t arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
117static usec_t arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
3f41e1e5
LN
118static usec_t arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
119static unsigned arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
e96d6be7
LP
120static usec_t arg_runtime_watchdog = 0;
121static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
97d0e5f8 122static char **arg_default_environment = NULL;
517d56b1 123static struct rlimit *arg_default_rlimit[_RLIMIT_MAX] = {};
a103496c 124static uint64_t arg_capability_bounding_set = CAP_ALL;
3a43da28 125static nsec_t arg_timer_slack_nsec = NSEC_INFINITY;
bd8f585b 126static usec_t arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
d3b1c508
LP
127static Set* arg_syscall_archs = NULL;
128static FILE* arg_serialization = NULL;
085afe36 129static bool arg_default_cpu_accounting = false;
13c31542 130static bool arg_default_io_accounting = false;
377bfd2d 131static bool arg_default_ip_accounting = false;
085afe36
LP
132static bool arg_default_blockio_accounting = false;
133static bool arg_default_memory_accounting = false;
9ded9cd1 134static bool arg_default_tasks_accounting = true;
79baeeb9 135static uint64_t arg_default_tasks_max = UINT64_MAX;
ee48dbd5 136static sd_id128_t arg_machine_id = {};
ae8c7939 137static EmergencyAction arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
4fc935ca 138
b9e74c39
LP
139noreturn static void freeze_or_reboot(void) {
140
141 if (arg_crash_reboot) {
142 log_notice("Rebooting in 10s...");
143 (void) sleep(10);
144
145 log_notice("Rebooting now...");
146 (void) reboot(RB_AUTOBOOT);
147 log_emergency_errno(errno, "Failed to reboot: %m");
148 }
149
150 log_emergency("Freezing execution.");
151 freeze();
152}
153
919ce0b7 154noreturn static void crash(int sig) {
7d06dad9
MS
155 struct sigaction sa;
156 pid_t pid;
97c4f35c 157
df0ff127 158 if (getpid_cached() != 1)
abb26902 159 /* Pass this on immediately, if this is not PID 1 */
92ca4cac 160 (void) raise(sig);
abb26902 161 else if (!arg_dump_core)
4104970e 162 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig));
97c4f35c 163 else {
7d06dad9 164 sa = (struct sigaction) {
189d5bac 165 .sa_handler = nop_signal_handler,
b92bea5d
ZJS
166 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
167 };
97c4f35c 168
6f5e3f35 169 /* We want to wait for the core process, hence let's enable SIGCHLD */
92ca4cac 170 (void) sigaction(SIGCHLD, &sa, NULL);
6f5e3f35 171
8869a0b4 172 pid = raw_clone(SIGCHLD);
e62d8c39 173 if (pid < 0)
56f64d95 174 log_emergency_errno(errno, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig));
97c4f35c 175 else if (pid == 0) {
97c4f35c 176 /* Enable default signal handler for core dump */
15a90032 177
92ca4cac
LP
178 sa = (struct sigaction) {
179 .sa_handler = SIG_DFL,
180 };
181 (void) sigaction(sig, &sa, NULL);
97c4f35c 182
15a90032
LP
183 /* Don't limit the coredump size */
184 (void) setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY));
97c4f35c
LP
185
186 /* Just to be sure... */
e62d9b81 187 (void) chdir("/");
97c4f35c
LP
188
189 /* Raise the signal again */
ee05e779 190 pid = raw_getpid();
92ca4cac 191 (void) kill(pid, sig); /* raise() would kill the parent */
97c4f35c
LP
192
193 assert_not_reached("We shouldn't be here...");
92ca4cac 194 _exit(EXIT_FAILURE);
4fc935ca 195 } else {
8e12a6ae
LP
196 siginfo_t status;
197 int r;
4fc935ca
LP
198
199 /* Order things nicely. */
e62d8c39
ZJS
200 r = wait_for_terminate(pid, &status);
201 if (r < 0)
da927ba9 202 log_emergency_errno(r, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig));
8e12a6ae 203 else if (status.si_code != CLD_DUMPED)
ee05e779
ZJS
204 log_emergency("Caught <%s>, core dump failed (child "PID_FMT", code=%s, status=%i/%s).",
205 signal_to_string(sig),
206 pid, sigchld_code_to_string(status.si_code),
207 status.si_status,
208 strna(status.si_code == CLD_EXITED
38107f5a 209 ? exit_status_to_string(status.si_status, EXIT_STATUS_MINIMAL)
ee05e779 210 : signal_to_string(status.si_status)));
4fc935ca 211 else
4104970e 212 log_emergency("Caught <%s>, dumped core as pid "PID_FMT".", signal_to_string(sig), pid);
97c4f35c
LP
213 }
214 }
215
b9e74c39 216 if (arg_crash_chvt >= 0)
92ca4cac 217 (void) chvt(arg_crash_chvt);
601f6a1e 218
7d06dad9
MS
219 sa = (struct sigaction) {
220 .sa_handler = SIG_IGN,
221 .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
222 };
223
224 /* Let the kernel reap children for us */
225 (void) sigaction(SIGCHLD, &sa, NULL);
8c43883a 226
7d06dad9 227 if (arg_crash_shell) {
b9e74c39 228 log_notice("Executing crash shell in 10s...");
92ca4cac 229 (void) sleep(10);
4fc935ca 230
8869a0b4 231 pid = raw_clone(SIGCHLD);
cd3bd60a 232 if (pid < 0)
56f64d95 233 log_emergency_errno(errno, "Failed to fork off crash shell: %m");
6f5e3f35 234 else if (pid == 0) {
b9e74c39 235 (void) setsid();
92ca4cac
LP
236 (void) make_console_stdio();
237 (void) execle("/bin/sh", "/bin/sh", NULL, environ);
6f5e3f35 238
ee05e779 239 log_emergency_errno(errno, "execle() failed: %m");
92ca4cac 240 _exit(EXIT_FAILURE);
b9e74c39
LP
241 } else {
242 log_info("Spawned crash shell as PID "PID_FMT".", pid);
4cf0b03b 243 (void) wait_for_terminate(pid, NULL);
b9e74c39 244 }
4fc935ca
LP
245 }
246
b9e74c39 247 freeze_or_reboot();
97c4f35c
LP
248}
249
250static void install_crash_handler(void) {
297d563d 251 static const struct sigaction sa = {
b92bea5d 252 .sa_handler = crash,
297d563d 253 .sa_flags = SA_NODEFER, /* So that we can raise the signal again from the signal handler */
b92bea5d 254 };
297d563d 255 int r;
97c4f35c 256
297d563d
LP
257 /* We ignore the return value here, since, we don't mind if we
258 * cannot set up a crash handler */
259 r = sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
260 if (r < 0)
261 log_debug_errno(r, "I had trouble setting up the crash handler, ignoring: %m");
97c4f35c 262}
f170852a 263
56d96fc0
LP
264static int console_setup(void) {
265 _cleanup_close_ int tty_fd = -1;
266 int r;
80876c20 267
512947d4 268 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
23bbb0de
MS
269 if (tty_fd < 0)
270 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
80876c20 271
56d96fc0
LP
272 /* We don't want to force text mode. plymouth may be showing
273 * pictures already from initrd. */
512947d4 274 r = reset_terminal_fd(tty_fd, false);
23bbb0de
MS
275 if (r < 0)
276 return log_error_errno(r, "Failed to reset /dev/console: %m");
843d2643 277
56d96fc0 278 return 0;
80876c20
LP
279}
280
b9e74c39
LP
281static int parse_crash_chvt(const char *value) {
282 int b;
283
284 if (safe_atoi(value, &arg_crash_chvt) >= 0)
285 return 0;
286
287 b = parse_boolean(value);
288 if (b < 0)
289 return b;
290
291 if (b > 0)
292 arg_crash_chvt = 0; /* switch to where kmsg goes */
293 else
294 arg_crash_chvt = -1; /* turn off switching */
295
296 return 0;
297}
298
7d5ceb64
FB
299static int parse_confirm_spawn(const char *value, char **console) {
300 char *s;
301 int r;
302
303 r = value ? parse_boolean(value) : 1;
304 if (r == 0) {
305 *console = NULL;
306 return 0;
307 }
308
309 if (r > 0) /* on with default tty */
310 s = strdup("/dev/console");
311 else if (is_path(value)) /* on with fully qualified path */
312 s = strdup(value);
313 else /* on with only a tty file name, not a fully qualified path */
314 s = strjoin("/dev/", value);
315 if (!s)
316 return -ENOMEM;
317 *console = s;
318 return 0;
319}
320
ee48dbd5 321static int set_machine_id(const char *m) {
e042eab7 322 sd_id128_t t;
8b26cdbd 323 assert(m);
ee48dbd5 324
e042eab7 325 if (sd_id128_from_string(m, &t) < 0)
ee48dbd5
NC
326 return -EINVAL;
327
e042eab7 328 if (sd_id128_is_null(t))
ee48dbd5
NC
329 return -EINVAL;
330
e042eab7 331 arg_machine_id = t;
ee48dbd5
NC
332 return 0;
333}
334
96287a49 335static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
f170852a 336
059cb385 337 int r;
f170852a 338
059cb385 339 assert(key);
5192bd19 340
1d84ad94 341 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
bf4df7c3 342
1d84ad94
LP
343 if (proc_cmdline_value_missing(key, value))
344 return 0;
bf4df7c3 345
1d84ad94
LP
346 if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
347 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value);
348 else if (in_initrd() == !!startswith(key, "rd.")) {
349 if (free_and_strdup(&arg_default_unit, value) < 0)
350 return log_oom();
351 }
f170852a 352
1d84ad94 353 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
4fc935ca 354
1d84ad94 355 r = value ? parse_boolean(value) : true;
fb472900 356 if (r < 0)
059cb385 357 log_warning("Failed to parse dump core switch %s. Ignoring.", value);
4fc935ca 358 else
fa0f4d8a 359 arg_dump_core = r;
4fc935ca 360
1d84ad94 361 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
b9e74c39 362
1d84ad94
LP
363 if (!value)
364 arg_crash_chvt = 0; /* turn on */
365 else if (parse_crash_chvt(value) < 0)
b9e74c39
LP
366 log_warning("Failed to parse crash chvt switch %s. Ignoring.", value);
367
1d84ad94 368 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
4fc935ca 369
1d84ad94 370 r = value ? parse_boolean(value) : true;
fb472900 371 if (r < 0)
059cb385 372 log_warning("Failed to parse crash shell switch %s. Ignoring.", value);
4fc935ca 373 else
fa0f4d8a 374 arg_crash_shell = r;
5e7ee61c 375
1d84ad94 376 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
5e7ee61c 377
1d84ad94 378 r = value ? parse_boolean(value) : true;
b9e74c39
LP
379 if (r < 0)
380 log_warning("Failed to parse crash reboot switch %s. Ignoring.", value);
5e7ee61c 381 else
b9e74c39 382 arg_crash_reboot = r;
5e7ee61c 383
1d84ad94
LP
384 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
385 char *s;
7d5ceb64 386
1d84ad94 387 r = parse_confirm_spawn(value, &s);
059cb385 388 if (r < 0)
7d5ceb64 389 log_warning_errno(r, "Failed to parse confirm_spawn switch %s. Ignoring.", value);
1d84ad94
LP
390 else {
391 free(arg_confirm_spawn);
392 arg_confirm_spawn = s;
393 }
601f6a1e 394
1d84ad94 395 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
9e58ff9c 396
1d84ad94
LP
397 if (value) {
398 r = parse_show_status(value, &arg_show_status);
399 if (r < 0)
400 log_warning("Failed to parse show status switch %s. Ignoring.", value);
401 } else
402 arg_show_status = SHOW_STATUS_YES;
059cb385 403
1d84ad94
LP
404 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
405
406 if (proc_cmdline_value_missing(key, value))
407 return 0;
0a494f1f 408
059cb385 409 r = exec_output_from_string(value);
fb472900 410 if (r < 0)
059cb385 411 log_warning("Failed to parse default standard output switch %s. Ignoring.", value);
0a494f1f
LP
412 else
413 arg_default_std_output = r;
0a494f1f 414
1d84ad94
LP
415 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
416
417 if (proc_cmdline_value_missing(key, value))
418 return 0;
059cb385
LP
419
420 r = exec_output_from_string(value);
fb472900 421 if (r < 0)
059cb385 422 log_warning("Failed to parse default standard error switch %s. Ignoring.", value);
0a494f1f
LP
423 else
424 arg_default_std_error = r;
9e7c5357 425
1d84ad94
LP
426 } else if (streq(key, "systemd.setenv")) {
427
428 if (proc_cmdline_value_missing(key, value))
429 return 0;
059cb385
LP
430
431 if (env_assignment_is_valid(value)) {
e21fea24
KS
432 char **env;
433
059cb385 434 env = strv_env_set(arg_default_environment, value);
1d84ad94
LP
435 if (!env)
436 return log_oom();
437
438 arg_default_environment = env;
e21fea24 439 } else
059cb385 440 log_warning("Environment variable name '%s' is not valid. Ignoring.", value);
9e58ff9c 441
1d84ad94
LP
442 } else if (proc_cmdline_key_streq(key, "systemd.machine_id")) {
443
444 if (proc_cmdline_value_missing(key, value))
445 return 0;
446
447 r = set_machine_id(value);
448 if (r < 0)
449 log_warning("MachineID '%s' is not valid. Ignoring.", value);
ee48dbd5 450
1d84ad94
LP
451 } else if (proc_cmdline_key_streq(key, "systemd.default_timeout_start_sec")) {
452
453 if (proc_cmdline_value_missing(key, value))
454 return 0;
455
456 r = parse_sec(value, &arg_default_timeout_start_usec);
457 if (r < 0)
458 log_warning_errno(r, "Failed to parse default start timeout: %s, ignoring.", value);
459
460 if (arg_default_timeout_start_usec <= 0)
461 arg_default_timeout_start_usec = USEC_INFINITY;
ee48dbd5 462
059cb385 463 } else if (streq(key, "quiet") && !value) {
d7b15e0a 464
b6e2f329 465 if (arg_show_status == _SHOW_STATUS_UNSET)
d450b6f2 466 arg_show_status = SHOW_STATUS_AUTO;
059cb385
LP
467
468 } else if (streq(key, "debug") && !value) {
d7b15e0a 469
1de1c9c3
LP
470 /* Note that log_parse_environment() handles 'debug'
471 * too, and sets the log level to LOG_DEBUG. */
d7b15e0a 472
75f86906 473 if (detect_container() > 0)
b2103dcc 474 log_set_target(LOG_TARGET_CONSOLE);
059cb385 475
dcd61450 476 } else if (!value) {
e2c9a131 477 const char *target;
f170852a
LP
478
479 /* SysV compatibility */
e2c9a131
EV
480 target = runlevel_to_target(key);
481 if (target)
482 return free_and_strdup(&arg_default_unit, target);
f170852a
LP
483 }
484
485 return 0;
486}
487
e8e581bf
ZJS
488#define DEFINE_SETTER(name, func, descr) \
489 static int name(const char *unit, \
490 const char *filename, \
491 unsigned line, \
492 const char *section, \
71a61510 493 unsigned section_line, \
e8e581bf
ZJS
494 const char *lvalue, \
495 int ltype, \
496 const char *rvalue, \
497 void *data, \
498 void *userdata) { \
499 \
500 int r; \
501 \
502 assert(filename); \
503 assert(lvalue); \
504 assert(rvalue); \
505 \
506 r = func(rvalue); \
507 if (r < 0) \
d1cefe0a
LP
508 log_syntax(unit, LOG_ERR, filename, line, r, \
509 "Invalid " descr "'%s': %m", \
510 rvalue); \
e8e581bf
ZJS
511 \
512 return 0; \
513 }
487393e9 514
e8e581bf
ZJS
515DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level")
516DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target")
517DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" )
518DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location")
487393e9 519
4d7213b2
LP
520static int config_parse_cpu_affinity2(
521 const char *unit,
522 const char *filename,
523 unsigned line,
524 const char *section,
525 unsigned section_line,
526 const char *lvalue,
527 int ltype,
528 const char *rvalue,
529 void *data,
530 void *userdata) {
487393e9 531
4b40bc38 532 _cleanup_cpu_free_ cpu_set_t *c = NULL;
f5c72b73 533 int ncpus;
487393e9 534
765d143b 535 ncpus = parse_cpu_set_and_warn(rvalue, &c, unit, filename, line, lvalue);
f5c72b73
FB
536 if (ncpus < 0)
537 return ncpus;
487393e9 538
f5c72b73 539 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
25f027c5 540 log_warning_errno(errno, "Failed to set CPU affinity: %m");
487393e9 541
487393e9
LP
542 return 0;
543}
544
4d7213b2
LP
545static int config_parse_show_status(
546 const char* unit,
547 const char *filename,
548 unsigned line,
549 const char *section,
550 unsigned section_line,
551 const char *lvalue,
552 int ltype,
553 const char *rvalue,
554 void *data,
555 void *userdata) {
556
557 int k;
558 ShowStatus *b = data;
559
560 assert(filename);
561 assert(lvalue);
562 assert(rvalue);
563 assert(data);
564
565 k = parse_show_status(rvalue, b);
566 if (k < 0) {
12ca818f 567 log_syntax(unit, LOG_ERR, filename, line, k, "Failed to parse show status setting, ignoring: %s", rvalue);
4d7213b2
LP
568 return 0;
569 }
570
571 return 0;
572}
573
b9e74c39
LP
574static int config_parse_crash_chvt(
575 const char* unit,
576 const char *filename,
577 unsigned line,
578 const char *section,
579 unsigned section_line,
580 const char *lvalue,
581 int ltype,
582 const char *rvalue,
583 void *data,
584 void *userdata) {
585
586 int r;
587
588 assert(filename);
589 assert(lvalue);
590 assert(rvalue);
b9e74c39
LP
591
592 r = parse_crash_chvt(rvalue);
593 if (r < 0) {
594 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse CrashChangeVT= setting, ignoring: %s", rvalue);
595 return 0;
596 }
597
598 return 0;
599}
600
e8e581bf
ZJS
601static int config_parse_join_controllers(const char *unit,
602 const char *filename,
603 unsigned line,
604 const char *section,
71a61510 605 unsigned section_line,
e8e581bf
ZJS
606 const char *lvalue,
607 int ltype,
608 const char *rvalue,
609 void *data,
610 void *userdata) {
0c85a4f3 611
3875c85b 612 const char *whole_rvalue = rvalue;
0c85a4f3 613 unsigned n = 0;
0c85a4f3
LP
614
615 assert(filename);
616 assert(lvalue);
617 assert(rvalue);
618
fe382237 619 arg_join_controllers = strv_free_free(arg_join_controllers);
0c85a4f3 620
d4ebeb4f
FB
621 for (;;) {
622 _cleanup_free_ char *word = NULL;
623 char **l;
624 int r;
0c85a4f3 625
9a82ab95 626 r = extract_first_word(&rvalue, &word, NULL, EXTRACT_QUOTES);
3875c85b
FB
627 if (r < 0) {
628 log_syntax(unit, LOG_ERR, filename, line, r, "Invalid value for %s: %s", lvalue, whole_rvalue);
d4ebeb4f 629 return r;
3875c85b 630 }
d4ebeb4f
FB
631 if (r == 0)
632 break;
0c85a4f3 633
d4ebeb4f 634 l = strv_split(word, ",");
1592ec21 635 if (!l)
aa8aeac0 636 return log_oom();
0c85a4f3
LP
637 strv_uniq(l);
638
639 if (strv_length(l) <= 1) {
640 strv_free(l);
641 continue;
642 }
643
644 if (!arg_join_controllers) {
645 arg_join_controllers = new(char**, 2);
646 if (!arg_join_controllers) {
647 strv_free(l);
14212119 648 return log_oom();
0c85a4f3
LP
649 }
650
651 arg_join_controllers[0] = l;
652 arg_join_controllers[1] = NULL;
653
654 n = 1;
655 } else {
656 char ***a;
657 char ***t;
658
659 t = new0(char**, n+2);
660 if (!t) {
661 strv_free(l);
14212119 662 return log_oom();
0c85a4f3
LP
663 }
664
665 n = 0;
666
667 for (a = arg_join_controllers; *a; a++) {
668
669 if (strv_overlap(*a, l)) {
e287086b 670 if (strv_extend_strv(&l, *a, false) < 0) {
0c85a4f3
LP
671 strv_free(l);
672 strv_free_free(t);
14212119 673 return log_oom();
0c85a4f3
LP
674 }
675
0c85a4f3
LP
676 } else {
677 char **c;
678
679 c = strv_copy(*a);
680 if (!c) {
681 strv_free(l);
682 strv_free_free(t);
14212119 683 return log_oom();
0c85a4f3
LP
684 }
685
686 t[n++] = c;
687 }
688 }
689
690 t[n++] = strv_uniq(l);
691
692 strv_free_free(arg_join_controllers);
693 arg_join_controllers = t;
694 }
695 }
d4ebeb4f 696 if (!isempty(rvalue))
12ca818f 697 log_syntax(unit, LOG_ERR, filename, line, 0, "Trailing garbage, ignoring.");
0c85a4f3
LP
698
699 return 0;
700}
701
487393e9
LP
702static int parse_config_file(void) {
703
f975e971 704 const ConfigTableItem items[] = {
d3b1c508
LP
705 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
706 { "Manager", "LogTarget", config_parse_target, 0, NULL },
707 { "Manager", "LogColor", config_parse_color, 0, NULL },
708 { "Manager", "LogLocation", config_parse_location, 0, NULL },
709 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
b9e74c39
LP
710 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt, 0, NULL },
711 { "Manager", "CrashChangeVT", config_parse_crash_chvt, 0, NULL },
d3b1c508 712 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
b9e74c39 713 { "Manager", "CrashReboot", config_parse_bool, 0, &arg_crash_reboot },
d3b1c508 714 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
d3b1c508
LP
715 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
716 { "Manager", "JoinControllers", config_parse_join_controllers, 0, &arg_join_controllers },
717 { "Manager", "RuntimeWatchdogSec", config_parse_sec, 0, &arg_runtime_watchdog },
718 { "Manager", "ShutdownWatchdogSec", config_parse_sec, 0, &arg_shutdown_watchdog },
a103496c 719 { "Manager", "CapabilityBoundingSet", config_parse_capability_set, 0, &arg_capability_bounding_set },
349cc4a5 720#if HAVE_SECCOMP
d3b1c508 721 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
89fffa27 722#endif
d3b1c508 723 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
bd8f585b 724 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_default_timer_accuracy_usec },
d3b1c508
LP
725 { "Manager", "DefaultStandardOutput", config_parse_output, 0, &arg_default_std_output },
726 { "Manager", "DefaultStandardError", config_parse_output, 0, &arg_default_std_error },
727 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_default_timeout_start_usec },
728 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_default_timeout_stop_usec },
729 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_default_restart_usec },
f0367da7
LP
730 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_default_start_limit_interval }, /* obsolete alias */
731 { "Manager", "DefaultStartLimitIntervalSec",config_parse_sec, 0, &arg_default_start_limit_interval },
d3b1c508
LP
732 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_default_start_limit_burst },
733 { "Manager", "DefaultEnvironment", config_parse_environ, 0, &arg_default_environment },
d0a7c5f6
LP
734 { "Manager", "DefaultLimitCPU", config_parse_limit, RLIMIT_CPU, arg_default_rlimit },
735 { "Manager", "DefaultLimitFSIZE", config_parse_limit, RLIMIT_FSIZE, arg_default_rlimit },
736 { "Manager", "DefaultLimitDATA", config_parse_limit, RLIMIT_DATA, arg_default_rlimit },
737 { "Manager", "DefaultLimitSTACK", config_parse_limit, RLIMIT_STACK, arg_default_rlimit },
738 { "Manager", "DefaultLimitCORE", config_parse_limit, RLIMIT_CORE, arg_default_rlimit },
739 { "Manager", "DefaultLimitRSS", config_parse_limit, RLIMIT_RSS, arg_default_rlimit },
740 { "Manager", "DefaultLimitNOFILE", config_parse_limit, RLIMIT_NOFILE, arg_default_rlimit },
741 { "Manager", "DefaultLimitAS", config_parse_limit, RLIMIT_AS, arg_default_rlimit },
742 { "Manager", "DefaultLimitNPROC", config_parse_limit, RLIMIT_NPROC, arg_default_rlimit },
743 { "Manager", "DefaultLimitMEMLOCK", config_parse_limit, RLIMIT_MEMLOCK, arg_default_rlimit },
744 { "Manager", "DefaultLimitLOCKS", config_parse_limit, RLIMIT_LOCKS, arg_default_rlimit },
745 { "Manager", "DefaultLimitSIGPENDING", config_parse_limit, RLIMIT_SIGPENDING, arg_default_rlimit },
746 { "Manager", "DefaultLimitMSGQUEUE", config_parse_limit, RLIMIT_MSGQUEUE, arg_default_rlimit },
747 { "Manager", "DefaultLimitNICE", config_parse_limit, RLIMIT_NICE, arg_default_rlimit },
748 { "Manager", "DefaultLimitRTPRIO", config_parse_limit, RLIMIT_RTPRIO, arg_default_rlimit },
749 { "Manager", "DefaultLimitRTTIME", config_parse_limit, RLIMIT_RTTIME, arg_default_rlimit },
085afe36 750 { "Manager", "DefaultCPUAccounting", config_parse_bool, 0, &arg_default_cpu_accounting },
13c31542 751 { "Manager", "DefaultIOAccounting", config_parse_bool, 0, &arg_default_io_accounting },
377bfd2d 752 { "Manager", "DefaultIPAccounting", config_parse_bool, 0, &arg_default_ip_accounting },
085afe36
LP
753 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_default_blockio_accounting },
754 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_default_memory_accounting },
03a7b521 755 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_default_tasks_accounting },
0af20ea2 756 { "Manager", "DefaultTasksMax", config_parse_tasks_max, 0, &arg_default_tasks_max },
ae8c7939 757 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action, 0, &arg_cad_burst_action },
d3b1c508 758 {}
487393e9
LP
759 };
760
1b907b5c 761 const char *fn, *conf_dirs_nulstr;
487393e9 762
463d0d15 763 fn = arg_system ?
75eb6154
LP
764 PKGSYSCONFDIR "/system.conf" :
765 PKGSYSCONFDIR "/user.conf";
766
463d0d15 767 conf_dirs_nulstr = arg_system ?
75eb6154
LP
768 CONF_PATHS_NULSTR("systemd/system.conf.d") :
769 CONF_PATHS_NULSTR("systemd/user.conf.d");
770
43688c49 771 config_parse_many_nulstr(fn, conf_dirs_nulstr, "Manager\0", config_item_table_lookup, items, false, NULL);
36c16a7c
LP
772
773 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
774 * like everywhere else. */
775 if (arg_default_timeout_start_usec <= 0)
776 arg_default_timeout_start_usec = USEC_INFINITY;
777 if (arg_default_timeout_stop_usec <= 0)
778 arg_default_timeout_stop_usec = USEC_INFINITY;
487393e9 779
487393e9
LP
780 return 0;
781}
782
06af2a04
TB
783static void manager_set_defaults(Manager *m) {
784
785 assert(m);
786
787 m->default_timer_accuracy_usec = arg_default_timer_accuracy_usec;
788 m->default_std_output = arg_default_std_output;
789 m->default_std_error = arg_default_std_error;
790 m->default_timeout_start_usec = arg_default_timeout_start_usec;
791 m->default_timeout_stop_usec = arg_default_timeout_stop_usec;
792 m->default_restart_usec = arg_default_restart_usec;
793 m->default_start_limit_interval = arg_default_start_limit_interval;
794 m->default_start_limit_burst = arg_default_start_limit_burst;
795 m->default_cpu_accounting = arg_default_cpu_accounting;
13c31542 796 m->default_io_accounting = arg_default_io_accounting;
377bfd2d 797 m->default_ip_accounting = arg_default_ip_accounting;
06af2a04
TB
798 m->default_blockio_accounting = arg_default_blockio_accounting;
799 m->default_memory_accounting = arg_default_memory_accounting;
03a7b521 800 m->default_tasks_accounting = arg_default_tasks_accounting;
0af20ea2 801 m->default_tasks_max = arg_default_tasks_max;
06af2a04
TB
802
803 manager_set_default_rlimits(m, arg_default_rlimit);
804 manager_environment_add(m, NULL, arg_default_environment);
805}
806
f170852a
LP
807static int parse_argv(int argc, char *argv[]) {
808
809 enum {
810 ARG_LOG_LEVEL = 0x100,
811 ARG_LOG_TARGET,
bbe63281
LP
812 ARG_LOG_COLOR,
813 ARG_LOG_LOCATION,
2f198e2f 814 ARG_UNIT,
edb9aaa8 815 ARG_SYSTEM,
af2d49f7 816 ARG_USER,
e537352b 817 ARG_TEST,
b87c2aa6 818 ARG_NO_PAGER,
9ba0bc4e 819 ARG_VERSION,
80876c20 820 ARG_DUMP_CONFIGURATION_ITEMS,
9e58ff9c 821 ARG_DUMP_CORE,
b9e74c39 822 ARG_CRASH_CHVT,
9e58ff9c 823 ARG_CRASH_SHELL,
b9e74c39 824 ARG_CRASH_REBOOT,
a16e1123 825 ARG_CONFIRM_SPAWN,
9e58ff9c 826 ARG_SHOW_STATUS,
4288f619 827 ARG_DESERIALIZE,
2660882b 828 ARG_SWITCHED_ROOT,
0a494f1f 829 ARG_DEFAULT_STD_OUTPUT,
ee48dbd5
NC
830 ARG_DEFAULT_STD_ERROR,
831 ARG_MACHINE_ID
f170852a
LP
832 };
833
834 static const struct option options[] = {
a16e1123
LP
835 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
836 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
bbe63281
LP
837 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
838 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
2f198e2f 839 { "unit", required_argument, NULL, ARG_UNIT },
edb9aaa8 840 { "system", no_argument, NULL, ARG_SYSTEM },
af2d49f7 841 { "user", no_argument, NULL, ARG_USER },
a16e1123 842 { "test", no_argument, NULL, ARG_TEST },
b87c2aa6 843 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
a16e1123 844 { "help", no_argument, NULL, 'h' },
9ba0bc4e 845 { "version", no_argument, NULL, ARG_VERSION },
a16e1123 846 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
a5d87bf0 847 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
b9e74c39 848 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
a5d87bf0 849 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
b9e74c39 850 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
a5d87bf0 851 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
6e98720f 852 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
a16e1123 853 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
2660882b 854 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
0a494f1f
LP
855 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
856 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
ee48dbd5 857 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
fb472900 858 {}
f170852a
LP
859 };
860
861 int c, r;
862
863 assert(argc >= 1);
864 assert(argv);
865
df0ff127 866 if (getpid_cached() == 1)
b770165a
LP
867 opterr = 0;
868
099663ff 869 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
f170852a
LP
870
871 switch (c) {
872
873 case ARG_LOG_LEVEL:
fb472900
ZJS
874 r = log_set_max_level_from_string(optarg);
875 if (r < 0) {
f170852a
LP
876 log_error("Failed to parse log level %s.", optarg);
877 return r;
878 }
879
880 break;
881
882 case ARG_LOG_TARGET:
fb472900
ZJS
883 r = log_set_target_from_string(optarg);
884 if (r < 0) {
f170852a
LP
885 log_error("Failed to parse log target %s.", optarg);
886 return r;
887 }
888
889 break;
890
bbe63281
LP
891 case ARG_LOG_COLOR:
892
d0b170c8 893 if (optarg) {
fb472900
ZJS
894 r = log_show_color_from_string(optarg);
895 if (r < 0) {
d0b170c8
LP
896 log_error("Failed to parse log color setting %s.", optarg);
897 return r;
898 }
899 } else
900 log_show_color(true);
bbe63281
LP
901
902 break;
903
904 case ARG_LOG_LOCATION:
d0b170c8 905 if (optarg) {
fb472900
ZJS
906 r = log_show_location_from_string(optarg);
907 if (r < 0) {
d0b170c8
LP
908 log_error("Failed to parse log location setting %s.", optarg);
909 return r;
910 }
911 } else
912 log_show_location(true);
bbe63281
LP
913
914 break;
915
0a494f1f 916 case ARG_DEFAULT_STD_OUTPUT:
fb472900
ZJS
917 r = exec_output_from_string(optarg);
918 if (r < 0) {
0a494f1f
LP
919 log_error("Failed to parse default standard output setting %s.", optarg);
920 return r;
921 } else
922 arg_default_std_output = r;
923 break;
924
925 case ARG_DEFAULT_STD_ERROR:
fb472900
ZJS
926 r = exec_output_from_string(optarg);
927 if (r < 0) {
0a494f1f
LP
928 log_error("Failed to parse default standard error output setting %s.", optarg);
929 return r;
930 } else
931 arg_default_std_error = r;
932 break;
933
2f198e2f 934 case ARG_UNIT:
e6e242ad 935 r = free_and_strdup(&arg_default_unit, optarg);
23bbb0de
MS
936 if (r < 0)
937 return log_error_errno(r, "Failed to set default unit %s: %m", optarg);
f170852a
LP
938
939 break;
940
edb9aaa8 941 case ARG_SYSTEM:
463d0d15 942 arg_system = true;
edb9aaa8 943 break;
a5dab5ce 944
af2d49f7 945 case ARG_USER:
463d0d15 946 arg_system = false;
a5dab5ce 947 break;
a5dab5ce 948
e965d56d 949 case ARG_TEST:
fa0f4d8a 950 arg_action = ACTION_TEST;
b87c2aa6
ZJS
951 break;
952
953 case ARG_NO_PAGER:
954 arg_no_pager = true;
e965d56d
LP
955 break;
956
9ba0bc4e
ZJS
957 case ARG_VERSION:
958 arg_action = ACTION_VERSION;
959 break;
960
e537352b 961 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 962 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
963 break;
964
9e58ff9c 965 case ARG_DUMP_CORE:
b9e74c39
LP
966 if (!optarg)
967 arg_dump_core = true;
968 else {
969 r = parse_boolean(optarg);
970 if (r < 0)
971 return log_error_errno(r, "Failed to parse dump core boolean: %s", optarg);
972 arg_dump_core = r;
a5d87bf0 973 }
b9e74c39
LP
974 break;
975
976 case ARG_CRASH_CHVT:
977 r = parse_crash_chvt(optarg);
978 if (r < 0)
979 return log_error_errno(r, "Failed to parse crash virtual terminal index: %s", optarg);
9e58ff9c
LP
980 break;
981
982 case ARG_CRASH_SHELL:
b9e74c39
LP
983 if (!optarg)
984 arg_crash_shell = true;
985 else {
986 r = parse_boolean(optarg);
987 if (r < 0)
988 return log_error_errno(r, "Failed to parse crash shell boolean: %s", optarg);
989 arg_crash_shell = r;
990 }
991 break;
992
993 case ARG_CRASH_REBOOT:
994 if (!optarg)
995 arg_crash_reboot = true;
996 else {
997 r = parse_boolean(optarg);
998 if (r < 0)
999 return log_error_errno(r, "Failed to parse crash shell boolean: %s", optarg);
1000 arg_crash_reboot = r;
a5d87bf0 1001 }
9e58ff9c
LP
1002 break;
1003
80876c20 1004 case ARG_CONFIRM_SPAWN:
7d5ceb64
FB
1005 arg_confirm_spawn = mfree(arg_confirm_spawn);
1006
1007 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
1008 if (r < 0)
1009 return log_error_errno(r, "Failed to parse confirm spawn option: %m");
80876c20
LP
1010 break;
1011
9e58ff9c 1012 case ARG_SHOW_STATUS:
d450b6f2
ZJS
1013 if (optarg) {
1014 r = parse_show_status(optarg, &arg_show_status);
1015 if (r < 0) {
1016 log_error("Failed to parse show status boolean %s.", optarg);
1017 return r;
1018 }
1019 } else
1020 arg_show_status = SHOW_STATUS_YES;
6e98720f 1021 break;
a5d87bf0 1022
a16e1123
LP
1023 case ARG_DESERIALIZE: {
1024 int fd;
1025 FILE *f;
1026
01e10de3
LP
1027 r = safe_atoi(optarg, &fd);
1028 if (r < 0 || fd < 0) {
a16e1123 1029 log_error("Failed to parse deserialize option %s.", optarg);
b9e74c39 1030 return -EINVAL;
a16e1123
LP
1031 }
1032
b9e74c39 1033 (void) fd_cloexec(fd, true);
01e10de3
LP
1034
1035 f = fdopen(fd, "r");
4a62c710
MS
1036 if (!f)
1037 return log_error_errno(errno, "Failed to open serialization fd: %m");
a16e1123 1038
74ca738f 1039 safe_fclose(arg_serialization);
d3b1c508 1040 arg_serialization = f;
a16e1123
LP
1041
1042 break;
1043 }
1044
2660882b 1045 case ARG_SWITCHED_ROOT:
bf4df7c3 1046 arg_switched_root = true;
d03bc1b8
HH
1047 break;
1048
ee48dbd5
NC
1049 case ARG_MACHINE_ID:
1050 r = set_machine_id(optarg);
54500613
LP
1051 if (r < 0)
1052 return log_error_errno(r, "MachineID '%s' is not valid.", optarg);
ee48dbd5
NC
1053 break;
1054
f170852a 1055 case 'h':
fa0f4d8a 1056 arg_action = ACTION_HELP;
f170852a
LP
1057 break;
1058
1d2e23ab
LP
1059 case 'D':
1060 log_set_max_level(LOG_DEBUG);
1061 break;
1062
099663ff
LP
1063 case 'b':
1064 case 's':
1065 case 'z':
1066 /* Just to eat away the sysvinit kernel
1067 * cmdline args without getopt() error
1068 * messages that we'll parse in
1069 * parse_proc_cmdline_word() or ignore. */
f170852a 1070
099663ff 1071 case '?':
df0ff127 1072 if (getpid_cached() != 1)
099663ff 1073 return -EINVAL;
601185b4
ZJS
1074 else
1075 return 0;
099663ff 1076
601185b4
ZJS
1077 default:
1078 assert_not_reached("Unhandled option code.");
f170852a
LP
1079 }
1080
df0ff127 1081 if (optind < argc && getpid_cached() != 1) {
d821e6d6
LP
1082 /* Hmm, when we aren't run as init system
1083 * let's complain about excess arguments */
1084
1085 log_error("Excess arguments.");
1086 return -EINVAL;
1087 }
1088
f170852a
LP
1089 return 0;
1090}
1091
1092static int help(void) {
1093
2e33c433 1094 printf("%s [OPTIONS...]\n\n"
af2d49f7 1095 "Starts up and maintains the system or user services.\n\n"
e537352b 1096 " -h --help Show this help\n"
cb4069d9 1097 " --version Show version\n"
e537352b 1098 " --test Determine startup sequence, dump it and exit\n"
b87c2aa6 1099 " --no-pager Do not pipe output into a pager\n"
80876c20 1100 " --dump-configuration-items Dump understood unit configuration items\n"
9e58ff9c 1101 " --unit=UNIT Set default unit\n"
edb9aaa8 1102 " --system Run a system instance, even if PID != 1\n"
af2d49f7 1103 " --user Run a user instance\n"
b9e74c39
LP
1104 " --dump-core[=BOOL] Dump core on crash\n"
1105 " --crash-vt=NR Change to specified VT on crash\n"
1106 " --crash-reboot[=BOOL] Reboot on crash\n"
1107 " --crash-shell[=BOOL] Run shell on crash\n"
1108 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1109 " --show-status[=BOOL] Show status updates on the console during bootup\n"
c1dc6153 1110 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
9e58ff9c 1111 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
b9e74c39
LP
1112 " --log-color[=BOOL] Highlight important log messages\n"
1113 " --log-location[=BOOL] Include code location in log messages\n"
0a494f1f
LP
1114 " --default-standard-output= Set default standard output for services\n"
1115 " --default-standard-error= Set default standard error output for services\n",
5b6319dc 1116 program_invocation_short_name);
f170852a
LP
1117
1118 return 0;
1119}
1120
b3680f49 1121static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds, bool switching_root) {
48b90859
LP
1122 _cleanup_fdset_free_ FDSet *fds = NULL;
1123 _cleanup_fclose_ FILE *f = NULL;
a16e1123
LP
1124 int r;
1125
1126 assert(m);
1127 assert(_f);
1128 assert(_fds);
1129
6b78f9b4 1130 r = manager_open_serialization(m, &f);
48b90859
LP
1131 if (r < 0)
1132 return log_error_errno(r, "Failed to create serialization file: %m");
a16e1123 1133
71445ae7 1134 /* Make sure nothing is really destructed when we shut down */
313cefa1 1135 m->n_reloading++;
718db961 1136 bus_manager_send_reloading(m, true);
71445ae7 1137
6b78f9b4 1138 fds = fdset_new();
48b90859
LP
1139 if (!fds)
1140 return log_oom();
a16e1123 1141
b3680f49 1142 r = manager_serialize(m, f, fds, switching_root);
48b90859
LP
1143 if (r < 0)
1144 return log_error_errno(r, "Failed to serialize state: %m");
a16e1123 1145
48b90859
LP
1146 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1147 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
a16e1123 1148
6b78f9b4 1149 r = fd_cloexec(fileno(f), false);
48b90859
LP
1150 if (r < 0)
1151 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
a16e1123 1152
6b78f9b4 1153 r = fdset_cloexec(fds, false);
48b90859
LP
1154 if (r < 0)
1155 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
a16e1123
LP
1156
1157 *_f = f;
1158 *_fds = fds;
1159
48b90859
LP
1160 f = NULL;
1161 fds = NULL;
a16e1123 1162
48b90859 1163 return 0;
a16e1123
LP
1164}
1165
4096d6f5
LP
1166static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
1167 struct rlimit nl;
1168 int r;
6385cb31
CB
1169 int min_max;
1170 _cleanup_free_ char *nr_open = NULL;
4096d6f5
LP
1171
1172 assert(saved_rlimit);
1173
1174 /* Save the original RLIMIT_NOFILE so that we can reset it
1175 * later when transitioning from the initrd to the main
1176 * systemd or suchlike. */
4a62c710 1177 if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0)
3ce40911 1178 return log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5
LP
1179
1180 /* Make sure forked processes get the default kernel setting */
1181 if (!arg_default_rlimit[RLIMIT_NOFILE]) {
1182 struct rlimit *rl;
1183
1184 rl = newdup(struct rlimit, saved_rlimit, 1);
1185 if (!rl)
1186 return log_oom();
1187
1188 arg_default_rlimit[RLIMIT_NOFILE] = rl;
1189 }
1190
6385cb31
CB
1191 /* Get current RLIMIT_NOFILE maximum compiled into the kernel. */
1192 r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
1193 if (r == 0)
1194 r = safe_atoi(nr_open, &min_max);
1195 /* If we fail, fallback to the hard-coded kernel limit of 1024 * 1024. */
1196 if (r < 0)
1197 min_max = 1024 * 1024;
1198
4096d6f5 1199 /* Bump up the resource limit for ourselves substantially */
6385cb31 1200 nl.rlim_cur = nl.rlim_max = min_max;
4096d6f5 1201 r = setrlimit_closest(RLIMIT_NOFILE, &nl);
23bbb0de 1202 if (r < 0)
3ce40911 1203 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5
LP
1204
1205 return 0;
1206}
1207
fb3ae275
LP
1208static int bump_rlimit_memlock(struct rlimit *saved_rlimit) {
1209 int r;
1210
1211 assert(saved_rlimit);
1212 assert(getuid() == 0);
1213
1214 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even though we have CAP_IPC_LOCK which
1215 * should normally disable such checks. We need them to implement IPAccessAllow= and IPAccessDeny=, hence let's
1216 * bump the value high enough for the root user. */
1217
1218 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit) < 0)
1219 return log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
1220
1221 r = setrlimit_closest(RLIMIT_MEMLOCK, &RLIMIT_MAKE_CONST(1024ULL*1024ULL*16ULL));
1222 if (r < 0)
1223 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1224
1225 return 0;
1226}
1227
80758717 1228static void test_usr(void) {
80758717 1229
ed1c99fc 1230 /* Check that /usr is not a separate fs */
80758717 1231
871c44a7
LP
1232 if (dir_is_empty("/usr") <= 0)
1233 return;
1234
8b173b5e 1235 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
871c44a7
LP
1236 "Some things will probably break (sometimes even silently) in mysterious ways. "
1237 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1238}
1239
a07fdfa3
LP
1240static int initialize_join_controllers(void) {
1241 /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
1242 * + "net_prio". We'd like to add "cpuset" to the mix, but
f131770b 1243 * "cpuset" doesn't really work for groups with no initialized
a07fdfa3
LP
1244 * attributes. */
1245
1246 arg_join_controllers = new(char**, 3);
1247 if (!arg_join_controllers)
1248 return -ENOMEM;
1249
1250 arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
fe382237
LP
1251 if (!arg_join_controllers[0])
1252 goto oom;
a6b26d90 1253
fe382237
LP
1254 arg_join_controllers[1] = strv_new("net_cls", "net_prio", NULL);
1255 if (!arg_join_controllers[1])
1256 goto oom;
a07fdfa3 1257
fe382237 1258 arg_join_controllers[2] = NULL;
a07fdfa3 1259 return 0;
fe382237
LP
1260
1261oom:
1262 arg_join_controllers = strv_free_free(arg_join_controllers);
1263 return -ENOMEM;
a07fdfa3
LP
1264}
1265
d3b1c508 1266static int enforce_syscall_archs(Set *archs) {
349cc4a5 1267#if HAVE_SECCOMP
d3b1c508
LP
1268 int r;
1269
83f12b27
FS
1270 if (!is_seccomp_available())
1271 return 0;
1272
469830d1 1273 r = seccomp_restrict_archs(arg_syscall_archs);
d3b1c508 1274 if (r < 0)
469830d1 1275 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
d3b1c508 1276#endif
469830d1 1277 return 0;
d3b1c508
LP
1278}
1279
b6e2f329
LP
1280static int status_welcome(void) {
1281 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1282 int r;
1283
1284 r = parse_env_file("/etc/os-release", NEWLINE,
1285 "PRETTY_NAME", &pretty_name,
1286 "ANSI_COLOR", &ansi_color,
1287 NULL);
ece174c5 1288 if (r == -ENOENT)
5ae4d543
LP
1289 r = parse_env_file("/usr/lib/os-release", NEWLINE,
1290 "PRETTY_NAME", &pretty_name,
1291 "ANSI_COLOR", &ansi_color,
1292 NULL);
b6e2f329
LP
1293
1294 if (r < 0 && r != -ENOENT)
da927ba9 1295 log_warning_errno(r, "Failed to read os-release file: %m");
b6e2f329 1296
dc9b5816
ZJS
1297 if (log_get_show_color())
1298 return status_printf(NULL, false, false,
1299 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1300 isempty(ansi_color) ? "1" : ansi_color,
1301 isempty(pretty_name) ? "Linux" : pretty_name);
1302 else
1303 return status_printf(NULL, false, false,
1304 "\nWelcome to %s!\n",
1305 isempty(pretty_name) ? "Linux" : pretty_name);
b6e2f329
LP
1306}
1307
fdd25311
LP
1308static int write_container_id(void) {
1309 const char *c;
19854865 1310 int r;
fdd25311
LP
1311
1312 c = getenv("container");
1313 if (isempty(c))
1314 return 0;
1315
8612da97
LP
1316 RUN_WITH_UMASK(0022)
1317 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
19854865 1318 if (r < 0)
f1f849b0 1319 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
19854865
LP
1320
1321 return 1;
1322}
1323
1324static int bump_unix_max_dgram_qlen(void) {
1325 _cleanup_free_ char *qlen = NULL;
1326 unsigned long v;
1327 int r;
1328
1329 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel
1330 * default of 16 is simply too low. We set the value really
1331 * really early during boot, so that it is actually applied to
1332 * all our sockets, including the $NOTIFY_SOCKET one. */
1333
1334 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1335 if (r < 0)
1336 return log_warning_errno(r, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1337
1338 r = safe_atolu(qlen, &v);
1339 if (r < 0)
1340 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length, ignoring: %m");
1341
1342 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1343 return 0;
1344
1345 qlen = mfree(qlen);
1346 if (asprintf(&qlen, "%lu\n", DEFAULT_UNIX_MAX_DGRAM_QLEN) < 0)
1347 return log_oom();
1348
1349 r = write_string_file("/proc/sys/net/unix/max_dgram_qlen", qlen, 0);
1350 if (r < 0)
1351 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1352 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1353
1354 return 1;
fdd25311
LP
1355}
1356
32391275
FB
1357static int fixup_environment(void) {
1358 _cleanup_free_ char *term = NULL;
1359 int r;
1360
84af7821
LP
1361 /* We expect the environment to be set correctly
1362 * if run inside a container. */
1363 if (detect_container() > 0)
1364 return 0;
1365
32391275
FB
1366 /* When started as PID1, the kernel uses /dev/console
1367 * for our stdios and uses TERM=linux whatever the
1368 * backend device used by the console. We try to make
1369 * a better guess here since some consoles might not
1370 * have support for color mode for example.
1371 *
1372 * However if TERM was configured through the kernel
1373 * command line then leave it alone. */
1374
1d84ad94 1375 r = proc_cmdline_get_key("TERM", 0, &term);
32391275
FB
1376 if (r < 0)
1377 return r;
32391275 1378 if (r == 0) {
6af760f3 1379 term = strdup(default_term_for_tty("/dev/console"));
32391275 1380 if (!term)
84af7821 1381 return -ENOMEM;
32391275
FB
1382 }
1383
1384 if (setenv("TERM", term, 1) < 0)
1385 return -errno;
1386
1387 return 0;
1388}
1389
60918275
LP
1390int main(int argc, char *argv[]) {
1391 Manager *m = NULL;
22f4096c 1392 int r, retval = EXIT_FAILURE;
9d76d730
LP
1393 usec_t before_startup, after_startup;
1394 char timespan[FORMAT_TIMESPAN_MAX];
a16e1123
LP
1395 FDSet *fds = NULL;
1396 bool reexecute = false;
b9080b03 1397 const char *shutdown_verb = NULL;
86caf095
LP
1398 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL;
1399 dual_timestamp userspace_timestamp = DUAL_TIMESTAMP_NULL;
1400 dual_timestamp kernel_timestamp = DUAL_TIMESTAMP_NULL;
1401 dual_timestamp security_start_timestamp = DUAL_TIMESTAMP_NULL;
1402 dual_timestamp security_finish_timestamp = DUAL_TIMESTAMP_NULL;
5d6b1584 1403 static char systemd[] = "systemd";
2660882b 1404 bool skip_setup = false;
d3b1c508 1405 unsigned j;
0b3325e7 1406 bool loaded_policy = false;
e96d6be7 1407 bool arm_reboot_watchdog = false;
bf4df7c3 1408 bool queue_default_job = false;
5f5c2f38 1409 bool empty_etc = false;
41669317 1410 char *switch_root_dir = NULL, *switch_root_init = NULL;
fb3ae275 1411 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0), saved_rlimit_memlock = RLIMIT_MAKE_CONST((rlim_t) -1);
cb6531be 1412 const char *error_message = NULL;
27b14a22 1413
349cc4a5 1414#if HAVE_SYSV_COMPAT
df0ff127 1415 if (getpid_cached() != 1 && strstr(program_invocation_short_name, "init")) {
35b8ca3a 1416 /* This is compatibility support for SysV, where
2cb1a60d
LP
1417 * calling init as a user is identical to telinit. */
1418
2cb1a60d 1419 execv(SYSTEMCTL_BINARY_PATH, argv);
56f64d95 1420 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
2cb1a60d
LP
1421 return 1;
1422 }
058dc6f3 1423#endif
2cb1a60d 1424
c3a170f3
HH
1425 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
1426 dual_timestamp_get(&userspace_timestamp);
1427
0b3325e7
LP
1428 /* Determine if this is a reexecution or normal bootup. We do
1429 * the full command line parsing much later, so let's just
1430 * have a quick peek here. */
db813c2a
LP
1431 if (strv_find(argv+1, "--deserialize"))
1432 skip_setup = true;
0b3325e7 1433
2660882b
LP
1434 /* If we have switched root, do all the special setup
1435 * things */
db813c2a
LP
1436 if (strv_find(argv+1, "--switched-root"))
1437 skip_setup = false;
d03bc1b8 1438
f3b6a3ed
LP
1439 /* If we get started via the /sbin/init symlink then we are
1440 called 'init'. After a subsequent reexecution we are then
1441 called 'systemd'. That is confusing, hence let's call us
1442 systemd right-away. */
f3b6a3ed 1443 program_invocation_short_name = systemd;
eee8b7ab 1444 (void) prctl(PR_SET_NAME, systemd);
5d6b1584 1445
9a0e6896
LP
1446 saved_argv = argv;
1447 saved_argc = argc;
f3b6a3ed 1448
c1dc6153 1449 log_set_upgrade_syslog_to_journal(true);
bbe63281 1450
df0ff127 1451 if (getpid_cached() == 1) {
48a601fe 1452 /* Disable the umask logic */
90dc8c2e
MG
1453 umask(0);
1454
48a601fe
LP
1455 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
1456 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
1457 * child process right before execve()'ing the actual binary, at a point in time where socket
1458 * activation stderr/stdout area already set up. */
1459 log_set_always_reopen_console(true);
1460 }
1461
df0ff127 1462 if (getpid_cached() == 1 && detect_container() <= 0) {
4f8d551f 1463
a866073d 1464 /* Running outside of a container as PID 1 */
463d0d15 1465 arg_system = true;
a866073d
LP
1466 log_set_target(LOG_TARGET_KMSG);
1467 log_open();
1468
21bf2ab0 1469 if (in_initrd())
c3a170f3 1470 initrd_timestamp = userspace_timestamp;
c3ba6250 1471
2660882b 1472 if (!skip_setup) {
d723cd65
AK
1473 r = mount_setup_early();
1474 if (r < 0) {
eee8b7ab 1475 error_message = "Failed to mount early API filesystems";
d723cd65
AK
1476 goto finish;
1477 }
eee8b7ab 1478
c2e0d600 1479 dual_timestamp_get(&security_start_timestamp);
cb6531be
ZJS
1480 if (mac_selinux_setup(&loaded_policy) < 0) {
1481 error_message = "Failed to load SELinux policy";
0b3325e7 1482 goto finish;
cb6531be
ZJS
1483 } else if (mac_smack_setup(&loaded_policy) < 0) {
1484 error_message = "Failed to load SMACK policy";
ffbd2c4d 1485 goto finish;
96694e99
IP
1486 } else if (ima_setup() < 0) {
1487 error_message = "Failed to load IMA policy";
1488 goto finish;
cb6531be 1489 }
c2e0d600 1490 dual_timestamp_get(&security_finish_timestamp);
81611586 1491 }
0b3325e7 1492
c3dacc8b 1493 if (mac_selinux_init() < 0) {
cb6531be 1494 error_message = "Failed to initialize SELinux policy";
0ff4cdd9 1495 goto finish;
cb6531be 1496 }
7948c4df 1497
72edcff5 1498 if (!skip_setup) {
6369641d 1499 if (clock_is_localtime(NULL) > 0) {
0b3325e7 1500 int min;
7948c4df 1501
c264aeab
KS
1502 /*
1503 * The very first call of settimeofday() also does a time warp in the kernel.
1504 *
1505 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on
1506 * external tools to take care of maintaining the RTC and do all adjustments.
1507 * This matches the behavior of Windows, which leaves the RTC alone if the
1508 * registry tells that the RTC runs in UTC.
1509 */
24efb112 1510 r = clock_set_timezone(&min);
0b3325e7 1511 if (r < 0)
da927ba9 1512 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
0b3325e7
LP
1513 else
1514 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
19e65613
KS
1515 } else if (!in_initrd()) {
1516 /*
c264aeab 1517 * Do a dummy very first call to seal the kernel's time warp magic.
19e65613 1518 *
61233823 1519 * Do not call this from inside the initrd. The initrd might not
19e65613
KS
1520 * carry /etc/adjtime with LOCAL, but the real system could be set up
1521 * that way. In such case, we need to delay the time-warp or the sealing
1522 * until we reach the real system.
c264aeab
KS
1523 *
1524 * Do no set the kernel's timezone. The concept of local time cannot
1525 * be supported reliably, the time will jump or be incorrect at every daylight
1526 * saving time change. All kernel local time concepts will be treated
1527 * as UTC that way.
19e65613 1528 */
021dd87b 1529 (void) clock_reset_timewarp();
72edcff5 1530 }
021dd87b
LP
1531
1532 r = clock_apply_epoch();
1533 if (r < 0)
1534 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1535 else if (r > 0)
1536 log_info("System time before build time, advancing clock.");
72edcff5 1537 }
a866073d
LP
1538
1539 /* Set the default for later on, but don't actually
1540 * open the logs like this for now. Note that if we
1541 * are transitioning from the initrd there might still
1542 * be journal fd open, and we shouldn't attempt
1543 * opening that before we parsed /proc/cmdline which
1544 * might redirect output elsewhere. */
1545 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1546
df0ff127 1547 } else if (getpid_cached() == 1) {
a866073d 1548 /* Running inside a container, as PID 1 */
463d0d15 1549 arg_system = true;
a866073d 1550 log_set_target(LOG_TARGET_CONSOLE);
99f09825 1551 log_close_console(); /* force reopen of /dev/console */
a866073d
LP
1552 log_open();
1553
eee8b7ab 1554 /* For later on, see above... */
a866073d
LP
1555 log_set_target(LOG_TARGET_JOURNAL);
1556
c3a170f3
HH
1557 /* clear the kernel timestamp,
1558 * because we are in a container */
0f5f63c3 1559 kernel_timestamp = DUAL_TIMESTAMP_NULL;
c3a170f3 1560 } else {
a866073d 1561 /* Running as user instance */
463d0d15 1562 arg_system = false;
eeecf6e6 1563 log_set_target(LOG_TARGET_AUTO);
871e5809 1564 log_open();
c3a170f3
HH
1565
1566 /* clear the kernel timestamp,
1567 * because we are not PID 1 */
6513d561 1568 kernel_timestamp = DUAL_TIMESTAMP_NULL;
bbe63281 1569 }
a5dab5ce 1570
df0ff127 1571 if (getpid_cached() == 1) {
15a90032
LP
1572 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1573 * will process core dumps for system services by default. */
206fc4b2
ZJS
1574 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1575 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
15a90032
LP
1576
1577 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1578 * until the systemd-coredump tool is enabled via sysctl. */
1579 if (!skip_setup)
1580 (void) write_string_file("/proc/sys/kernel/core_pattern", "|/bin/false", 0);
1581 }
1582
6edefe0b 1583 if (arg_system) {
84af7821
LP
1584 if (fixup_environment() < 0) {
1585 error_message = "Failed to fix up PID1 environment";
1586 goto finish;
1587 }
32391275 1588
3a18b604
FB
1589 /* Try to figure out if we can use colors with the console. No
1590 * need to do that for user instances since they never log
1591 * into the console. */
1592 log_show_color(colors_enabled());
c76cf844
AK
1593 r = make_null_stdio();
1594 if (r < 0)
1595 log_warning_errno(r, "Failed to redirect standard streams to /dev/null: %m");
3a18b604
FB
1596 }
1597
a07fdfa3 1598 r = initialize_join_controllers();
cb6531be 1599 if (r < 0) {
ff9b60f3 1600 error_message = "Failed to initialize cgroup controllers";
0c85a4f3 1601 goto finish;
cb6531be 1602 }
0c85a4f3 1603
f170852a
LP
1604 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1605 * /proc/$PID/fd is available. */
df0ff127 1606 if (getpid_cached() == 1) {
f84f9974 1607
a132bef0 1608 /* Load the kernel modules early. */
2e75e2a8
DM
1609 if (!skip_setup)
1610 kmod_setup();
2e75e2a8 1611
0c85a4f3 1612 r = mount_setup(loaded_policy);
cb6531be
ZJS
1613 if (r < 0) {
1614 error_message = "Failed to mount API filesystems";
8efe3c01 1615 goto finish;
cb6531be 1616 }
0c85a4f3 1617 }
4ade7963
LP
1618
1619 /* Reset all signal handlers. */
ce30c8dc
LP
1620 (void) reset_all_signal_handlers();
1621 (void) ignore_signals(SIGNALS_IGNORE, -1);
078e4539 1622
f5058264 1623 arg_default_tasks_max = system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE, 100U);
79baeeb9 1624
cb6531be
ZJS
1625 if (parse_config_file() < 0) {
1626 error_message = "Failed to parse config file";
487393e9 1627 goto finish;
cb6531be 1628 }
487393e9 1629
463d0d15 1630 if (arg_system) {
1d84ad94 1631 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
b5884878 1632 if (r < 0)
da927ba9 1633 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
b5884878 1634 }
f170852a 1635
1de1c9c3
LP
1636 /* Note that this also parses bits from the kernel command
1637 * line, including "debug". */
f170852a
LP
1638 log_parse_environment();
1639
cb6531be
ZJS
1640 if (parse_argv(argc, argv) < 0) {
1641 error_message = "Failed to parse commandline arguments";
f170852a 1642 goto finish;
cb6531be 1643 }
f170852a 1644
10c961b9
AK
1645 /* Initialize default unit */
1646 if (!arg_default_unit) {
f6dd106c
AK
1647 arg_default_unit = strdup(SPECIAL_DEFAULT_TARGET);
1648 if (!arg_default_unit) {
1649 r = log_oom();
10c961b9
AK
1650 error_message = "Failed to set default unit";
1651 goto finish;
1652 }
1653 }
1654
6bae23a0
TB
1655 if (arg_action == ACTION_TEST &&
1656 geteuid() == 0) {
b5c6cf87
LP
1657 log_error("Don't run test mode as root.");
1658 goto finish;
1659 }
1660
463d0d15 1661 if (!arg_system &&
6bae23a0
TB
1662 arg_action == ACTION_RUN &&
1663 sd_booted() <= 0) {
1664 log_error("Trying to run as user instance, but the system has not been booted with systemd.");
1665 goto finish;
1666 }
1667
463d0d15 1668 if (arg_system &&
fe783b03
LP
1669 arg_action == ACTION_RUN &&
1670 running_in_chroot() > 0) {
1671 log_error("Cannot be run in a chroot() environment.");
1672 goto finish;
1673 }
1674
74e7579c 1675 if (arg_action == ACTION_TEST || arg_action == ACTION_HELP) {
ea4b98e6 1676 pager_open(arg_no_pager, false);
74e7579c
AK
1677 skip_setup = true;
1678 }
b87c2aa6 1679
fa0f4d8a 1680 if (arg_action == ACTION_HELP) {
f170852a
LP
1681 retval = help();
1682 goto finish;
9ba0bc4e
ZJS
1683 } else if (arg_action == ACTION_VERSION) {
1684 retval = version();
1685 goto finish;
fa0f4d8a 1686 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
13811bf9 1687 pager_open(arg_no_pager, false);
e537352b 1688 unit_dump_config_items(stdout);
22f4096c 1689 retval = EXIT_SUCCESS;
e537352b 1690 goto finish;
f170852a
LP
1691 }
1692
463d0d15 1693 if (!arg_system &&
8be28fb1
KS
1694 !getenv("XDG_RUNTIME_DIR")) {
1695 log_error("Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
1696 goto finish;
1697 }
1698
fa0f4d8a 1699 assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
f170852a 1700
871e5809
LP
1701 /* Close logging fds, in order not to confuse fdset below */
1702 log_close();
1703
a16e1123 1704 /* Remember open file descriptors for later deserialization */
dea374e8
LP
1705 if (arg_action == ACTION_RUN) {
1706 r = fdset_new_fill(&fds);
1707 if (r < 0) {
1708 log_emergency_errno(r, "Failed to allocate fd set: %m");
1709 error_message = "Failed to allocate fd set";
1710 goto finish;
1711 } else
1712 fdset_cloexec(fds, true);
a16e1123 1713
dea374e8
LP
1714 if (arg_serialization)
1715 assert_se(fdset_remove(fds, fileno(arg_serialization)) >= 0);
a16e1123 1716
dea374e8
LP
1717 if (arg_system)
1718 /* Become a session leader if we aren't one yet. */
1719 setsid();
1720 }
4ade7963 1721
befb5b6a 1722 /* Move out of the way, so that we won't block unmounts */
d250afe7 1723 assert_se(chdir("/") == 0);
befb5b6a 1724
2146621b
LP
1725 /* Reset the console, but only if this is really init and we
1726 * are freshly booted */
463d0d15 1727 if (arg_system && arg_action == ACTION_RUN) {
56d96fc0
LP
1728
1729 /* If we are init, we connect stdin/stdout/stderr to
1730 * /dev/null and make sure we don't have a controlling
1731 * tty. */
1732 release_terminal();
1733
df0ff127 1734 if (getpid_cached() == 1 && !skip_setup)
56d96fc0
LP
1735 console_setup();
1736 }
4ade7963 1737
18149b9f 1738 /* Open the logging devices, if possible and necessary */
843d2643 1739 log_open();
4ade7963 1740
b6e2f329
LP
1741 if (arg_show_status == _SHOW_STATUS_UNSET)
1742 arg_show_status = SHOW_STATUS_YES;
1743
5373d602
LP
1744 /* Make sure we leave a core dump without panicing the
1745 * kernel. */
df0ff127 1746 if (getpid_cached() == 1) {
4fc935ca 1747 install_crash_handler();
97c4f35c 1748
0c85a4f3
LP
1749 r = mount_cgroup_controllers(arg_join_controllers);
1750 if (r < 0)
1751 goto finish;
1752 }
1753
463d0d15 1754 if (arg_system) {
75f86906 1755 int v;
c20f5ac7 1756
0d8c31ff
ZJS
1757 log_info(PACKAGE_STRING " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
1758 arg_action == ACTION_TEST ? "test " : "" );
c20f5ac7 1759
75f86906
LP
1760 v = detect_virtualization();
1761 if (v > 0)
1762 log_info("Detected virtualization %s.", virtualization_to_string(v));
c20f5ac7 1763
fdd25311
LP
1764 write_container_id();
1765
d3f86679 1766 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
d9d93745 1767
26a1efdf
LP
1768 if (in_initrd())
1769 log_info("Running in initial RAM disk.");
1770
3408ba01
LP
1771 /* Let's check whether /etc is already populated. We
1772 * don't actually really check for that, but use
1773 * /etc/machine-id as flag file. This allows container
1774 * managers and installers to provision a couple of
1775 * files already. If the container manager wants to
1776 * provision the machine ID itself it should pass
ee33e53a 1777 * $container_uuid to PID 1. */
3408ba01 1778
baa1bdf7 1779 empty_etc = access("/etc/machine-id", F_OK) < 0;
5f5c2f38
LP
1780 if (empty_etc)
1781 log_info("Running with unpopulated /etc.");
d8160f21 1782 } else {
1f97091d
LP
1783 _cleanup_free_ char *t;
1784
1785 t = uid_to_name(getuid());
0d8c31ff
ZJS
1786 log_debug(PACKAGE_STRING " running in %suser mode for user "UID_FMT"/%s. (" SYSTEMD_FEATURES ")",
1787 arg_action == ACTION_TEST ? " test" : "", getuid(), t);
d8160f21 1788 }
a5dab5ce 1789
dea374e8
LP
1790 if (arg_action == ACTION_RUN) {
1791 if (arg_system && !skip_setup) {
1792 if (arg_show_status > 0)
1793 status_welcome();
888c6216 1794
dea374e8
LP
1795 hostname_setup();
1796 machine_id_setup(NULL, arg_machine_id, NULL);
1797 loopback_setup();
1798 bump_unix_max_dgram_qlen();
490aed58 1799
dea374e8
LP
1800 test_usr();
1801 }
302e8c4c 1802
dea374e8
LP
1803 if (arg_system && arg_runtime_watchdog > 0 && arg_runtime_watchdog != USEC_INFINITY)
1804 watchdog_set_timeout(&arg_runtime_watchdog);
e96d6be7 1805
dea374e8
LP
1806 if (arg_timer_slack_nsec != NSEC_INFINITY)
1807 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
1808 log_error_errno(errno, "Failed to adjust timer slack: %m");
aa0f64ac 1809
dea374e8
LP
1810 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
1811 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
1812 if (r < 0) {
1813 log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
1814 error_message = "Failed to drop capability bounding set of usermode helpers";
1815 goto finish;
1816 }
1817 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
1818 if (r < 0) {
1819 log_emergency_errno(r, "Failed to drop capability bounding set: %m");
1820 error_message = "Failed to drop capability bounding set";
1821 goto finish;
1822 }
939b8f14 1823 }
ec8927ca 1824
dea374e8
LP
1825 if (arg_syscall_archs) {
1826 r = enforce_syscall_archs(arg_syscall_archs);
1827 if (r < 0) {
1828 error_message = "Failed to set syscall architectures";
1829 goto finish;
1830 }
cb6531be 1831 }
d3b1c508 1832
dea374e8
LP
1833 if (!arg_system)
1834 /* Become reaper of our children */
1835 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
1836 log_warning_errno(errno, "Failed to make us a subreaper: %m");
d4447f4d 1837
fb3ae275 1838 if (arg_system) {
dea374e8
LP
1839 /* Bump up RLIMIT_NOFILE for systemd itself */
1840 (void) bump_rlimit_nofile(&saved_rlimit_nofile);
fb3ae275
LP
1841 (void) bump_rlimit_memlock(&saved_rlimit_memlock);
1842 }
dea374e8 1843 }
4096d6f5 1844
e0a3da1f
ZJS
1845 r = manager_new(arg_system ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
1846 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
1847 &m);
e96d6be7 1848 if (r < 0) {
da927ba9 1849 log_emergency_errno(r, "Failed to allocate manager object: %m");
cb6531be 1850 error_message = "Failed to allocate manager object";
60918275
LP
1851 goto finish;
1852 }
1853
9e58ff9c 1854 m->confirm_spawn = arg_confirm_spawn;
e96d6be7
LP
1855 m->runtime_watchdog = arg_runtime_watchdog;
1856 m->shutdown_watchdog = arg_shutdown_watchdog;
c3a170f3
HH
1857 m->userspace_timestamp = userspace_timestamp;
1858 m->kernel_timestamp = kernel_timestamp;
c3a170f3 1859 m->initrd_timestamp = initrd_timestamp;
c2e0d600
TA
1860 m->security_start_timestamp = security_start_timestamp;
1861 m->security_finish_timestamp = security_finish_timestamp;
24dd31c1 1862 m->cad_burst_action = arg_cad_burst_action;
9e58ff9c 1863
06af2a04 1864 manager_set_defaults(m);
27d340c7 1865 manager_set_show_status(m, arg_show_status);
e2680723 1866 manager_set_first_boot(m, empty_etc);
27d340c7 1867
bf4df7c3 1868 /* Remember whether we should queue the default job */
d3b1c508 1869 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 1870
9d76d730
LP
1871 before_startup = now(CLOCK_MONOTONIC);
1872
d3b1c508 1873 r = manager_startup(m, arg_serialization, fds);
58f88d92 1874 if (r < 0) {
da927ba9 1875 log_error_errno(r, "Failed to fully start up daemon: %m");
58f88d92
ZJS
1876 goto finish;
1877 }
a16e1123 1878
bf4df7c3
LP
1879 /* This will close all file descriptors that were opened, but
1880 * not claimed by any unit. */
2feceb5e 1881 fds = fdset_free(fds);
f50e0a01 1882
74ca738f 1883 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
1884
1885 if (queue_default_job) {
4afd3348 1886 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1c27d3f3 1887 Unit *target = NULL;
bacbccb7 1888 Job *default_unit_job;
398ef8ba 1889
fa0f4d8a 1890 log_debug("Activating default unit: %s", arg_default_unit);
a16e1123 1891
e96d6be7 1892 r = manager_load_unit(m, arg_default_unit, NULL, &error, &target);
718db961
LP
1893 if (r < 0)
1894 log_error("Failed to load default target: %s", bus_error_message(&error, r));
1895 else if (target->load_state == UNIT_ERROR || target->load_state == UNIT_NOT_FOUND)
c33b3297 1896 log_error_errno(target->load_error, "Failed to load default target: %m");
ac155bb8 1897 else if (target->load_state == UNIT_MASKED)
6daf4f90 1898 log_error("Default target masked.");
27b14a22 1899
ac155bb8 1900 if (!target || target->load_state != UNIT_LOADED) {
a16e1123 1901 log_info("Trying to load rescue target...");
1c27d3f3 1902
e96d6be7
LP
1903 r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target);
1904 if (r < 0) {
4104970e 1905 log_emergency("Failed to load rescue target: %s", bus_error_message(&error, r));
cb6531be 1906 error_message = "Failed to load rescue target";
a16e1123 1907 goto finish;
11ddb6f4 1908 } else if (target->load_state == UNIT_ERROR || target->load_state == UNIT_NOT_FOUND) {
c33b3297 1909 log_emergency_errno(target->load_error, "Failed to load rescue target: %m");
cb6531be 1910 error_message = "Failed to load rescue target";
1c27d3f3 1911 goto finish;
ac155bb8 1912 } else if (target->load_state == UNIT_MASKED) {
4104970e 1913 log_emergency("Rescue target masked.");
cb6531be 1914 error_message = "Rescue target masked";
00dc5d76 1915 goto finish;
a16e1123
LP
1916 }
1917 }
37d88da7 1918
ac155bb8 1919 assert(target->load_state == UNIT_LOADED);
00dc5d76 1920
fa0f4d8a 1921 if (arg_action == ACTION_TEST) {
40d50879 1922 printf("-> By units:\n");
a16e1123
LP
1923 manager_dump_units(m, stdout, "\t");
1924 }
1925
4bd29fe5 1926 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, &error, &default_unit_job);
ab17a050 1927 if (r == -EPERM) {
718db961 1928 log_debug("Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
ab17a050 1929
5022ce71
LP
1930 sd_bus_error_free(&error);
1931
4bd29fe5 1932 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, &error, &default_unit_job);
ab17a050 1933 if (r < 0) {
4104970e 1934 log_emergency("Failed to start default target: %s", bus_error_message(&error, r));
cb6531be 1935 error_message = "Failed to start default target";
ab17a050
LP
1936 goto finish;
1937 }
1938 } else if (r < 0) {
4104970e 1939 log_emergency("Failed to isolate default target: %s", bus_error_message(&error, r));
cb6531be 1940 error_message = "Failed to isolate default target";
37d88da7
LP
1941 goto finish;
1942 }
ab17a050 1943
bacbccb7 1944 m->default_unit_job_id = default_unit_job->id;
60918275 1945
07672f49
LP
1946 after_startup = now(CLOCK_MONOTONIC);
1947 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
1948 "Loaded units and determined initial transaction in %s.",
fdb14b7e 1949 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 1950
fa0f4d8a 1951 if (arg_action == ACTION_TEST) {
40d50879 1952 printf("-> By jobs:\n");
a16e1123 1953 manager_dump_jobs(m, stdout, "\t");
22f4096c 1954 retval = EXIT_SUCCESS;
a16e1123
LP
1955 goto finish;
1956 }
e965d56d 1957 }
d46de8a1 1958
a16e1123 1959 for (;;) {
e96d6be7
LP
1960 r = manager_loop(m);
1961 if (r < 0) {
da927ba9 1962 log_emergency_errno(r, "Failed to run main loop: %m");
cb6531be 1963 error_message = "Failed to run main loop";
a16e1123
LP
1964 goto finish;
1965 }
11dd41ce 1966
a16e1123 1967 switch (m->exit_code) {
e965d56d 1968
a16e1123 1969 case MANAGER_RELOAD:
e015090f 1970 log_info("Reloading.");
06af2a04
TB
1971
1972 r = parse_config_file();
1973 if (r < 0)
1974 log_error("Failed to parse config file.");
1975
1976 manager_set_defaults(m);
1977
e96d6be7
LP
1978 r = manager_reload(m);
1979 if (r < 0)
da927ba9 1980 log_error_errno(r, "Failed to reload: %m");
a16e1123 1981 break;
cea8e32e 1982
a16e1123 1983 case MANAGER_REEXECUTE:
664f88a7 1984
cb6531be 1985 if (prepare_reexecute(m, &arg_serialization, &fds, false) < 0) {
6b9af963 1986 error_message = "Failed to prepare for reexecution";
a16e1123 1987 goto finish;
cb6531be 1988 }
60918275 1989
a16e1123 1990 reexecute = true;
e015090f 1991 log_notice("Reexecuting.");
a16e1123
LP
1992 goto finish;
1993
664f88a7
LP
1994 case MANAGER_SWITCH_ROOT:
1995 /* Steal the switch root parameters */
41669317 1996 switch_root_dir = m->switch_root;
664f88a7
LP
1997 switch_root_init = m->switch_root_init;
1998 m->switch_root = m->switch_root_init = NULL;
1999
2000 if (!switch_root_init)
cb6531be 2001 if (prepare_reexecute(m, &arg_serialization, &fds, true) < 0) {
6b9af963 2002 error_message = "Failed to prepare for reexecution";
664f88a7 2003 goto finish;
cb6531be 2004 }
664f88a7
LP
2005
2006 reexecute = true;
2007 log_notice("Switching root.");
2008 goto finish;
2009
287419c1 2010 case MANAGER_EXIT:
97792515
LP
2011 retval = m->return_value;
2012
463d0d15 2013 if (MANAGER_IS_USER(m)) {
8ebfe0cb
DH
2014 log_debug("Exit.");
2015 goto finish;
2016 }
2017
2018 /* fallthrough */
b9080b03
FF
2019 case MANAGER_REBOOT:
2020 case MANAGER_POWEROFF:
2021 case MANAGER_HALT:
2022 case MANAGER_KEXEC: {
2023 static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
287419c1 2024 [MANAGER_EXIT] = "exit",
b9080b03
FF
2025 [MANAGER_REBOOT] = "reboot",
2026 [MANAGER_POWEROFF] = "poweroff",
2027 [MANAGER_HALT] = "halt",
2028 [MANAGER_KEXEC] = "kexec"
2029 };
2030
2031 assert_se(shutdown_verb = table[m->exit_code]);
e96d6be7 2032 arm_reboot_watchdog = m->exit_code == MANAGER_REBOOT;
b9080b03
FF
2033
2034 log_notice("Shutting down.");
2035 goto finish;
2036 }
2037
a16e1123
LP
2038 default:
2039 assert_not_reached("Unknown exit code.");
2040 }
2041 }
f170852a 2042
60918275 2043finish:
b87c2aa6
ZJS
2044 pager_close();
2045
97792515 2046 if (m)
81f5fc2d 2047 arg_shutdown_watchdog = m->shutdown_watchdog;
fe382237 2048
06d8d842 2049 m = manager_free(m);
60918275 2050
1f6b4113 2051 for (j = 0; j < ELEMENTSOF(arg_default_rlimit); j++)
a1e58e8e 2052 arg_default_rlimit[j] = mfree(arg_default_rlimit[j]);
c93ff2e9 2053
97b11eed 2054 arg_default_unit = mfree(arg_default_unit);
7d5ceb64 2055 arg_confirm_spawn = mfree(arg_confirm_spawn);
fe382237 2056 arg_join_controllers = strv_free_free(arg_join_controllers);
97b11eed 2057 arg_default_environment = strv_free(arg_default_environment);
525d3cc7 2058 arg_syscall_archs = set_free(arg_syscall_archs);
d3b1c508 2059
cc56fafe 2060 mac_selinux_finish();
b2bb3dbe 2061
a16e1123 2062 if (reexecute) {
664f88a7 2063 const char **args;
e564a982 2064 unsigned i, args_size;
a16e1123 2065
664f88a7
LP
2066 /* Close and disarm the watchdog, so that the new
2067 * instance can reinitialize it, but doesn't get
2068 * rebooted while we do that */
2069 watchdog_close(true);
a16e1123 2070
4096d6f5
LP
2071 /* Reset the RLIMIT_NOFILE to the kernel default, so
2072 * that the new systemd can pass the kernel default to
2073 * its child processes */
2074 if (saved_rlimit_nofile.rlim_cur > 0)
92ca4cac 2075 (void) setrlimit(RLIMIT_NOFILE, &saved_rlimit_nofile);
fb3ae275
LP
2076 if (saved_rlimit_memlock.rlim_cur != (rlim_t) -1)
2077 (void) setrlimit(RLIMIT_MEMLOCK, &saved_rlimit_memlock);
4096d6f5 2078
41669317 2079 if (switch_root_dir) {
cee530bb
LP
2080 /* Kill all remaining processes from the
2081 * initrd, but don't wait for them, so that we
2082 * can handle the SIGCHLD for them after
2083 * deserializing. */
0bee65f0 2084 broadcast_signal(SIGTERM, false, true);
bd3fa1d2 2085
5a4bf02f
HH
2086 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
2087 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
41669317 2088 if (r < 0)
da927ba9 2089 log_error_errno(r, "Failed to switch root, trying to continue: %m");
41669317 2090 }
a16e1123 2091
d03bc1b8 2092 args_size = MAX(6, argc+1);
e564a982 2093 args = newa(const char*, args_size);
a16e1123 2094
664f88a7 2095 if (!switch_root_init) {
5ffa8c81 2096 char sfd[DECIMAL_STR_MAX(int) + 1];
a16e1123 2097
664f88a7
LP
2098 /* First try to spawn ourselves with the right
2099 * path, and with full serialization. We do
2100 * this only if the user didn't specify an
2101 * explicit init to spawn. */
edb9aaa8 2102
d3b1c508 2103 assert(arg_serialization);
664f88a7 2104 assert(fds);
edb9aaa8 2105
5ffa8c81 2106 xsprintf(sfd, "%i", fileno(arg_serialization));
edb9aaa8 2107
664f88a7
LP
2108 i = 0;
2109 args[i++] = SYSTEMD_BINARY_PATH;
41669317 2110 if (switch_root_dir)
2660882b 2111 args[i++] = "--switched-root";
463d0d15 2112 args[i++] = arg_system ? "--system" : "--user";
664f88a7
LP
2113 args[i++] = "--deserialize";
2114 args[i++] = sfd;
2115 args[i++] = NULL;
edb9aaa8 2116
e564a982 2117 assert(i <= args_size);
dcadc967
EV
2118
2119 /*
2120 * We want valgrind to print its memory usage summary before reexecution.
2121 * Valgrind won't do this is on its own on exec(), but it will do it on exit().
2122 * Hence, to ensure we get a summary here, fork() off a child, let it exit() cleanly,
2123 * so that it prints the summary, and wait() for it in the parent, before proceeding into the exec().
2124 */
2125 valgrind_summary_hack();
2126
92ca4cac 2127 (void) execv(args[0], (char* const*) args);
664f88a7 2128 }
6e98720f 2129
664f88a7
LP
2130 /* Try the fallback, if there is any, without any
2131 * serialization. We pass the original argv[] and
2132 * envp[]. (Well, modulo the ordering changes due to
2133 * getopt() in argv[], and some cleanups in envp[],
2134 * but let's hope that doesn't matter.) */
a16e1123 2135
74ca738f 2136 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2137 fds = fdset_free(fds);
a16e1123 2138
bd64d82c
ZJS
2139 /* Reopen the console */
2140 (void) make_console_stdio();
2141
d3b1c508 2142 for (j = 1, i = 1; j < (unsigned) argc; j++)
664f88a7 2143 args[i++] = argv[j];
a16e1123 2144 args[i++] = NULL;
e564a982 2145 assert(i <= args_size);
b8f83232 2146
1b6d7fa7 2147 /* Reenable any blocked signals, especially important
5a85ca1c 2148 * if we switch from initial ramdisk to init=... */
ce30c8dc
LP
2149 (void) reset_all_signal_handlers();
2150 (void) reset_signal_mask();
5a85ca1c 2151
b8f83232
LP
2152 if (switch_root_init) {
2153 args[0] = switch_root_init;
92ca4cac 2154 (void) execv(args[0], (char* const*) args);
56f64d95 2155 log_warning_errno(errno, "Failed to execute configured init, trying fallback: %m");
b8f83232
LP
2156 }
2157
2158 args[0] = "/sbin/init";
92ca4cac 2159 (void) execv(args[0], (char* const*) args);
a16e1123 2160
745e2fb7
KS
2161 if (errno == ENOENT) {
2162 log_warning("No /sbin/init, trying fallback");
b8f83232 2163
745e2fb7
KS
2164 args[0] = "/bin/sh";
2165 args[1] = NULL;
92ca4cac 2166 (void) execv(args[0], (char* const*) args);
56f64d95 2167 log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
745e2fb7 2168 } else
56f64d95 2169 log_warning_errno(errno, "Failed to execute /sbin/init, giving up: %m");
a16e1123
LP
2170 }
2171
74ca738f 2172 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2173 fds = fdset_free(fds);
a16e1123 2174
349cc4a5 2175#if HAVE_VALGRIND_VALGRIND_H
54b434b1
LP
2176 /* If we are PID 1 and running under valgrind, then let's exit
2177 * here explicitly. valgrind will only generate nice output on
2178 * exit(), not on exec(), hence let's do the former not the
2179 * latter here. */
df0ff127 2180 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND)
54b434b1
LP
2181 return 0;
2182#endif
2183
b9080b03 2184 if (shutdown_verb) {
b1e90ec5 2185 char log_level[DECIMAL_STR_MAX(int) + 1];
287419c1
AC
2186 char exit_code[DECIMAL_STR_MAX(uint8_t) + 1];
2187 const char* command_line[11] = {
b9080b03
FF
2188 SYSTEMD_SHUTDOWN_BINARY_PATH,
2189 shutdown_verb,
b1e90ec5
ZJS
2190 "--log-level", log_level,
2191 "--log-target",
b9080b03 2192 };
b1e90ec5 2193 unsigned pos = 5;
e3e45d4f 2194 _cleanup_strv_free_ char **env_block = NULL;
15bd5aee
LP
2195
2196 assert(command_line[pos] == NULL);
e3e45d4f 2197 env_block = strv_copy(environ);
b9080b03 2198
5ffa8c81 2199 xsprintf(log_level, "%d", log_get_max_level());
b1e90ec5
ZJS
2200
2201 switch (log_get_target()) {
92ca4cac 2202
b1e90ec5
ZJS
2203 case LOG_TARGET_KMSG:
2204 case LOG_TARGET_JOURNAL_OR_KMSG:
2205 case LOG_TARGET_SYSLOG_OR_KMSG:
2206 command_line[pos++] = "kmsg";
2207 break;
2208
10f00ff1
ILG
2209 case LOG_TARGET_NULL:
2210 command_line[pos++] = "null";
2211 break;
2212
b1e90ec5
ZJS
2213 case LOG_TARGET_CONSOLE:
2214 default:
2215 command_line[pos++] = "console";
2216 break;
2217 };
2218
2219 if (log_get_show_color())
2220 command_line[pos++] = "--log-color";
2221
2222 if (log_get_show_location())
2223 command_line[pos++] = "--log-location";
2224
287419c1
AC
2225 if (streq(shutdown_verb, "exit")) {
2226 command_line[pos++] = "--exit-code";
2227 command_line[pos++] = exit_code;
97792515 2228 xsprintf(exit_code, "%d", retval);
287419c1
AC
2229 }
2230
26abdc73 2231 assert(pos < ELEMENTSOF(command_line));
b1e90ec5 2232
5146c619 2233 if (arm_reboot_watchdog && arg_shutdown_watchdog > 0 && arg_shutdown_watchdog != USEC_INFINITY) {
e3e45d4f 2234 char *e;
d18f337c 2235
e96d6be7
LP
2236 /* If we reboot let's set the shutdown
2237 * watchdog and tell the shutdown binary to
2238 * repeatedly ping it */
c2cc6b9a
LP
2239 r = watchdog_set_timeout(&arg_shutdown_watchdog);
2240 watchdog_close(r < 0);
e96d6be7 2241
e3e45d4f
SP
2242 /* Tell the binary how often to ping, ignore failure */
2243 if (asprintf(&e, "WATCHDOG_USEC="USEC_FMT, arg_shutdown_watchdog) > 0)
92ca4cac 2244 (void) strv_push(&env_block, e);
e3e45d4f 2245 } else
e96d6be7
LP
2246 watchdog_close(true);
2247
66713f77
LP
2248 /* Avoid the creation of new processes forked by the
2249 * kernel; at this point, we will not listen to the
2250 * signals anyway */
75f86906 2251 if (detect_container() <= 0)
e155a0aa 2252 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
ad929bcc 2253
d18f337c 2254 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
56f64d95 2255 log_error_errno(errno, "Failed to execute shutdown binary, %s: %m",
df0ff127 2256 getpid_cached() == 1 ? "freezing" : "quitting");
b9080b03
FF
2257 }
2258
df0ff127 2259 if (getpid_cached() == 1) {
cb6531be
ZJS
2260 if (error_message)
2261 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 2262 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
cb6531be 2263 "%s, freezing.", error_message);
b9e74c39 2264 freeze_or_reboot();
cb6531be 2265 }
c3b3c274 2266
60918275
LP
2267 return retval;
2268}