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