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