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