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