]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
Merge pull request #7388 from keszybz/doc-tweak
[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
bcde742e 771 (void) config_parse_many_nulstr(fn, conf_dirs_nulstr, "Manager\0", config_item_table_lookup, items, CONFIG_PARSE_WARN, 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
85cb4151 783static void set_manager_defaults(Manager *m) {
06af2a04
TB
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
7b46fc6a
LP
807static void set_manager_settings(Manager *m) {
808
809 assert(m);
810
811 m->confirm_spawn = arg_confirm_spawn;
812 m->runtime_watchdog = arg_runtime_watchdog;
813 m->shutdown_watchdog = arg_shutdown_watchdog;
814 m->cad_burst_action = arg_cad_burst_action;
815
816 manager_set_show_status(m, arg_show_status);
817}
818
f170852a
LP
819static int parse_argv(int argc, char *argv[]) {
820
821 enum {
822 ARG_LOG_LEVEL = 0x100,
823 ARG_LOG_TARGET,
bbe63281
LP
824 ARG_LOG_COLOR,
825 ARG_LOG_LOCATION,
2f198e2f 826 ARG_UNIT,
edb9aaa8 827 ARG_SYSTEM,
af2d49f7 828 ARG_USER,
e537352b 829 ARG_TEST,
b87c2aa6 830 ARG_NO_PAGER,
9ba0bc4e 831 ARG_VERSION,
80876c20 832 ARG_DUMP_CONFIGURATION_ITEMS,
9e58ff9c 833 ARG_DUMP_CORE,
b9e74c39 834 ARG_CRASH_CHVT,
9e58ff9c 835 ARG_CRASH_SHELL,
b9e74c39 836 ARG_CRASH_REBOOT,
a16e1123 837 ARG_CONFIRM_SPAWN,
9e58ff9c 838 ARG_SHOW_STATUS,
4288f619 839 ARG_DESERIALIZE,
2660882b 840 ARG_SWITCHED_ROOT,
0a494f1f 841 ARG_DEFAULT_STD_OUTPUT,
ee48dbd5
NC
842 ARG_DEFAULT_STD_ERROR,
843 ARG_MACHINE_ID
f170852a
LP
844 };
845
846 static const struct option options[] = {
a16e1123
LP
847 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
848 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
bbe63281
LP
849 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
850 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
2f198e2f 851 { "unit", required_argument, NULL, ARG_UNIT },
edb9aaa8 852 { "system", no_argument, NULL, ARG_SYSTEM },
af2d49f7 853 { "user", no_argument, NULL, ARG_USER },
a16e1123 854 { "test", no_argument, NULL, ARG_TEST },
b87c2aa6 855 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
a16e1123 856 { "help", no_argument, NULL, 'h' },
9ba0bc4e 857 { "version", no_argument, NULL, ARG_VERSION },
a16e1123 858 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
a5d87bf0 859 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
b9e74c39 860 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
a5d87bf0 861 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
b9e74c39 862 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
a5d87bf0 863 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
6e98720f 864 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
a16e1123 865 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
2660882b 866 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
0a494f1f
LP
867 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
868 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
ee48dbd5 869 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
fb472900 870 {}
f170852a
LP
871 };
872
873 int c, r;
874
875 assert(argc >= 1);
876 assert(argv);
877
df0ff127 878 if (getpid_cached() == 1)
b770165a
LP
879 opterr = 0;
880
099663ff 881 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
f170852a
LP
882
883 switch (c) {
884
885 case ARG_LOG_LEVEL:
fb472900
ZJS
886 r = log_set_max_level_from_string(optarg);
887 if (r < 0) {
f170852a
LP
888 log_error("Failed to parse log level %s.", optarg);
889 return r;
890 }
891
892 break;
893
894 case ARG_LOG_TARGET:
fb472900
ZJS
895 r = log_set_target_from_string(optarg);
896 if (r < 0) {
f170852a
LP
897 log_error("Failed to parse log target %s.", optarg);
898 return r;
899 }
900
901 break;
902
bbe63281
LP
903 case ARG_LOG_COLOR:
904
d0b170c8 905 if (optarg) {
fb472900
ZJS
906 r = log_show_color_from_string(optarg);
907 if (r < 0) {
d0b170c8
LP
908 log_error("Failed to parse log color setting %s.", optarg);
909 return r;
910 }
911 } else
912 log_show_color(true);
bbe63281
LP
913
914 break;
915
916 case ARG_LOG_LOCATION:
d0b170c8 917 if (optarg) {
fb472900
ZJS
918 r = log_show_location_from_string(optarg);
919 if (r < 0) {
d0b170c8
LP
920 log_error("Failed to parse log location setting %s.", optarg);
921 return r;
922 }
923 } else
924 log_show_location(true);
bbe63281
LP
925
926 break;
927
0a494f1f 928 case ARG_DEFAULT_STD_OUTPUT:
fb472900
ZJS
929 r = exec_output_from_string(optarg);
930 if (r < 0) {
0a494f1f
LP
931 log_error("Failed to parse default standard output setting %s.", optarg);
932 return r;
933 } else
934 arg_default_std_output = r;
935 break;
936
937 case ARG_DEFAULT_STD_ERROR:
fb472900
ZJS
938 r = exec_output_from_string(optarg);
939 if (r < 0) {
0a494f1f
LP
940 log_error("Failed to parse default standard error output setting %s.", optarg);
941 return r;
942 } else
943 arg_default_std_error = r;
944 break;
945
2f198e2f 946 case ARG_UNIT:
e6e242ad 947 r = free_and_strdup(&arg_default_unit, optarg);
23bbb0de
MS
948 if (r < 0)
949 return log_error_errno(r, "Failed to set default unit %s: %m", optarg);
f170852a
LP
950
951 break;
952
edb9aaa8 953 case ARG_SYSTEM:
463d0d15 954 arg_system = true;
edb9aaa8 955 break;
a5dab5ce 956
af2d49f7 957 case ARG_USER:
463d0d15 958 arg_system = false;
a5dab5ce 959 break;
a5dab5ce 960
e965d56d 961 case ARG_TEST:
fa0f4d8a 962 arg_action = ACTION_TEST;
b87c2aa6
ZJS
963 break;
964
965 case ARG_NO_PAGER:
966 arg_no_pager = true;
e965d56d
LP
967 break;
968
9ba0bc4e
ZJS
969 case ARG_VERSION:
970 arg_action = ACTION_VERSION;
971 break;
972
e537352b 973 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 974 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
975 break;
976
9e58ff9c 977 case ARG_DUMP_CORE:
b9e74c39
LP
978 if (!optarg)
979 arg_dump_core = true;
980 else {
981 r = parse_boolean(optarg);
982 if (r < 0)
983 return log_error_errno(r, "Failed to parse dump core boolean: %s", optarg);
984 arg_dump_core = r;
a5d87bf0 985 }
b9e74c39
LP
986 break;
987
988 case ARG_CRASH_CHVT:
989 r = parse_crash_chvt(optarg);
990 if (r < 0)
991 return log_error_errno(r, "Failed to parse crash virtual terminal index: %s", optarg);
9e58ff9c
LP
992 break;
993
994 case ARG_CRASH_SHELL:
b9e74c39
LP
995 if (!optarg)
996 arg_crash_shell = true;
997 else {
998 r = parse_boolean(optarg);
999 if (r < 0)
1000 return log_error_errno(r, "Failed to parse crash shell boolean: %s", optarg);
1001 arg_crash_shell = r;
1002 }
1003 break;
1004
1005 case ARG_CRASH_REBOOT:
1006 if (!optarg)
1007 arg_crash_reboot = true;
1008 else {
1009 r = parse_boolean(optarg);
1010 if (r < 0)
1011 return log_error_errno(r, "Failed to parse crash shell boolean: %s", optarg);
1012 arg_crash_reboot = r;
a5d87bf0 1013 }
9e58ff9c
LP
1014 break;
1015
80876c20 1016 case ARG_CONFIRM_SPAWN:
7d5ceb64
FB
1017 arg_confirm_spawn = mfree(arg_confirm_spawn);
1018
1019 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
1020 if (r < 0)
1021 return log_error_errno(r, "Failed to parse confirm spawn option: %m");
80876c20
LP
1022 break;
1023
9e58ff9c 1024 case ARG_SHOW_STATUS:
d450b6f2
ZJS
1025 if (optarg) {
1026 r = parse_show_status(optarg, &arg_show_status);
1027 if (r < 0) {
1028 log_error("Failed to parse show status boolean %s.", optarg);
1029 return r;
1030 }
1031 } else
1032 arg_show_status = SHOW_STATUS_YES;
6e98720f 1033 break;
a5d87bf0 1034
a16e1123
LP
1035 case ARG_DESERIALIZE: {
1036 int fd;
1037 FILE *f;
1038
01e10de3
LP
1039 r = safe_atoi(optarg, &fd);
1040 if (r < 0 || fd < 0) {
a16e1123 1041 log_error("Failed to parse deserialize option %s.", optarg);
b9e74c39 1042 return -EINVAL;
a16e1123
LP
1043 }
1044
b9e74c39 1045 (void) fd_cloexec(fd, true);
01e10de3
LP
1046
1047 f = fdopen(fd, "r");
4a62c710
MS
1048 if (!f)
1049 return log_error_errno(errno, "Failed to open serialization fd: %m");
a16e1123 1050
74ca738f 1051 safe_fclose(arg_serialization);
d3b1c508 1052 arg_serialization = f;
a16e1123
LP
1053
1054 break;
1055 }
1056
2660882b 1057 case ARG_SWITCHED_ROOT:
bf4df7c3 1058 arg_switched_root = true;
d03bc1b8
HH
1059 break;
1060
ee48dbd5
NC
1061 case ARG_MACHINE_ID:
1062 r = set_machine_id(optarg);
54500613
LP
1063 if (r < 0)
1064 return log_error_errno(r, "MachineID '%s' is not valid.", optarg);
ee48dbd5
NC
1065 break;
1066
f170852a 1067 case 'h':
fa0f4d8a 1068 arg_action = ACTION_HELP;
f170852a
LP
1069 break;
1070
1d2e23ab
LP
1071 case 'D':
1072 log_set_max_level(LOG_DEBUG);
1073 break;
1074
099663ff
LP
1075 case 'b':
1076 case 's':
1077 case 'z':
1078 /* Just to eat away the sysvinit kernel
1079 * cmdline args without getopt() error
1080 * messages that we'll parse in
1081 * parse_proc_cmdline_word() or ignore. */
f170852a 1082
099663ff 1083 case '?':
df0ff127 1084 if (getpid_cached() != 1)
099663ff 1085 return -EINVAL;
601185b4
ZJS
1086 else
1087 return 0;
099663ff 1088
601185b4
ZJS
1089 default:
1090 assert_not_reached("Unhandled option code.");
f170852a
LP
1091 }
1092
df0ff127 1093 if (optind < argc && getpid_cached() != 1) {
d821e6d6
LP
1094 /* Hmm, when we aren't run as init system
1095 * let's complain about excess arguments */
1096
1097 log_error("Excess arguments.");
1098 return -EINVAL;
1099 }
1100
f170852a
LP
1101 return 0;
1102}
1103
1104static int help(void) {
1105
2e33c433 1106 printf("%s [OPTIONS...]\n\n"
af2d49f7 1107 "Starts up and maintains the system or user services.\n\n"
e537352b 1108 " -h --help Show this help\n"
cb4069d9 1109 " --version Show version\n"
e537352b 1110 " --test Determine startup sequence, dump it and exit\n"
b87c2aa6 1111 " --no-pager Do not pipe output into a pager\n"
80876c20 1112 " --dump-configuration-items Dump understood unit configuration items\n"
9e58ff9c 1113 " --unit=UNIT Set default unit\n"
edb9aaa8 1114 " --system Run a system instance, even if PID != 1\n"
af2d49f7 1115 " --user Run a user instance\n"
b9e74c39
LP
1116 " --dump-core[=BOOL] Dump core on crash\n"
1117 " --crash-vt=NR Change to specified VT on crash\n"
1118 " --crash-reboot[=BOOL] Reboot on crash\n"
1119 " --crash-shell[=BOOL] Run shell on crash\n"
1120 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1121 " --show-status[=BOOL] Show status updates on the console during bootup\n"
c1dc6153 1122 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
9e58ff9c 1123 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
b9e74c39
LP
1124 " --log-color[=BOOL] Highlight important log messages\n"
1125 " --log-location[=BOOL] Include code location in log messages\n"
0a494f1f
LP
1126 " --default-standard-output= Set default standard output for services\n"
1127 " --default-standard-error= Set default standard error output for services\n",
5b6319dc 1128 program_invocation_short_name);
f170852a
LP
1129
1130 return 0;
1131}
1132
b3680f49 1133static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds, bool switching_root) {
48b90859
LP
1134 _cleanup_fdset_free_ FDSet *fds = NULL;
1135 _cleanup_fclose_ FILE *f = NULL;
a16e1123
LP
1136 int r;
1137
1138 assert(m);
1139 assert(_f);
1140 assert(_fds);
1141
6b78f9b4 1142 r = manager_open_serialization(m, &f);
48b90859
LP
1143 if (r < 0)
1144 return log_error_errno(r, "Failed to create serialization file: %m");
a16e1123 1145
71445ae7 1146 /* Make sure nothing is really destructed when we shut down */
313cefa1 1147 m->n_reloading++;
718db961 1148 bus_manager_send_reloading(m, true);
71445ae7 1149
6b78f9b4 1150 fds = fdset_new();
48b90859
LP
1151 if (!fds)
1152 return log_oom();
a16e1123 1153
b3680f49 1154 r = manager_serialize(m, f, fds, switching_root);
48b90859
LP
1155 if (r < 0)
1156 return log_error_errno(r, "Failed to serialize state: %m");
a16e1123 1157
48b90859
LP
1158 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1159 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
a16e1123 1160
6b78f9b4 1161 r = fd_cloexec(fileno(f), false);
48b90859
LP
1162 if (r < 0)
1163 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
a16e1123 1164
6b78f9b4 1165 r = fdset_cloexec(fds, false);
48b90859
LP
1166 if (r < 0)
1167 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
a16e1123
LP
1168
1169 *_f = f;
1170 *_fds = fds;
1171
48b90859
LP
1172 f = NULL;
1173 fds = NULL;
a16e1123 1174
48b90859 1175 return 0;
a16e1123
LP
1176}
1177
4096d6f5
LP
1178static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
1179 struct rlimit nl;
1180 int r;
6385cb31
CB
1181 int min_max;
1182 _cleanup_free_ char *nr_open = NULL;
4096d6f5
LP
1183
1184 assert(saved_rlimit);
1185
1186 /* Save the original RLIMIT_NOFILE so that we can reset it
1187 * later when transitioning from the initrd to the main
1188 * systemd or suchlike. */
4a62c710 1189 if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0)
3ce40911 1190 return log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5
LP
1191
1192 /* Make sure forked processes get the default kernel setting */
1193 if (!arg_default_rlimit[RLIMIT_NOFILE]) {
1194 struct rlimit *rl;
1195
1196 rl = newdup(struct rlimit, saved_rlimit, 1);
1197 if (!rl)
1198 return log_oom();
1199
1200 arg_default_rlimit[RLIMIT_NOFILE] = rl;
1201 }
1202
6385cb31
CB
1203 /* Get current RLIMIT_NOFILE maximum compiled into the kernel. */
1204 r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
1205 if (r == 0)
1206 r = safe_atoi(nr_open, &min_max);
1207 /* If we fail, fallback to the hard-coded kernel limit of 1024 * 1024. */
1208 if (r < 0)
1209 min_max = 1024 * 1024;
1210
4096d6f5 1211 /* Bump up the resource limit for ourselves substantially */
6385cb31 1212 nl.rlim_cur = nl.rlim_max = min_max;
4096d6f5 1213 r = setrlimit_closest(RLIMIT_NOFILE, &nl);
23bbb0de 1214 if (r < 0)
3ce40911 1215 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5
LP
1216
1217 return 0;
1218}
1219
fb3ae275
LP
1220static int bump_rlimit_memlock(struct rlimit *saved_rlimit) {
1221 int r;
1222
1223 assert(saved_rlimit);
1224 assert(getuid() == 0);
1225
1226 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even though we have CAP_IPC_LOCK which
1227 * should normally disable such checks. We need them to implement IPAccessAllow= and IPAccessDeny=, hence let's
1228 * bump the value high enough for the root user. */
1229
1230 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit) < 0)
1231 return log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
1232
1233 r = setrlimit_closest(RLIMIT_MEMLOCK, &RLIMIT_MAKE_CONST(1024ULL*1024ULL*16ULL));
1234 if (r < 0)
1235 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1236
1237 return 0;
1238}
1239
80758717 1240static void test_usr(void) {
80758717 1241
ed1c99fc 1242 /* Check that /usr is not a separate fs */
80758717 1243
871c44a7
LP
1244 if (dir_is_empty("/usr") <= 0)
1245 return;
1246
8b173b5e 1247 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
871c44a7
LP
1248 "Some things will probably break (sometimes even silently) in mysterious ways. "
1249 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1250}
1251
a07fdfa3
LP
1252static int initialize_join_controllers(void) {
1253 /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
1254 * + "net_prio". We'd like to add "cpuset" to the mix, but
f131770b 1255 * "cpuset" doesn't really work for groups with no initialized
a07fdfa3
LP
1256 * attributes. */
1257
1258 arg_join_controllers = new(char**, 3);
1259 if (!arg_join_controllers)
1260 return -ENOMEM;
1261
1262 arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
fe382237
LP
1263 if (!arg_join_controllers[0])
1264 goto oom;
a6b26d90 1265
fe382237
LP
1266 arg_join_controllers[1] = strv_new("net_cls", "net_prio", NULL);
1267 if (!arg_join_controllers[1])
1268 goto oom;
a07fdfa3 1269
fe382237 1270 arg_join_controllers[2] = NULL;
a07fdfa3 1271 return 0;
fe382237
LP
1272
1273oom:
1274 arg_join_controllers = strv_free_free(arg_join_controllers);
1275 return -ENOMEM;
a07fdfa3
LP
1276}
1277
d3b1c508 1278static int enforce_syscall_archs(Set *archs) {
349cc4a5 1279#if HAVE_SECCOMP
d3b1c508
LP
1280 int r;
1281
83f12b27
FS
1282 if (!is_seccomp_available())
1283 return 0;
1284
469830d1 1285 r = seccomp_restrict_archs(arg_syscall_archs);
d3b1c508 1286 if (r < 0)
469830d1 1287 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
d3b1c508 1288#endif
469830d1 1289 return 0;
d3b1c508
LP
1290}
1291
b6e2f329
LP
1292static int status_welcome(void) {
1293 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1294 int r;
1295
1296 r = parse_env_file("/etc/os-release", NEWLINE,
1297 "PRETTY_NAME", &pretty_name,
1298 "ANSI_COLOR", &ansi_color,
1299 NULL);
ece174c5 1300 if (r == -ENOENT)
5ae4d543
LP
1301 r = parse_env_file("/usr/lib/os-release", NEWLINE,
1302 "PRETTY_NAME", &pretty_name,
1303 "ANSI_COLOR", &ansi_color,
1304 NULL);
b6e2f329
LP
1305
1306 if (r < 0 && r != -ENOENT)
da927ba9 1307 log_warning_errno(r, "Failed to read os-release file: %m");
b6e2f329 1308
dc9b5816
ZJS
1309 if (log_get_show_color())
1310 return status_printf(NULL, false, false,
1311 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1312 isempty(ansi_color) ? "1" : ansi_color,
1313 isempty(pretty_name) ? "Linux" : pretty_name);
1314 else
1315 return status_printf(NULL, false, false,
1316 "\nWelcome to %s!\n",
1317 isempty(pretty_name) ? "Linux" : pretty_name);
b6e2f329
LP
1318}
1319
fdd25311
LP
1320static int write_container_id(void) {
1321 const char *c;
19854865 1322 int r;
fdd25311
LP
1323
1324 c = getenv("container");
1325 if (isempty(c))
1326 return 0;
1327
8612da97
LP
1328 RUN_WITH_UMASK(0022)
1329 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
19854865 1330 if (r < 0)
f1f849b0 1331 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
19854865
LP
1332
1333 return 1;
1334}
1335
1336static int bump_unix_max_dgram_qlen(void) {
1337 _cleanup_free_ char *qlen = NULL;
1338 unsigned long v;
1339 int r;
1340
1341 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel
1342 * default of 16 is simply too low. We set the value really
1343 * really early during boot, so that it is actually applied to
1344 * all our sockets, including the $NOTIFY_SOCKET one. */
1345
1346 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1347 if (r < 0)
1348 return log_warning_errno(r, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1349
1350 r = safe_atolu(qlen, &v);
1351 if (r < 0)
1352 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length, ignoring: %m");
1353
1354 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1355 return 0;
1356
1357 qlen = mfree(qlen);
1358 if (asprintf(&qlen, "%lu\n", DEFAULT_UNIX_MAX_DGRAM_QLEN) < 0)
1359 return log_oom();
1360
1361 r = write_string_file("/proc/sys/net/unix/max_dgram_qlen", qlen, 0);
1362 if (r < 0)
1363 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1364 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1365
1366 return 1;
fdd25311
LP
1367}
1368
32391275
FB
1369static int fixup_environment(void) {
1370 _cleanup_free_ char *term = NULL;
1371 int r;
1372
84af7821
LP
1373 /* We expect the environment to be set correctly
1374 * if run inside a container. */
1375 if (detect_container() > 0)
1376 return 0;
1377
32391275
FB
1378 /* When started as PID1, the kernel uses /dev/console
1379 * for our stdios and uses TERM=linux whatever the
1380 * backend device used by the console. We try to make
1381 * a better guess here since some consoles might not
1382 * have support for color mode for example.
1383 *
1384 * However if TERM was configured through the kernel
1385 * command line then leave it alone. */
1386
1d84ad94 1387 r = proc_cmdline_get_key("TERM", 0, &term);
32391275
FB
1388 if (r < 0)
1389 return r;
32391275 1390 if (r == 0) {
6af760f3 1391 term = strdup(default_term_for_tty("/dev/console"));
32391275 1392 if (!term)
84af7821 1393 return -ENOMEM;
32391275
FB
1394 }
1395
1396 if (setenv("TERM", term, 1) < 0)
1397 return -errno;
1398
1399 return 0;
1400}
1401
6808a0bc
LP
1402static void redirect_telinit(int argc, char *argv[]) {
1403
1404 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1405
1406#if HAVE_SYSV_COMPAT
1407 if (getpid_cached() == 1)
1408 return;
1409
1410 if (!strstr(program_invocation_short_name, "init"))
1411 return;
1412
1413 execv(SYSTEMCTL_BINARY_PATH, argv);
1414 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
1415 exit(1);
1416#endif
1417}
1418
4a36297c
LP
1419static int become_shutdown(
1420 const char *shutdown_verb,
1421 int retval,
1422 bool arm_reboot_watchdog) {
1423
1424 char log_level[DECIMAL_STR_MAX(int) + 1],
1425 exit_code[DECIMAL_STR_MAX(uint8_t) + 1];
1426
1427 const char* command_line[11] = {
1428 SYSTEMD_SHUTDOWN_BINARY_PATH,
1429 shutdown_verb,
1430 "--log-level", log_level,
1431 "--log-target",
1432 };
1433
1434 _cleanup_strv_free_ char **env_block = NULL;
1435 size_t pos = 5;
1436 int r;
1437
1438 assert(command_line[pos] == NULL);
1439 env_block = strv_copy(environ);
1440
1441 xsprintf(log_level, "%d", log_get_max_level());
1442
1443 switch (log_get_target()) {
1444
1445 case LOG_TARGET_KMSG:
1446 case LOG_TARGET_JOURNAL_OR_KMSG:
1447 case LOG_TARGET_SYSLOG_OR_KMSG:
1448 command_line[pos++] = "kmsg";
1449 break;
1450
1451 case LOG_TARGET_NULL:
1452 command_line[pos++] = "null";
1453 break;
1454
1455 case LOG_TARGET_CONSOLE:
1456 default:
1457 command_line[pos++] = "console";
1458 break;
1459 };
1460
1461 if (log_get_show_color())
1462 command_line[pos++] = "--log-color";
1463
1464 if (log_get_show_location())
1465 command_line[pos++] = "--log-location";
1466
1467 if (streq(shutdown_verb, "exit")) {
1468 command_line[pos++] = "--exit-code";
1469 command_line[pos++] = exit_code;
1470 xsprintf(exit_code, "%d", retval);
1471 }
1472
1473 assert(pos < ELEMENTSOF(command_line));
1474
1475 if (arm_reboot_watchdog && arg_shutdown_watchdog > 0 && arg_shutdown_watchdog != USEC_INFINITY) {
1476 char *e;
1477
1478 /* If we reboot let's set the shutdown
1479 * watchdog and tell the shutdown binary to
1480 * repeatedly ping it */
1481 r = watchdog_set_timeout(&arg_shutdown_watchdog);
1482 watchdog_close(r < 0);
1483
1484 /* Tell the binary how often to ping, ignore failure */
1485 if (asprintf(&e, "WATCHDOG_USEC="USEC_FMT, arg_shutdown_watchdog) > 0)
1486 (void) strv_push(&env_block, e);
1487 } else
1488 watchdog_close(true);
1489
1490 /* Avoid the creation of new processes forked by the
1491 * kernel; at this point, we will not listen to the
1492 * signals anyway */
1493 if (detect_container() <= 0)
1494 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
1495
1496 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
1497 return -errno;
1498}
1499
e839bafd
LP
1500static void initialize_clock(void) {
1501 int r;
1502
1503 if (clock_is_localtime(NULL) > 0) {
1504 int min;
1505
1506 /*
1507 * The very first call of settimeofday() also does a time warp in the kernel.
1508 *
1509 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to take care
1510 * of maintaining the RTC and do all adjustments. This matches the behavior of Windows, which leaves
1511 * the RTC alone if the registry tells that the RTC runs in UTC.
1512 */
1513 r = clock_set_timezone(&min);
1514 if (r < 0)
1515 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
1516 else
1517 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1518
1519 } else if (!in_initrd()) {
1520 /*
1521 * Do a dummy very first call to seal the kernel's time warp magic.
1522 *
1523 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with LOCAL, but the
1524 * real system could be set up that way. In such case, we need to delay the time-warp or the sealing
1525 * until we reach the real system.
1526 *
1527 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably, the time
1528 * will jump or be incorrect at every daylight saving time change. All kernel local time concepts will
1529 * be treated as UTC that way.
1530 */
1531 (void) clock_reset_timewarp();
1532 }
1533
1534 r = clock_apply_epoch();
1535 if (r < 0)
1536 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1537 else if (r > 0)
1538 log_info("System time before build time, advancing clock.");
1539}
1540
1e41242e
LP
1541static void initialize_coredump(bool skip_setup) {
1542
1543 if (getpid_cached() != 1)
1544 return;
1545
1546 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1547 * will process core dumps for system services by default. */
1548 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1549 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1550
1551 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1552 * until the systemd-coredump tool is enabled via sysctl. */
1553 if (!skip_setup)
1554 (void) write_string_file("/proc/sys/kernel/core_pattern", "|/bin/false", 0);
1555}
1556
60918275
LP
1557int main(int argc, char *argv[]) {
1558 Manager *m = NULL;
22f4096c 1559 int r, retval = EXIT_FAILURE;
9d76d730
LP
1560 usec_t before_startup, after_startup;
1561 char timespan[FORMAT_TIMESPAN_MAX];
a16e1123
LP
1562 FDSet *fds = NULL;
1563 bool reexecute = false;
b9080b03 1564 const char *shutdown_verb = NULL;
86caf095
LP
1565 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL;
1566 dual_timestamp userspace_timestamp = DUAL_TIMESTAMP_NULL;
1567 dual_timestamp kernel_timestamp = DUAL_TIMESTAMP_NULL;
1568 dual_timestamp security_start_timestamp = DUAL_TIMESTAMP_NULL;
1569 dual_timestamp security_finish_timestamp = DUAL_TIMESTAMP_NULL;
5d6b1584 1570 static char systemd[] = "systemd";
2660882b 1571 bool skip_setup = false;
d3b1c508 1572 unsigned j;
0b3325e7 1573 bool loaded_policy = false;
e96d6be7 1574 bool arm_reboot_watchdog = false;
bf4df7c3 1575 bool queue_default_job = false;
fd130612 1576 bool first_boot = false;
41669317 1577 char *switch_root_dir = NULL, *switch_root_init = NULL;
fb3ae275 1578 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0), saved_rlimit_memlock = RLIMIT_MAKE_CONST((rlim_t) -1);
cb6531be 1579 const char *error_message = NULL;
27b14a22 1580
6808a0bc 1581 redirect_telinit(argc, argv);
2cb1a60d 1582
c3a170f3
HH
1583 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
1584 dual_timestamp_get(&userspace_timestamp);
1585
0b3325e7
LP
1586 /* Determine if this is a reexecution or normal bootup. We do
1587 * the full command line parsing much later, so let's just
1588 * have a quick peek here. */
db813c2a
LP
1589 if (strv_find(argv+1, "--deserialize"))
1590 skip_setup = true;
0b3325e7 1591
2660882b
LP
1592 /* If we have switched root, do all the special setup
1593 * things */
db813c2a
LP
1594 if (strv_find(argv+1, "--switched-root"))
1595 skip_setup = false;
d03bc1b8 1596
f3b6a3ed
LP
1597 /* If we get started via the /sbin/init symlink then we are
1598 called 'init'. After a subsequent reexecution we are then
1599 called 'systemd'. That is confusing, hence let's call us
1600 systemd right-away. */
f3b6a3ed 1601 program_invocation_short_name = systemd;
eee8b7ab 1602 (void) prctl(PR_SET_NAME, systemd);
5d6b1584 1603
9a0e6896
LP
1604 saved_argv = argv;
1605 saved_argc = argc;
f3b6a3ed 1606
c1dc6153 1607 log_set_upgrade_syslog_to_journal(true);
bbe63281 1608
df0ff127 1609 if (getpid_cached() == 1) {
48a601fe 1610 /* Disable the umask logic */
90dc8c2e
MG
1611 umask(0);
1612
48a601fe
LP
1613 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
1614 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
1615 * child process right before execve()'ing the actual binary, at a point in time where socket
1616 * activation stderr/stdout area already set up. */
1617 log_set_always_reopen_console(true);
1618 }
1619
df0ff127 1620 if (getpid_cached() == 1 && detect_container() <= 0) {
4f8d551f 1621
a866073d 1622 /* Running outside of a container as PID 1 */
463d0d15 1623 arg_system = true;
a866073d
LP
1624 log_set_target(LOG_TARGET_KMSG);
1625 log_open();
1626
21bf2ab0 1627 if (in_initrd())
c3a170f3 1628 initrd_timestamp = userspace_timestamp;
c3ba6250 1629
2660882b 1630 if (!skip_setup) {
d723cd65
AK
1631 r = mount_setup_early();
1632 if (r < 0) {
eee8b7ab 1633 error_message = "Failed to mount early API filesystems";
d723cd65
AK
1634 goto finish;
1635 }
eee8b7ab 1636
c2e0d600 1637 dual_timestamp_get(&security_start_timestamp);
cb6531be
ZJS
1638 if (mac_selinux_setup(&loaded_policy) < 0) {
1639 error_message = "Failed to load SELinux policy";
0b3325e7 1640 goto finish;
cb6531be
ZJS
1641 } else if (mac_smack_setup(&loaded_policy) < 0) {
1642 error_message = "Failed to load SMACK policy";
ffbd2c4d 1643 goto finish;
96694e99
IP
1644 } else if (ima_setup() < 0) {
1645 error_message = "Failed to load IMA policy";
1646 goto finish;
cb6531be 1647 }
c2e0d600 1648 dual_timestamp_get(&security_finish_timestamp);
81611586 1649 }
0b3325e7 1650
c3dacc8b 1651 if (mac_selinux_init() < 0) {
cb6531be 1652 error_message = "Failed to initialize SELinux policy";
0ff4cdd9 1653 goto finish;
cb6531be 1654 }
7948c4df 1655
e839bafd
LP
1656 if (!skip_setup)
1657 initialize_clock();
a866073d
LP
1658
1659 /* Set the default for later on, but don't actually
1660 * open the logs like this for now. Note that if we
1661 * are transitioning from the initrd there might still
1662 * be journal fd open, and we shouldn't attempt
1663 * opening that before we parsed /proc/cmdline which
1664 * might redirect output elsewhere. */
1665 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1666
df0ff127 1667 } else if (getpid_cached() == 1) {
a866073d 1668 /* Running inside a container, as PID 1 */
463d0d15 1669 arg_system = true;
a866073d 1670 log_set_target(LOG_TARGET_CONSOLE);
99f09825 1671 log_close_console(); /* force reopen of /dev/console */
a866073d
LP
1672 log_open();
1673
eee8b7ab 1674 /* For later on, see above... */
a866073d
LP
1675 log_set_target(LOG_TARGET_JOURNAL);
1676
c3a170f3
HH
1677 /* clear the kernel timestamp,
1678 * because we are in a container */
0f5f63c3 1679 kernel_timestamp = DUAL_TIMESTAMP_NULL;
c3a170f3 1680 } else {
a866073d 1681 /* Running as user instance */
463d0d15 1682 arg_system = false;
eeecf6e6 1683 log_set_target(LOG_TARGET_AUTO);
871e5809 1684 log_open();
c3a170f3
HH
1685
1686 /* clear the kernel timestamp,
1687 * because we are not PID 1 */
6513d561 1688 kernel_timestamp = DUAL_TIMESTAMP_NULL;
bbe63281 1689 }
a5dab5ce 1690
1e41242e 1691 initialize_coredump(skip_setup);
15a90032 1692
6edefe0b 1693 if (arg_system) {
84af7821
LP
1694 if (fixup_environment() < 0) {
1695 error_message = "Failed to fix up PID1 environment";
1696 goto finish;
1697 }
32391275 1698
3a18b604
FB
1699 /* Try to figure out if we can use colors with the console. No
1700 * need to do that for user instances since they never log
1701 * into the console. */
1702 log_show_color(colors_enabled());
c76cf844
AK
1703 r = make_null_stdio();
1704 if (r < 0)
1705 log_warning_errno(r, "Failed to redirect standard streams to /dev/null: %m");
3a18b604
FB
1706 }
1707
a07fdfa3 1708 r = initialize_join_controllers();
cb6531be 1709 if (r < 0) {
ff9b60f3 1710 error_message = "Failed to initialize cgroup controllers";
0c85a4f3 1711 goto finish;
cb6531be 1712 }
0c85a4f3 1713
f170852a
LP
1714 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1715 * /proc/$PID/fd is available. */
df0ff127 1716 if (getpid_cached() == 1) {
f84f9974 1717
a132bef0 1718 /* Load the kernel modules early. */
2e75e2a8
DM
1719 if (!skip_setup)
1720 kmod_setup();
2e75e2a8 1721
0c85a4f3 1722 r = mount_setup(loaded_policy);
cb6531be
ZJS
1723 if (r < 0) {
1724 error_message = "Failed to mount API filesystems";
8efe3c01 1725 goto finish;
cb6531be 1726 }
0c85a4f3 1727 }
4ade7963
LP
1728
1729 /* Reset all signal handlers. */
ce30c8dc
LP
1730 (void) reset_all_signal_handlers();
1731 (void) ignore_signals(SIGNALS_IGNORE, -1);
078e4539 1732
f5058264 1733 arg_default_tasks_max = system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE, 100U);
79baeeb9 1734
cb6531be
ZJS
1735 if (parse_config_file() < 0) {
1736 error_message = "Failed to parse config file";
487393e9 1737 goto finish;
cb6531be 1738 }
487393e9 1739
463d0d15 1740 if (arg_system) {
1d84ad94 1741 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
b5884878 1742 if (r < 0)
da927ba9 1743 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
b5884878 1744 }
f170852a 1745
1de1c9c3
LP
1746 /* Note that this also parses bits from the kernel command
1747 * line, including "debug". */
f170852a
LP
1748 log_parse_environment();
1749
cb6531be
ZJS
1750 if (parse_argv(argc, argv) < 0) {
1751 error_message = "Failed to parse commandline arguments";
f170852a 1752 goto finish;
cb6531be 1753 }
f170852a 1754
10c961b9
AK
1755 /* Initialize default unit */
1756 if (!arg_default_unit) {
f6dd106c
AK
1757 arg_default_unit = strdup(SPECIAL_DEFAULT_TARGET);
1758 if (!arg_default_unit) {
1759 r = log_oom();
10c961b9
AK
1760 error_message = "Failed to set default unit";
1761 goto finish;
1762 }
1763 }
1764
6bae23a0
TB
1765 if (arg_action == ACTION_TEST &&
1766 geteuid() == 0) {
b5c6cf87
LP
1767 log_error("Don't run test mode as root.");
1768 goto finish;
1769 }
1770
463d0d15 1771 if (!arg_system &&
6bae23a0
TB
1772 arg_action == ACTION_RUN &&
1773 sd_booted() <= 0) {
1774 log_error("Trying to run as user instance, but the system has not been booted with systemd.");
1775 goto finish;
1776 }
1777
463d0d15 1778 if (arg_system &&
fe783b03
LP
1779 arg_action == ACTION_RUN &&
1780 running_in_chroot() > 0) {
1781 log_error("Cannot be run in a chroot() environment.");
1782 goto finish;
1783 }
1784
4c701096 1785 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP)) {
ea4b98e6 1786 pager_open(arg_no_pager, false);
74e7579c
AK
1787 skip_setup = true;
1788 }
b87c2aa6 1789
fa0f4d8a 1790 if (arg_action == ACTION_HELP) {
f170852a
LP
1791 retval = help();
1792 goto finish;
9ba0bc4e
ZJS
1793 } else if (arg_action == ACTION_VERSION) {
1794 retval = version();
1795 goto finish;
fa0f4d8a 1796 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
13811bf9 1797 pager_open(arg_no_pager, false);
e537352b 1798 unit_dump_config_items(stdout);
22f4096c 1799 retval = EXIT_SUCCESS;
e537352b 1800 goto finish;
f170852a
LP
1801 }
1802
463d0d15 1803 if (!arg_system &&
8be28fb1
KS
1804 !getenv("XDG_RUNTIME_DIR")) {
1805 log_error("Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
1806 goto finish;
1807 }
1808
4c701096 1809 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
f170852a 1810
871e5809
LP
1811 /* Close logging fds, in order not to confuse fdset below */
1812 log_close();
1813
a16e1123 1814 /* Remember open file descriptors for later deserialization */
dea374e8
LP
1815 if (arg_action == ACTION_RUN) {
1816 r = fdset_new_fill(&fds);
1817 if (r < 0) {
1818 log_emergency_errno(r, "Failed to allocate fd set: %m");
1819 error_message = "Failed to allocate fd set";
1820 goto finish;
1821 } else
1822 fdset_cloexec(fds, true);
a16e1123 1823
dea374e8
LP
1824 if (arg_serialization)
1825 assert_se(fdset_remove(fds, fileno(arg_serialization)) >= 0);
a16e1123 1826
dea374e8
LP
1827 if (arg_system)
1828 /* Become a session leader if we aren't one yet. */
1829 setsid();
1830 }
4ade7963 1831
befb5b6a 1832 /* Move out of the way, so that we won't block unmounts */
d250afe7 1833 assert_se(chdir("/") == 0);
befb5b6a 1834
2146621b
LP
1835 /* Reset the console, but only if this is really init and we
1836 * are freshly booted */
463d0d15 1837 if (arg_system && arg_action == ACTION_RUN) {
56d96fc0
LP
1838
1839 /* If we are init, we connect stdin/stdout/stderr to
1840 * /dev/null and make sure we don't have a controlling
1841 * tty. */
1842 release_terminal();
1843
df0ff127 1844 if (getpid_cached() == 1 && !skip_setup)
56d96fc0
LP
1845 console_setup();
1846 }
4ade7963 1847
18149b9f 1848 /* Open the logging devices, if possible and necessary */
843d2643 1849 log_open();
4ade7963 1850
b6e2f329
LP
1851 if (arg_show_status == _SHOW_STATUS_UNSET)
1852 arg_show_status = SHOW_STATUS_YES;
1853
5373d602
LP
1854 /* Make sure we leave a core dump without panicing the
1855 * kernel. */
df0ff127 1856 if (getpid_cached() == 1) {
4fc935ca 1857 install_crash_handler();
97c4f35c 1858
0c85a4f3
LP
1859 r = mount_cgroup_controllers(arg_join_controllers);
1860 if (r < 0)
1861 goto finish;
1862 }
1863
463d0d15 1864 if (arg_system) {
75f86906 1865 int v;
c20f5ac7 1866
0d8c31ff
ZJS
1867 log_info(PACKAGE_STRING " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
1868 arg_action == ACTION_TEST ? "test " : "" );
c20f5ac7 1869
75f86906
LP
1870 v = detect_virtualization();
1871 if (v > 0)
1872 log_info("Detected virtualization %s.", virtualization_to_string(v));
c20f5ac7 1873
fdd25311
LP
1874 write_container_id();
1875
d3f86679 1876 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
d9d93745 1877
26a1efdf
LP
1878 if (in_initrd())
1879 log_info("Running in initial RAM disk.");
fd130612
LP
1880 else {
1881 /* Let's check whether we are in first boot, i.e. whether /etc is still unpopulated. We use
1882 * /etc/machine-id as flag file, for this: if it exists we assume /etc is populated, if it
1883 * doesn't it's unpopulated. This allows container managers and installers to provision a
1884 * couple of files already. If the container manager wants to provision the machine ID itself
1885 * it should pass $container_uuid to PID 1. */
1886
1887 first_boot = access("/etc/machine-id", F_OK) < 0;
1888 if (first_boot)
1889 log_info("Running with unpopulated /etc.");
1890 }
d8160f21 1891 } else {
1f97091d
LP
1892 _cleanup_free_ char *t;
1893
1894 t = uid_to_name(getuid());
a68aef7a
LP
1895 log_debug(PACKAGE_STRING " running in %suser mode for user " UID_FMT "/%s. (" SYSTEMD_FEATURES ")",
1896 arg_action == ACTION_TEST ? " test" : "", getuid(), strna(t));
d8160f21 1897 }
a5dab5ce 1898
dea374e8
LP
1899 if (arg_action == ACTION_RUN) {
1900 if (arg_system && !skip_setup) {
1901 if (arg_show_status > 0)
1902 status_welcome();
888c6216 1903
dea374e8
LP
1904 hostname_setup();
1905 machine_id_setup(NULL, arg_machine_id, NULL);
1906 loopback_setup();
1907 bump_unix_max_dgram_qlen();
490aed58 1908
dea374e8
LP
1909 test_usr();
1910 }
302e8c4c 1911
dea374e8
LP
1912 if (arg_system && arg_runtime_watchdog > 0 && arg_runtime_watchdog != USEC_INFINITY)
1913 watchdog_set_timeout(&arg_runtime_watchdog);
e96d6be7 1914
dea374e8
LP
1915 if (arg_timer_slack_nsec != NSEC_INFINITY)
1916 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
1917 log_error_errno(errno, "Failed to adjust timer slack: %m");
aa0f64ac 1918
dea374e8
LP
1919 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
1920 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
1921 if (r < 0) {
1922 log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
1923 error_message = "Failed to drop capability bounding set of usermode helpers";
1924 goto finish;
1925 }
1926 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
1927 if (r < 0) {
1928 log_emergency_errno(r, "Failed to drop capability bounding set: %m");
1929 error_message = "Failed to drop capability bounding set";
1930 goto finish;
1931 }
939b8f14 1932 }
ec8927ca 1933
dea374e8
LP
1934 if (arg_syscall_archs) {
1935 r = enforce_syscall_archs(arg_syscall_archs);
1936 if (r < 0) {
1937 error_message = "Failed to set syscall architectures";
1938 goto finish;
1939 }
cb6531be 1940 }
d3b1c508 1941
dea374e8
LP
1942 if (!arg_system)
1943 /* Become reaper of our children */
1944 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
1945 log_warning_errno(errno, "Failed to make us a subreaper: %m");
d4447f4d 1946
fb3ae275 1947 if (arg_system) {
dea374e8
LP
1948 /* Bump up RLIMIT_NOFILE for systemd itself */
1949 (void) bump_rlimit_nofile(&saved_rlimit_nofile);
fb3ae275
LP
1950 (void) bump_rlimit_memlock(&saved_rlimit_memlock);
1951 }
dea374e8 1952 }
4096d6f5 1953
e0a3da1f
ZJS
1954 r = manager_new(arg_system ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
1955 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
1956 &m);
e96d6be7 1957 if (r < 0) {
da927ba9 1958 log_emergency_errno(r, "Failed to allocate manager object: %m");
cb6531be 1959 error_message = "Failed to allocate manager object";
60918275
LP
1960 goto finish;
1961 }
1962
c3a170f3
HH
1963 m->userspace_timestamp = userspace_timestamp;
1964 m->kernel_timestamp = kernel_timestamp;
c3a170f3 1965 m->initrd_timestamp = initrd_timestamp;
c2e0d600
TA
1966 m->security_start_timestamp = security_start_timestamp;
1967 m->security_finish_timestamp = security_finish_timestamp;
9e58ff9c 1968
85cb4151 1969 set_manager_defaults(m);
7b46fc6a 1970 set_manager_settings(m);
fd130612 1971 manager_set_first_boot(m, first_boot);
27d340c7 1972
bf4df7c3 1973 /* Remember whether we should queue the default job */
d3b1c508 1974 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 1975
9d76d730
LP
1976 before_startup = now(CLOCK_MONOTONIC);
1977
d3b1c508 1978 r = manager_startup(m, arg_serialization, fds);
58f88d92 1979 if (r < 0) {
da927ba9 1980 log_error_errno(r, "Failed to fully start up daemon: %m");
58f88d92
ZJS
1981 goto finish;
1982 }
a16e1123 1983
bf4df7c3
LP
1984 /* This will close all file descriptors that were opened, but
1985 * not claimed by any unit. */
2feceb5e 1986 fds = fdset_free(fds);
f50e0a01 1987
74ca738f 1988 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
1989
1990 if (queue_default_job) {
4afd3348 1991 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1c27d3f3 1992 Unit *target = NULL;
bacbccb7 1993 Job *default_unit_job;
398ef8ba 1994
fa0f4d8a 1995 log_debug("Activating default unit: %s", arg_default_unit);
a16e1123 1996
e96d6be7 1997 r = manager_load_unit(m, arg_default_unit, NULL, &error, &target);
718db961
LP
1998 if (r < 0)
1999 log_error("Failed to load default target: %s", bus_error_message(&error, r));
4c701096 2000 else if (IN_SET(target->load_state, UNIT_ERROR, UNIT_NOT_FOUND))
c33b3297 2001 log_error_errno(target->load_error, "Failed to load default target: %m");
ac155bb8 2002 else if (target->load_state == UNIT_MASKED)
6daf4f90 2003 log_error("Default target masked.");
27b14a22 2004
ac155bb8 2005 if (!target || target->load_state != UNIT_LOADED) {
a16e1123 2006 log_info("Trying to load rescue target...");
1c27d3f3 2007
e96d6be7
LP
2008 r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target);
2009 if (r < 0) {
4104970e 2010 log_emergency("Failed to load rescue target: %s", bus_error_message(&error, r));
cb6531be 2011 error_message = "Failed to load rescue target";
a16e1123 2012 goto finish;
4c701096 2013 } else if (IN_SET(target->load_state, UNIT_ERROR, UNIT_NOT_FOUND)) {
c33b3297 2014 log_emergency_errno(target->load_error, "Failed to load rescue target: %m");
cb6531be 2015 error_message = "Failed to load rescue target";
1c27d3f3 2016 goto finish;
ac155bb8 2017 } else if (target->load_state == UNIT_MASKED) {
4104970e 2018 log_emergency("Rescue target masked.");
cb6531be 2019 error_message = "Rescue target masked";
00dc5d76 2020 goto finish;
a16e1123
LP
2021 }
2022 }
37d88da7 2023
ac155bb8 2024 assert(target->load_state == UNIT_LOADED);
00dc5d76 2025
fa0f4d8a 2026 if (arg_action == ACTION_TEST) {
40d50879 2027 printf("-> By units:\n");
a16e1123
LP
2028 manager_dump_units(m, stdout, "\t");
2029 }
2030
4bd29fe5 2031 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, &error, &default_unit_job);
ab17a050 2032 if (r == -EPERM) {
718db961 2033 log_debug("Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
ab17a050 2034
5022ce71
LP
2035 sd_bus_error_free(&error);
2036
4bd29fe5 2037 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, &error, &default_unit_job);
ab17a050 2038 if (r < 0) {
4104970e 2039 log_emergency("Failed to start default target: %s", bus_error_message(&error, r));
cb6531be 2040 error_message = "Failed to start default target";
ab17a050
LP
2041 goto finish;
2042 }
2043 } else if (r < 0) {
4104970e 2044 log_emergency("Failed to isolate default target: %s", bus_error_message(&error, r));
cb6531be 2045 error_message = "Failed to isolate default target";
37d88da7
LP
2046 goto finish;
2047 }
ab17a050 2048
bacbccb7 2049 m->default_unit_job_id = default_unit_job->id;
60918275 2050
07672f49
LP
2051 after_startup = now(CLOCK_MONOTONIC);
2052 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2053 "Loaded units and determined initial transaction in %s.",
fdb14b7e 2054 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 2055
fa0f4d8a 2056 if (arg_action == ACTION_TEST) {
40d50879 2057 printf("-> By jobs:\n");
a16e1123 2058 manager_dump_jobs(m, stdout, "\t");
22f4096c 2059 retval = EXIT_SUCCESS;
a16e1123
LP
2060 goto finish;
2061 }
e965d56d 2062 }
d46de8a1 2063
a16e1123 2064 for (;;) {
e96d6be7
LP
2065 r = manager_loop(m);
2066 if (r < 0) {
da927ba9 2067 log_emergency_errno(r, "Failed to run main loop: %m");
cb6531be 2068 error_message = "Failed to run main loop";
a16e1123
LP
2069 goto finish;
2070 }
11dd41ce 2071
a16e1123 2072 switch (m->exit_code) {
e965d56d 2073
a16e1123 2074 case MANAGER_RELOAD:
e015090f 2075 log_info("Reloading.");
06af2a04
TB
2076
2077 r = parse_config_file();
2078 if (r < 0)
2079 log_error("Failed to parse config file.");
2080
85cb4151 2081 set_manager_defaults(m);
06af2a04 2082
e96d6be7
LP
2083 r = manager_reload(m);
2084 if (r < 0)
da927ba9 2085 log_error_errno(r, "Failed to reload: %m");
a16e1123 2086 break;
cea8e32e 2087
a16e1123 2088 case MANAGER_REEXECUTE:
664f88a7 2089
cb6531be 2090 if (prepare_reexecute(m, &arg_serialization, &fds, false) < 0) {
6b9af963 2091 error_message = "Failed to prepare for reexecution";
a16e1123 2092 goto finish;
cb6531be 2093 }
60918275 2094
a16e1123 2095 reexecute = true;
e015090f 2096 log_notice("Reexecuting.");
a16e1123
LP
2097 goto finish;
2098
664f88a7
LP
2099 case MANAGER_SWITCH_ROOT:
2100 /* Steal the switch root parameters */
41669317 2101 switch_root_dir = m->switch_root;
664f88a7
LP
2102 switch_root_init = m->switch_root_init;
2103 m->switch_root = m->switch_root_init = NULL;
2104
2105 if (!switch_root_init)
cb6531be 2106 if (prepare_reexecute(m, &arg_serialization, &fds, true) < 0) {
6b9af963 2107 error_message = "Failed to prepare for reexecution";
664f88a7 2108 goto finish;
cb6531be 2109 }
664f88a7
LP
2110
2111 reexecute = true;
2112 log_notice("Switching root.");
2113 goto finish;
2114
287419c1 2115 case MANAGER_EXIT:
97792515
LP
2116 retval = m->return_value;
2117
463d0d15 2118 if (MANAGER_IS_USER(m)) {
8ebfe0cb
DH
2119 log_debug("Exit.");
2120 goto finish;
2121 }
2122
2123 /* fallthrough */
b9080b03
FF
2124 case MANAGER_REBOOT:
2125 case MANAGER_POWEROFF:
2126 case MANAGER_HALT:
2127 case MANAGER_KEXEC: {
2128 static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
287419c1 2129 [MANAGER_EXIT] = "exit",
b9080b03
FF
2130 [MANAGER_REBOOT] = "reboot",
2131 [MANAGER_POWEROFF] = "poweroff",
2132 [MANAGER_HALT] = "halt",
2133 [MANAGER_KEXEC] = "kexec"
2134 };
2135
2136 assert_se(shutdown_verb = table[m->exit_code]);
e96d6be7 2137 arm_reboot_watchdog = m->exit_code == MANAGER_REBOOT;
b9080b03
FF
2138
2139 log_notice("Shutting down.");
2140 goto finish;
2141 }
2142
a16e1123
LP
2143 default:
2144 assert_not_reached("Unknown exit code.");
2145 }
2146 }
f170852a 2147
60918275 2148finish:
b87c2aa6
ZJS
2149 pager_close();
2150
97792515 2151 if (m)
81f5fc2d 2152 arg_shutdown_watchdog = m->shutdown_watchdog;
fe382237 2153
06d8d842 2154 m = manager_free(m);
60918275 2155
1f6b4113 2156 for (j = 0; j < ELEMENTSOF(arg_default_rlimit); j++)
a1e58e8e 2157 arg_default_rlimit[j] = mfree(arg_default_rlimit[j]);
c93ff2e9 2158
97b11eed 2159 arg_default_unit = mfree(arg_default_unit);
7d5ceb64 2160 arg_confirm_spawn = mfree(arg_confirm_spawn);
fe382237 2161 arg_join_controllers = strv_free_free(arg_join_controllers);
97b11eed 2162 arg_default_environment = strv_free(arg_default_environment);
525d3cc7 2163 arg_syscall_archs = set_free(arg_syscall_archs);
d3b1c508 2164
cc56fafe 2165 mac_selinux_finish();
b2bb3dbe 2166
a16e1123 2167 if (reexecute) {
664f88a7 2168 const char **args;
e564a982 2169 unsigned i, args_size;
a16e1123 2170
664f88a7
LP
2171 /* Close and disarm the watchdog, so that the new
2172 * instance can reinitialize it, but doesn't get
2173 * rebooted while we do that */
2174 watchdog_close(true);
a16e1123 2175
4096d6f5
LP
2176 /* Reset the RLIMIT_NOFILE to the kernel default, so
2177 * that the new systemd can pass the kernel default to
2178 * its child processes */
2179 if (saved_rlimit_nofile.rlim_cur > 0)
92ca4cac 2180 (void) setrlimit(RLIMIT_NOFILE, &saved_rlimit_nofile);
fb3ae275
LP
2181 if (saved_rlimit_memlock.rlim_cur != (rlim_t) -1)
2182 (void) setrlimit(RLIMIT_MEMLOCK, &saved_rlimit_memlock);
4096d6f5 2183
41669317 2184 if (switch_root_dir) {
cee530bb
LP
2185 /* Kill all remaining processes from the
2186 * initrd, but don't wait for them, so that we
2187 * can handle the SIGCHLD for them after
2188 * deserializing. */
0bee65f0 2189 broadcast_signal(SIGTERM, false, true);
bd3fa1d2 2190
5a4bf02f
HH
2191 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
2192 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
41669317 2193 if (r < 0)
da927ba9 2194 log_error_errno(r, "Failed to switch root, trying to continue: %m");
41669317 2195 }
a16e1123 2196
d03bc1b8 2197 args_size = MAX(6, argc+1);
e564a982 2198 args = newa(const char*, args_size);
a16e1123 2199
664f88a7 2200 if (!switch_root_init) {
5ffa8c81 2201 char sfd[DECIMAL_STR_MAX(int) + 1];
a16e1123 2202
664f88a7
LP
2203 /* First try to spawn ourselves with the right
2204 * path, and with full serialization. We do
2205 * this only if the user didn't specify an
2206 * explicit init to spawn. */
edb9aaa8 2207
d3b1c508 2208 assert(arg_serialization);
664f88a7 2209 assert(fds);
edb9aaa8 2210
5ffa8c81 2211 xsprintf(sfd, "%i", fileno(arg_serialization));
edb9aaa8 2212
664f88a7
LP
2213 i = 0;
2214 args[i++] = SYSTEMD_BINARY_PATH;
41669317 2215 if (switch_root_dir)
2660882b 2216 args[i++] = "--switched-root";
463d0d15 2217 args[i++] = arg_system ? "--system" : "--user";
664f88a7
LP
2218 args[i++] = "--deserialize";
2219 args[i++] = sfd;
2220 args[i++] = NULL;
edb9aaa8 2221
e564a982 2222 assert(i <= args_size);
dcadc967
EV
2223
2224 /*
2225 * We want valgrind to print its memory usage summary before reexecution.
2226 * Valgrind won't do this is on its own on exec(), but it will do it on exit().
2227 * Hence, to ensure we get a summary here, fork() off a child, let it exit() cleanly,
2228 * so that it prints the summary, and wait() for it in the parent, before proceeding into the exec().
2229 */
2230 valgrind_summary_hack();
2231
92ca4cac 2232 (void) execv(args[0], (char* const*) args);
664f88a7 2233 }
6e98720f 2234
664f88a7
LP
2235 /* Try the fallback, if there is any, without any
2236 * serialization. We pass the original argv[] and
2237 * envp[]. (Well, modulo the ordering changes due to
2238 * getopt() in argv[], and some cleanups in envp[],
2239 * but let's hope that doesn't matter.) */
a16e1123 2240
74ca738f 2241 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2242 fds = fdset_free(fds);
a16e1123 2243
bd64d82c
ZJS
2244 /* Reopen the console */
2245 (void) make_console_stdio();
2246
d3b1c508 2247 for (j = 1, i = 1; j < (unsigned) argc; j++)
664f88a7 2248 args[i++] = argv[j];
a16e1123 2249 args[i++] = NULL;
e564a982 2250 assert(i <= args_size);
b8f83232 2251
1b6d7fa7 2252 /* Reenable any blocked signals, especially important
5a85ca1c 2253 * if we switch from initial ramdisk to init=... */
ce30c8dc
LP
2254 (void) reset_all_signal_handlers();
2255 (void) reset_signal_mask();
5a85ca1c 2256
b8f83232
LP
2257 if (switch_root_init) {
2258 args[0] = switch_root_init;
92ca4cac 2259 (void) execv(args[0], (char* const*) args);
56f64d95 2260 log_warning_errno(errno, "Failed to execute configured init, trying fallback: %m");
b8f83232
LP
2261 }
2262
2263 args[0] = "/sbin/init";
92ca4cac 2264 (void) execv(args[0], (char* const*) args);
a16e1123 2265
9b9881d7
AJ
2266 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
2267 ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL,
2268 "Failed to execute /sbin/init");
2269
745e2fb7
KS
2270 if (errno == ENOENT) {
2271 log_warning("No /sbin/init, trying fallback");
b8f83232 2272
745e2fb7
KS
2273 args[0] = "/bin/sh";
2274 args[1] = NULL;
92ca4cac 2275 (void) execv(args[0], (char* const*) args);
56f64d95 2276 log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
745e2fb7 2277 } else
56f64d95 2278 log_warning_errno(errno, "Failed to execute /sbin/init, giving up: %m");
9b9881d7
AJ
2279
2280 error_message = "Failed to execute fallback shell";
a16e1123
LP
2281 }
2282
74ca738f 2283 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2284 fds = fdset_free(fds);
a16e1123 2285
349cc4a5 2286#if HAVE_VALGRIND_VALGRIND_H
54b434b1
LP
2287 /* If we are PID 1 and running under valgrind, then let's exit
2288 * here explicitly. valgrind will only generate nice output on
2289 * exit(), not on exec(), hence let's do the former not the
2290 * latter here. */
df0ff127 2291 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND)
54b434b1
LP
2292 return 0;
2293#endif
2294
b9080b03 2295 if (shutdown_verb) {
4a36297c 2296 r = become_shutdown(shutdown_verb, retval, arm_reboot_watchdog);
ad929bcc 2297
4a36297c 2298 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
9b9881d7 2299 error_message = "Failed to execute shutdown binary";
b9080b03
FF
2300 }
2301
df0ff127 2302 if (getpid_cached() == 1) {
cb6531be
ZJS
2303 if (error_message)
2304 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 2305 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
cb6531be 2306 "%s, freezing.", error_message);
b9e74c39 2307 freeze_or_reboot();
cb6531be 2308 }
c3b3c274 2309
60918275
LP
2310 return retval;
2311}