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