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