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