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