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