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