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