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