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