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