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