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
manager_find_user_config_paths(char *** ret_files,char *** ret_dirs)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
console_setup(void)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
set_machine_id(const char * m)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
parse_proc_cmdline_item(const char * key,const char * value,void * data)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
config_parse_default_timeout_abort(const char * unit,const char * filename,unsigned line,const char * section,unsigned section_line,const char * lvalue,int ltype,const char * rvalue,void * data,void * userdata)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
config_parse_oom_score_adjust(const char * unit,const char * filename,unsigned line,const char * section,unsigned section_line,const char * lvalue,int ltype,const char * rvalue,void * data,void * userdata)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
parse_config_file(void)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
set_manager_defaults(Manager * m)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
set_manager_settings(Manager * m)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
parse_argv(int argc,char * argv[])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
help(void)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
prepare_reexecute(Manager * m,FILE ** ret_f,FDSet ** ret_fds,bool switching_root)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
bump_file_max_and_nr_open(void)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
bump_rlimit_nofile(const struct rlimit * saved_rlimit)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
bump_rlimit_memlock(const struct rlimit * saved_rlimit)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
test_usr(void)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 http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1299 }
1300
enforce_syscall_archs(Set * archs)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
status_welcome(void)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
write_container_id(void)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
bump_unix_max_dgram_qlen(void)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
fixup_environment(void)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
redirect_telinit(int argc,char * argv[])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
become_shutdown(const char * shutdown_verb,int retval)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
initialize_clock(void)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
apply_clock_update(void)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
cmdline_take_random_seed(void)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
initialize_coredump(bool skip_setup)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
initialize_core_pattern(bool skip_setup)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
update_cpu_affinity(bool skip_setup)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
update_numa_policy(bool skip_setup)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
filter_args(const char * dst[],size_t * dst_index,char ** src,int argc)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 if (startswith(src[i],
1725 in_initrd() ? "rd.systemd.unit=" : "systemd.unit="))
1726 continue;
1727
1728 if (runlevel_to_target(src[i]))
1729 continue;
1730
1731 /* Seems we have a good old option. Let's pass it over to the new instance. */
1732 dst[(*dst_index)++] = src[i];
1733 }
1734 }
1735
do_reexecute(ManagerObjective objective,int argc,char * argv[],const struct rlimit * saved_rlimit_nofile,const struct rlimit * saved_rlimit_memlock,FDSet * fds,const char * switch_root_dir,const char * switch_root_init,const char ** ret_error_message)1736 static int do_reexecute(
1737 ManagerObjective objective,
1738 int argc,
1739 char* argv[],
1740 const struct rlimit *saved_rlimit_nofile,
1741 const struct rlimit *saved_rlimit_memlock,
1742 FDSet *fds,
1743 const char *switch_root_dir,
1744 const char *switch_root_init,
1745 const char **ret_error_message) {
1746
1747 size_t i, args_size;
1748 const char **args;
1749 int r;
1750
1751 assert(IN_SET(objective, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT));
1752 assert(argc >= 0);
1753 assert(saved_rlimit_nofile);
1754 assert(saved_rlimit_memlock);
1755 assert(ret_error_message);
1756
1757 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1758 * rebooted while we do that */
1759 watchdog_close(true);
1760
1761 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1762 * the kernel default to its child processes */
1763 if (saved_rlimit_nofile->rlim_cur != 0)
1764 (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
1765 if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
1766 (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
1767
1768 if (switch_root_dir) {
1769 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can
1770 * handle the SIGCHLD for them after deserializing. */
1771 broadcast_signal(SIGTERM, false, true, arg_default_timeout_stop_usec);
1772
1773 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1774 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
1775 if (r < 0)
1776 log_error_errno(r, "Failed to switch root, trying to continue: %m");
1777 }
1778
1779 args_size = argc + 6;
1780 args = newa(const char*, args_size);
1781
1782 if (!switch_root_init) {
1783 char sfd[DECIMAL_STR_MAX(int)];
1784
1785 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1786 * only if the user didn't specify an explicit init to spawn. */
1787
1788 assert(arg_serialization);
1789 assert(fds);
1790
1791 xsprintf(sfd, "%i", fileno(arg_serialization));
1792
1793 i = 1; /* Leave args[0] empty for now. */
1794 filter_args(args, &i, argv, argc);
1795
1796 if (switch_root_dir)
1797 args[i++] = "--switched-root";
1798 args[i++] = arg_system ? "--system" : "--user";
1799 args[i++] = "--deserialize";
1800 args[i++] = sfd;
1801 args[i++] = NULL;
1802
1803 assert(i <= args_size);
1804
1805 /*
1806 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1807 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
1808 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1809 * and wait() for it in the parent, before proceeding into the exec().
1810 */
1811 valgrind_summary_hack();
1812
1813 args[0] = SYSTEMD_BINARY_PATH;
1814 (void) execv(args[0], (char* const*) args);
1815
1816 if (objective == MANAGER_REEXECUTE) {
1817 *ret_error_message = "Failed to execute our own binary";
1818 return log_error_errno(errno, "Failed to execute our own binary %s: %m", args[0]);
1819 }
1820
1821 log_debug_errno(errno, "Failed to execute our own binary %s, trying fallback: %m", args[0]);
1822 }
1823
1824 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1825 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1826 * but let's hope that doesn't matter.) */
1827
1828 arg_serialization = safe_fclose(arg_serialization);
1829 fds = fdset_free(fds);
1830
1831 /* Reopen the console */
1832 (void) make_console_stdio();
1833
1834 i = 1; /* Leave args[0] empty for now. */
1835 for (int j = 1; j <= argc; j++)
1836 args[i++] = argv[j];
1837 assert(i <= args_size);
1838
1839 /* Re-enable any blocked signals, especially important if we switch from initial ramdisk to init=... */
1840 (void) reset_all_signal_handlers();
1841 (void) reset_signal_mask();
1842 (void) rlimit_nofile_safe();
1843
1844 if (switch_root_init) {
1845 args[0] = switch_root_init;
1846 (void) execve(args[0], (char* const*) args, saved_env);
1847 log_warning_errno(errno, "Failed to execute configured init %s, trying fallback: %m", args[0]);
1848 }
1849
1850 args[0] = "/sbin/init";
1851 (void) execv(args[0], (char* const*) args);
1852 r = -errno;
1853
1854 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1855 ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL,
1856 "Failed to execute /sbin/init");
1857
1858 *ret_error_message = "Failed to execute fallback shell";
1859 if (r == -ENOENT) {
1860 log_warning("No /sbin/init, trying fallback");
1861
1862 args[0] = "/bin/sh";
1863 args[1] = NULL;
1864 (void) execve(args[0], (char* const*) args, saved_env);
1865 return log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
1866 } else
1867 return log_error_errno(r, "Failed to execute /sbin/init, giving up: %m");
1868 }
1869
invoke_main_loop(Manager * m,const struct rlimit * saved_rlimit_nofile,const struct rlimit * saved_rlimit_memlock,int * ret_retval,const char ** ret_shutdown_verb,FDSet ** ret_fds,char ** ret_switch_root_dir,char ** ret_switch_root_init,const char ** ret_error_message)1870 static int invoke_main_loop(
1871 Manager *m,
1872 const struct rlimit *saved_rlimit_nofile,
1873 const struct rlimit *saved_rlimit_memlock,
1874 int *ret_retval, /* Return parameters relevant for shutting down */
1875 const char **ret_shutdown_verb, /* … */
1876 FDSet **ret_fds, /* Return parameters for reexecuting */
1877 char **ret_switch_root_dir, /* … */
1878 char **ret_switch_root_init, /* … */
1879 const char **ret_error_message) {
1880
1881 int r;
1882
1883 assert(m);
1884 assert(saved_rlimit_nofile);
1885 assert(saved_rlimit_memlock);
1886 assert(ret_retval);
1887 assert(ret_shutdown_verb);
1888 assert(ret_fds);
1889 assert(ret_switch_root_dir);
1890 assert(ret_switch_root_init);
1891 assert(ret_error_message);
1892
1893 for (;;) {
1894 int objective = manager_loop(m);
1895 if (objective < 0) {
1896 *ret_error_message = "Failed to run main loop";
1897 return log_emergency_errno(objective, "Failed to run main loop: %m");
1898 }
1899
1900 switch (objective) {
1901
1902 case MANAGER_RELOAD: {
1903 LogTarget saved_log_target;
1904 int saved_log_level;
1905
1906 log_info("Reloading.");
1907
1908 /* First, save any overridden log level/target, then parse the configuration file,
1909 * which might change the log level to new settings. */
1910
1911 saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
1912 saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
1913
1914 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
1915
1916 set_manager_defaults(m);
1917 set_manager_settings(m);
1918
1919 update_cpu_affinity(false);
1920 update_numa_policy(false);
1921
1922 if (saved_log_level >= 0)
1923 manager_override_log_level(m, saved_log_level);
1924 if (saved_log_target >= 0)
1925 manager_override_log_target(m, saved_log_target);
1926
1927 if (manager_reload(m) < 0)
1928 /* Reloading failed before the point of no return.
1929 * Let's continue running as if nothing happened. */
1930 m->objective = MANAGER_OK;
1931
1932 continue;
1933 }
1934
1935 case MANAGER_REEXECUTE:
1936 r = prepare_reexecute(m, &arg_serialization, ret_fds, false);
1937 if (r < 0) {
1938 *ret_error_message = "Failed to prepare for reexecution";
1939 return r;
1940 }
1941
1942 log_notice("Reexecuting.");
1943
1944 *ret_retval = EXIT_SUCCESS;
1945 *ret_shutdown_verb = NULL;
1946 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1947
1948 return objective;
1949
1950 case MANAGER_SWITCH_ROOT:
1951 if (!m->switch_root_init) {
1952 r = prepare_reexecute(m, &arg_serialization, ret_fds, true);
1953 if (r < 0) {
1954 *ret_error_message = "Failed to prepare for reexecution";
1955 return r;
1956 }
1957 } else
1958 *ret_fds = NULL;
1959
1960 log_notice("Switching root.");
1961
1962 *ret_retval = EXIT_SUCCESS;
1963 *ret_shutdown_verb = NULL;
1964
1965 /* Steal the switch root parameters */
1966 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
1967 *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
1968
1969 return objective;
1970
1971 case MANAGER_EXIT:
1972 if (MANAGER_IS_USER(m)) {
1973 log_debug("Exit.");
1974
1975 *ret_retval = m->return_value;
1976 *ret_shutdown_verb = NULL;
1977 *ret_fds = NULL;
1978 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1979
1980 return objective;
1981 }
1982
1983 _fallthrough_;
1984 case MANAGER_REBOOT:
1985 case MANAGER_POWEROFF:
1986 case MANAGER_HALT:
1987 case MANAGER_KEXEC: {
1988 static const char* const table[_MANAGER_OBJECTIVE_MAX] = {
1989 [MANAGER_EXIT] = "exit",
1990 [MANAGER_REBOOT] = "reboot",
1991 [MANAGER_POWEROFF] = "poweroff",
1992 [MANAGER_HALT] = "halt",
1993 [MANAGER_KEXEC] = "kexec",
1994 };
1995
1996 log_notice("Shutting down.");
1997
1998 *ret_retval = m->return_value;
1999 assert_se(*ret_shutdown_verb = table[m->objective]);
2000 *ret_fds = NULL;
2001 *ret_switch_root_dir = *ret_switch_root_init = NULL;
2002
2003 return objective;
2004 }
2005
2006 default:
2007 assert_not_reached();
2008 }
2009 }
2010 }
2011
log_execution_mode(bool * ret_first_boot)2012 static void log_execution_mode(bool *ret_first_boot) {
2013 assert(ret_first_boot);
2014
2015 if (arg_system) {
2016 struct utsname uts;
2017 int v;
2018
2019 log_info("systemd " GIT_VERSION " running in %ssystem mode (%s)",
2020 arg_action == ACTION_TEST ? "test " : "",
2021 systemd_features);
2022
2023 v = detect_virtualization();
2024 if (v > 0)
2025 log_info("Detected virtualization %s.", virtualization_to_string(v));
2026
2027 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2028
2029 if (in_initrd()) {
2030 *ret_first_boot = false;
2031 log_info("Running in initial RAM disk.");
2032 } else {
2033 int r;
2034 _cleanup_free_ char *id_text = NULL;
2035
2036 /* Let's check whether we are in first boot. We use /etc/machine-id as flag file
2037 * for this: If it is missing or contains the value "uninitialized", this is the
2038 * first boot. In any other case, it is not. This allows container managers and
2039 * installers to provision a couple of files already. If the container manager
2040 * wants to provision the machine ID itself it should pass $container_uuid to PID 1. */
2041
2042 r = read_one_line_file("/etc/machine-id", &id_text);
2043 if (r < 0 || streq(id_text, "uninitialized")) {
2044 if (r < 0 && r != -ENOENT)
2045 log_warning_errno(r, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2046
2047 *ret_first_boot = true;
2048 log_info("Detected first boot.");
2049 } else {
2050 *ret_first_boot = false;
2051 log_debug("Detected initialized system, this is not the first boot.");
2052 }
2053 }
2054
2055 assert_se(uname(&uts) >= 0);
2056
2057 if (strverscmp_improved(uts.release, KERNEL_BASELINE_VERSION) < 0)
2058 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2059 "Your mileage may vary.", uts.release, KERNEL_BASELINE_VERSION);
2060 else
2061 log_debug("Kernel version %s, our baseline is %s", uts.release, KERNEL_BASELINE_VERSION);
2062 } else {
2063 if (DEBUG_LOGGING) {
2064 _cleanup_free_ char *t = NULL;
2065
2066 t = uid_to_name(getuid());
2067 log_debug("systemd " GIT_VERSION " running in %suser mode for user " UID_FMT "/%s. (%s)",
2068 arg_action == ACTION_TEST ? " test" : "",
2069 getuid(), strna(t), systemd_features);
2070 }
2071
2072 *ret_first_boot = false;
2073 }
2074 }
2075
initialize_runtime(bool skip_setup,bool first_boot,struct rlimit * saved_rlimit_nofile,struct rlimit * saved_rlimit_memlock,const char ** ret_error_message)2076 static int initialize_runtime(
2077 bool skip_setup,
2078 bool first_boot,
2079 struct rlimit *saved_rlimit_nofile,
2080 struct rlimit *saved_rlimit_memlock,
2081 const char **ret_error_message) {
2082 int r;
2083
2084 assert(ret_error_message);
2085
2086 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2087 *
2088 * - Some only apply to --system instances
2089 * - Some only apply to --user instances
2090 * - Some only apply when we first start up, but not when we reexecute
2091 */
2092
2093 if (arg_action != ACTION_RUN)
2094 return 0;
2095
2096 update_cpu_affinity(skip_setup);
2097 update_numa_policy(skip_setup);
2098
2099 if (arg_system) {
2100 /* Make sure we leave a core dump without panicking the kernel. */
2101 install_crash_handler();
2102
2103 if (!skip_setup) {
2104 r = mount_cgroup_controllers();
2105 if (r < 0) {
2106 *ret_error_message = "Failed to mount cgroup hierarchies";
2107 return r;
2108 }
2109
2110 status_welcome();
2111 (void) hostname_setup(true);
2112 /* Force transient machine-id on first boot. */
2113 machine_id_setup(NULL, first_boot, arg_machine_id, NULL);
2114 (void) loopback_setup();
2115 bump_unix_max_dgram_qlen();
2116 bump_file_max_and_nr_open();
2117 test_usr();
2118 write_container_id();
2119 }
2120
2121 if (arg_watchdog_device) {
2122 r = watchdog_set_device(arg_watchdog_device);
2123 if (r < 0)
2124 log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device);
2125 }
2126 } else {
2127 _cleanup_free_ char *p = NULL;
2128
2129 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2130 * user mode. In system mode mount_setup() already did that. */
2131
2132 r = xdg_user_runtime_dir(&p, "/systemd");
2133 if (r < 0) {
2134 *ret_error_message = "$XDG_RUNTIME_DIR is not set";
2135 return log_emergency_errno(r, "Failed to determine $XDG_RUNTIME_DIR path: %m");
2136 }
2137
2138 (void) mkdir_p_label(p, 0755);
2139 (void) make_inaccessible_nodes(p, UID_INVALID, GID_INVALID);
2140 }
2141
2142 if (arg_timer_slack_nsec != NSEC_INFINITY)
2143 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
2144 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
2145
2146 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
2147 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
2148 if (r < 0) {
2149 *ret_error_message = "Failed to drop capability bounding set of usermode helpers";
2150 return log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
2151 }
2152
2153 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
2154 if (r < 0) {
2155 *ret_error_message = "Failed to drop capability bounding set";
2156 return log_emergency_errno(r, "Failed to drop capability bounding set: %m");
2157 }
2158 }
2159
2160 if (arg_system && arg_no_new_privs) {
2161 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
2162 *ret_error_message = "Failed to disable new privileges";
2163 return log_emergency_errno(errno, "Failed to disable new privileges: %m");
2164 }
2165 }
2166
2167 if (arg_syscall_archs) {
2168 r = enforce_syscall_archs(arg_syscall_archs);
2169 if (r < 0) {
2170 *ret_error_message = "Failed to set syscall architectures";
2171 return r;
2172 }
2173 }
2174
2175 if (!arg_system)
2176 /* Become reaper of our children */
2177 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
2178 log_warning_errno(errno, "Failed to make us a subreaper, ignoring: %m");
2179
2180 /* Bump up RLIMIT_NOFILE for systemd itself */
2181 (void) bump_rlimit_nofile(saved_rlimit_nofile);
2182 (void) bump_rlimit_memlock(saved_rlimit_memlock);
2183
2184 /* Pull credentials from various sources into a common credential directory */
2185 if (arg_system && !skip_setup)
2186 (void) import_credentials();
2187
2188 return 0;
2189 }
2190
do_queue_default_job(Manager * m,const char ** ret_error_message)2191 static int do_queue_default_job(
2192 Manager *m,
2193 const char **ret_error_message) {
2194
2195 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2196 const char *unit;
2197 Job *job;
2198 Unit *target;
2199 int r;
2200
2201 if (arg_default_unit)
2202 unit = arg_default_unit;
2203 else if (in_initrd())
2204 unit = SPECIAL_INITRD_TARGET;
2205 else
2206 unit = SPECIAL_DEFAULT_TARGET;
2207
2208 log_debug("Activating default unit: %s", unit);
2209
2210 r = manager_load_startable_unit_or_warn(m, unit, NULL, &target);
2211 if (r < 0 && in_initrd() && !arg_default_unit) {
2212 /* Fall back to default.target, which we used to always use by default. Only do this if no
2213 * explicit configuration was given. */
2214
2215 log_info("Falling back to " SPECIAL_DEFAULT_TARGET ".");
2216
2217 r = manager_load_startable_unit_or_warn(m, SPECIAL_DEFAULT_TARGET, NULL, &target);
2218 }
2219 if (r < 0) {
2220 log_info("Falling back to " SPECIAL_RESCUE_TARGET ".");
2221
2222 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
2223 if (r < 0) {
2224 *ret_error_message = r == -ERFKILL ? SPECIAL_RESCUE_TARGET " masked"
2225 : "Failed to load " SPECIAL_RESCUE_TARGET;
2226 return r;
2227 }
2228 }
2229
2230 assert(target->load_state == UNIT_LOADED);
2231
2232 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &job);
2233 if (r == -EPERM) {
2234 log_debug_errno(r, "Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
2235
2236 sd_bus_error_free(&error);
2237
2238 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &job);
2239 if (r < 0) {
2240 *ret_error_message = "Failed to start default target";
2241 return log_emergency_errno(r, "Failed to start default target: %s", bus_error_message(&error, r));
2242 }
2243
2244 } else if (r < 0) {
2245 *ret_error_message = "Failed to isolate default target";
2246 return log_emergency_errno(r, "Failed to isolate default target: %s", bus_error_message(&error, r));
2247 } else
2248 log_info("Queued %s job for default target %s.",
2249 job_type_to_string(job->type),
2250 unit_status_string(job->unit, NULL));
2251
2252 m->default_unit_job_id = job->id;
2253
2254 return 0;
2255 }
2256
save_rlimits(struct rlimit * saved_rlimit_nofile,struct rlimit * saved_rlimit_memlock)2257 static void save_rlimits(struct rlimit *saved_rlimit_nofile,
2258 struct rlimit *saved_rlimit_memlock) {
2259
2260 assert(saved_rlimit_nofile);
2261 assert(saved_rlimit_memlock);
2262
2263 if (getrlimit(RLIMIT_NOFILE, saved_rlimit_nofile) < 0)
2264 log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2265
2266 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock) < 0)
2267 log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2268 }
2269
fallback_rlimit_nofile(const struct rlimit * saved_rlimit_nofile)2270 static void fallback_rlimit_nofile(const struct rlimit *saved_rlimit_nofile) {
2271 struct rlimit *rl;
2272
2273 if (arg_default_rlimit[RLIMIT_NOFILE])
2274 return;
2275
2276 /* Make sure forked processes get limits based on the original kernel setting */
2277
2278 rl = newdup(struct rlimit, saved_rlimit_nofile, 1);
2279 if (!rl) {
2280 log_oom();
2281 return;
2282 }
2283
2284 /* Bump the hard limit for system services to a substantially higher value. The default
2285 * hard limit current kernels set is pretty low (4K), mostly for historical
2286 * reasons. According to kernel developers, the fd handling in recent kernels has been
2287 * optimized substantially enough, so that we can bump the limit now, without paying too
2288 * high a price in memory or performance. Note however that we only bump the hard limit,
2289 * not the soft limit. That's because select() works the way it works, and chokes on fds
2290 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2291 * unexpecting programs that they get fds higher than what they can process using
2292 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2293 * this pitfall: programs that are written by folks aware of the select() problem in mind
2294 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2295 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2296 * we pass. */
2297 if (arg_system) {
2298 int nr;
2299
2300 /* Get the underlying absolute limit the kernel enforces */
2301 nr = read_nr_open();
2302
2303 rl->rlim_max = MIN((rlim_t) nr, MAX(rl->rlim_max, (rlim_t) HIGH_RLIMIT_NOFILE));
2304 }
2305
2306 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2307 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2308 * instance), then lower what we pass on to not confuse our children */
2309 rl->rlim_cur = MIN(rl->rlim_cur, (rlim_t) FD_SETSIZE);
2310
2311 arg_default_rlimit[RLIMIT_NOFILE] = rl;
2312 }
2313
fallback_rlimit_memlock(const struct rlimit * saved_rlimit_memlock)2314 static void fallback_rlimit_memlock(const struct rlimit *saved_rlimit_memlock) {
2315 struct rlimit *rl;
2316
2317 /* Pass the original value down to invoked processes */
2318
2319 if (arg_default_rlimit[RLIMIT_MEMLOCK])
2320 return;
2321
2322 rl = newdup(struct rlimit, saved_rlimit_memlock, 1);
2323 if (!rl) {
2324 log_oom();
2325 return;
2326 }
2327
2328 if (arg_system) {
2329 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2330 * default for this since kernel 5.16) */
2331 rl->rlim_max = MAX(rl->rlim_max, (rlim_t) DEFAULT_RLIMIT_MEMLOCK);
2332 rl->rlim_cur = MAX(rl->rlim_cur, (rlim_t) DEFAULT_RLIMIT_MEMLOCK);
2333 }
2334
2335 arg_default_rlimit[RLIMIT_MEMLOCK] = rl;
2336 }
2337
setenv_manager_environment(void)2338 static void setenv_manager_environment(void) {
2339 int r;
2340
2341 STRV_FOREACH(p, arg_manager_environment) {
2342 log_debug("Setting '%s' in our own environment.", *p);
2343
2344 r = putenv_dup(*p, true);
2345 if (r < 0)
2346 log_warning_errno(errno, "Failed to setenv \"%s\", ignoring: %m", *p);
2347 }
2348 }
2349
reset_arguments(void)2350 static void reset_arguments(void) {
2351 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2352
2353 arg_default_unit = mfree(arg_default_unit);
2354
2355 /* arg_system — ignore */
2356
2357 arg_dump_core = true;
2358 arg_crash_chvt = -1;
2359 arg_crash_shell = false;
2360 arg_crash_reboot = false;
2361 arg_confirm_spawn = mfree(arg_confirm_spawn);
2362 arg_show_status = _SHOW_STATUS_INVALID;
2363 arg_status_unit_format = STATUS_UNIT_FORMAT_DEFAULT;
2364 arg_switched_root = false;
2365 arg_pager_flags = 0;
2366 arg_service_watchdogs = true;
2367 arg_default_std_output = EXEC_OUTPUT_JOURNAL;
2368 arg_default_std_error = EXEC_OUTPUT_INHERIT;
2369 arg_default_restart_usec = DEFAULT_RESTART_USEC;
2370 arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
2371 arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
2372 arg_default_timeout_abort_usec = DEFAULT_TIMEOUT_USEC;
2373 arg_default_timeout_abort_set = false;
2374 arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
2375 arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
2376 arg_runtime_watchdog = 0;
2377 arg_reboot_watchdog = 10 * USEC_PER_MINUTE;
2378 arg_kexec_watchdog = 0;
2379 arg_pretimeout_watchdog = 0;
2380 arg_early_core_pattern = NULL;
2381 arg_watchdog_device = NULL;
2382 arg_watchdog_pretimeout_governor = mfree(arg_watchdog_pretimeout_governor);
2383
2384 arg_default_environment = strv_free(arg_default_environment);
2385 arg_manager_environment = strv_free(arg_manager_environment);
2386 rlimit_free_all(arg_default_rlimit);
2387
2388 arg_capability_bounding_set = CAP_ALL;
2389 arg_no_new_privs = false;
2390 arg_timer_slack_nsec = NSEC_INFINITY;
2391 arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
2392
2393 arg_syscall_archs = set_free(arg_syscall_archs);
2394
2395 /* arg_serialization — ignore */
2396
2397 arg_default_cpu_accounting = -1;
2398 arg_default_io_accounting = false;
2399 arg_default_ip_accounting = false;
2400 arg_default_blockio_accounting = false;
2401 arg_default_memory_accounting = MEMORY_ACCOUNTING_DEFAULT;
2402 arg_default_tasks_accounting = true;
2403 arg_default_tasks_max = DEFAULT_TASKS_MAX;
2404 arg_machine_id = (sd_id128_t) {};
2405 arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
2406 arg_default_oom_policy = OOM_STOP;
2407
2408 cpu_set_reset(&arg_cpu_affinity);
2409 numa_policy_reset(&arg_numa_policy);
2410
2411 arg_random_seed = mfree(arg_random_seed);
2412 arg_random_seed_size = 0;
2413 arg_clock_usec = 0;
2414
2415 arg_default_oom_score_adjust_set = false;
2416 }
2417
determine_default_oom_score_adjust(void)2418 static void determine_default_oom_score_adjust(void) {
2419 int r, a, b;
2420
2421 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2422 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2423 * user). */
2424
2425 if (arg_default_oom_score_adjust_set)
2426 return;
2427
2428 if (getuid() == 0)
2429 return;
2430
2431 r = get_oom_score_adjust(&a);
2432 if (r < 0)
2433 return (void) log_warning_errno(r, "Failed to determine current OOM score adjustment value, ignoring: %m");
2434
2435 assert_cc(100 <= OOM_SCORE_ADJ_MAX);
2436 b = a >= OOM_SCORE_ADJ_MAX - 100 ? OOM_SCORE_ADJ_MAX : a + 100;
2437
2438 if (a == b)
2439 return;
2440
2441 arg_default_oom_score_adjust = b;
2442 arg_default_oom_score_adjust_set = true;
2443 }
2444
parse_configuration(const struct rlimit * saved_rlimit_nofile,const struct rlimit * saved_rlimit_memlock)2445 static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
2446 const struct rlimit *saved_rlimit_memlock) {
2447 int r;
2448
2449 assert(saved_rlimit_nofile);
2450 assert(saved_rlimit_memlock);
2451
2452 /* Assign configuration defaults */
2453 reset_arguments();
2454
2455 r = parse_config_file();
2456 if (r < 0)
2457 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
2458
2459 if (arg_system) {
2460 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
2461 if (r < 0)
2462 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
2463 }
2464
2465 /* Initialize some default rlimits for services if they haven't been configured */
2466 fallback_rlimit_nofile(saved_rlimit_nofile);
2467 fallback_rlimit_memlock(saved_rlimit_memlock);
2468
2469 /* Note that this also parses bits from the kernel command line, including "debug". */
2470 log_parse_environment();
2471
2472 /* Initialize the show status setting if it hasn't been set explicitly yet */
2473 if (arg_show_status == _SHOW_STATUS_INVALID)
2474 arg_show_status = SHOW_STATUS_YES;
2475
2476 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2477 determine_default_oom_score_adjust();
2478
2479 /* Push variables into the manager environment block */
2480 setenv_manager_environment();
2481
2482 /* Parse log environment variables again to take into account any new environment variables. */
2483 log_parse_environment();
2484
2485 return 0;
2486 }
2487
safety_checks(void)2488 static int safety_checks(void) {
2489
2490 if (getpid_cached() == 1 &&
2491 arg_action != ACTION_RUN)
2492 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2493 "Unsupported execution mode while PID 1.");
2494
2495 if (getpid_cached() == 1 &&
2496 !arg_system)
2497 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2498 "Can't run --user mode as PID 1.");
2499
2500 if (arg_action == ACTION_RUN &&
2501 arg_system &&
2502 getpid_cached() != 1)
2503 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2504 "Can't run system mode unless PID 1.");
2505
2506 if (arg_action == ACTION_TEST &&
2507 geteuid() == 0)
2508 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2509 "Don't run test mode as root.");
2510
2511 if (!arg_system &&
2512 arg_action == ACTION_RUN &&
2513 sd_booted() <= 0)
2514 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2515 "Trying to run as user instance, but the system has not been booted with systemd.");
2516
2517 if (!arg_system &&
2518 arg_action == ACTION_RUN &&
2519 !getenv("XDG_RUNTIME_DIR"))
2520 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH),
2521 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2522
2523 if (arg_system &&
2524 arg_action == ACTION_RUN &&
2525 running_in_chroot() > 0)
2526 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2527 "Cannot be run in a chroot() environment.");
2528
2529 return 0;
2530 }
2531
initialize_security(bool * loaded_policy,dual_timestamp * security_start_timestamp,dual_timestamp * security_finish_timestamp,const char ** ret_error_message)2532 static int initialize_security(
2533 bool *loaded_policy,
2534 dual_timestamp *security_start_timestamp,
2535 dual_timestamp *security_finish_timestamp,
2536 const char **ret_error_message) {
2537
2538 int r;
2539
2540 assert(loaded_policy);
2541 assert(security_start_timestamp);
2542 assert(security_finish_timestamp);
2543 assert(ret_error_message);
2544
2545 dual_timestamp_get(security_start_timestamp);
2546
2547 r = mac_selinux_setup(loaded_policy);
2548 if (r < 0) {
2549 *ret_error_message = "Failed to load SELinux policy";
2550 return r;
2551 }
2552
2553 r = mac_smack_setup(loaded_policy);
2554 if (r < 0) {
2555 *ret_error_message = "Failed to load SMACK policy";
2556 return r;
2557 }
2558
2559 r = mac_apparmor_setup();
2560 if (r < 0) {
2561 *ret_error_message = "Failed to load AppArmor policy";
2562 return r;
2563 }
2564
2565 r = ima_setup();
2566 if (r < 0) {
2567 *ret_error_message = "Failed to load IMA policy";
2568 return r;
2569 }
2570
2571 dual_timestamp_get(security_finish_timestamp);
2572 return 0;
2573 }
2574
collect_fds(FDSet ** ret_fds,const char ** ret_error_message)2575 static int collect_fds(FDSet **ret_fds, const char **ret_error_message) {
2576 int r;
2577
2578 assert(ret_fds);
2579 assert(ret_error_message);
2580
2581 r = fdset_new_fill(ret_fds);
2582 if (r < 0) {
2583 *ret_error_message = "Failed to allocate fd set";
2584 return log_emergency_errno(r, "Failed to allocate fd set: %m");
2585 }
2586
2587 fdset_cloexec(*ret_fds, true);
2588
2589 if (arg_serialization)
2590 assert_se(fdset_remove(*ret_fds, fileno(arg_serialization)) >= 0);
2591
2592 return 0;
2593 }
2594
setup_console_terminal(bool skip_setup)2595 static void setup_console_terminal(bool skip_setup) {
2596
2597 if (!arg_system)
2598 return;
2599
2600 /* Become a session leader if we aren't one yet. */
2601 (void) setsid();
2602
2603 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2604 * controlling tty. */
2605 (void) release_terminal();
2606
2607 /* Reset the console, but only if this is really init and we are freshly booted */
2608 if (getpid_cached() == 1 && !skip_setup)
2609 (void) console_setup();
2610 }
2611
early_skip_setup_check(int argc,char * argv[])2612 static bool early_skip_setup_check(int argc, char *argv[]) {
2613 bool found_deserialize = false;
2614
2615 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2616 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2617 * special setup things anyway, even if in that case we also do deserialization. */
2618
2619 for (int i = 1; i < argc; i++)
2620 if (streq(argv[i], "--switched-root"))
2621 return false; /* If we switched root, don't skip the setup. */
2622 else if (streq(argv[i], "--deserialize"))
2623 found_deserialize = true;
2624
2625 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2626 }
2627
save_env(void)2628 static int save_env(void) {
2629 char **l;
2630
2631 l = strv_copy(environ);
2632 if (!l)
2633 return -ENOMEM;
2634
2635 strv_free_and_replace(saved_env, l);
2636 return 0;
2637 }
2638
main(int argc,char * argv[])2639 int main(int argc, char *argv[]) {
2640 dual_timestamp
2641 initrd_timestamp = DUAL_TIMESTAMP_NULL,
2642 userspace_timestamp = DUAL_TIMESTAMP_NULL,
2643 kernel_timestamp = DUAL_TIMESTAMP_NULL,
2644 security_start_timestamp = DUAL_TIMESTAMP_NULL,
2645 security_finish_timestamp = DUAL_TIMESTAMP_NULL;
2646 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0),
2647 saved_rlimit_memlock = RLIMIT_MAKE_CONST(RLIM_INFINITY); /* The original rlimits we passed
2648 * in. Note we use different values
2649 * for the two that indicate whether
2650 * these fields are initialized! */
2651 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false;
2652 char *switch_root_dir = NULL, *switch_root_init = NULL;
2653 usec_t before_startup, after_startup;
2654 static char systemd[] = "systemd";
2655 const char *shutdown_verb = NULL, *error_message = NULL;
2656 int r, retval = EXIT_FAILURE;
2657 Manager *m = NULL;
2658 FDSet *fds = NULL;
2659
2660 assert_se(argc > 0 && !isempty(argv[0]));
2661
2662 /* SysV compatibility: redirect init → telinit */
2663 redirect_telinit(argc, argv);
2664
2665 /* Take timestamps early on */
2666 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2667 dual_timestamp_get(&userspace_timestamp);
2668
2669 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2670 * reexecuting. */
2671 skip_setup = early_skip_setup_check(argc, argv);
2672
2673 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2674 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2675 * right-away. */
2676 program_invocation_short_name = systemd;
2677 (void) prctl(PR_SET_NAME, systemd);
2678
2679 /* Save the original command line */
2680 save_argc_argv(argc, argv);
2681
2682 /* Save the original environment as we might need to restore it if we're requested to execute another
2683 * system manager later. */
2684 r = save_env();
2685 if (r < 0) {
2686 error_message = "Failed to copy environment block";
2687 goto finish;
2688 }
2689
2690 /* Make sure that if the user says "syslog" we actually log to the journal. */
2691 log_set_upgrade_syslog_to_journal(true);
2692
2693 if (getpid_cached() == 1) {
2694 /* When we run as PID 1 force system mode */
2695 arg_system = true;
2696
2697 /* Disable the umask logic */
2698 umask(0);
2699
2700 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2701 * not be activated yet (even though the log socket for it exists). */
2702 log_set_prohibit_ipc(true);
2703
2704 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2705 * is important so that we never end up logging to any foreign stderr, for example if we have
2706 * to log in a child process right before execve()'ing the actual binary, at a point in time
2707 * where socket activation stderr/stdout area already set up. */
2708 log_set_always_reopen_console(true);
2709
2710 if (detect_container() <= 0) {
2711
2712 /* Running outside of a container as PID 1 */
2713 log_set_target(LOG_TARGET_KMSG);
2714 log_open();
2715
2716 if (in_initrd())
2717 initrd_timestamp = userspace_timestamp;
2718
2719 if (!skip_setup) {
2720 r = mount_setup_early();
2721 if (r < 0) {
2722 error_message = "Failed to mount early API filesystems";
2723 goto finish;
2724 }
2725
2726 /* Let's open the log backend a second time, in case the first time didn't
2727 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2728 * available, and it previously wasn't. */
2729 log_open();
2730
2731 disable_printk_ratelimit();
2732
2733 r = initialize_security(
2734 &loaded_policy,
2735 &security_start_timestamp,
2736 &security_finish_timestamp,
2737 &error_message);
2738 if (r < 0)
2739 goto finish;
2740 }
2741
2742 if (mac_selinux_init() < 0) {
2743 error_message = "Failed to initialize SELinux support";
2744 goto finish;
2745 }
2746
2747 if (!skip_setup)
2748 initialize_clock();
2749
2750 /* Set the default for later on, but don't actually open the logs like this for
2751 * now. Note that if we are transitioning from the initrd there might still be
2752 * journal fd open, and we shouldn't attempt opening that before we parsed
2753 * /proc/cmdline which might redirect output elsewhere. */
2754 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2755
2756 } else {
2757 /* Running inside a container, as PID 1 */
2758 log_set_target(LOG_TARGET_CONSOLE);
2759 log_open();
2760
2761 /* For later on, see above... */
2762 log_set_target(LOG_TARGET_JOURNAL);
2763
2764 /* clear the kernel timestamp, because we are in a container */
2765 kernel_timestamp = DUAL_TIMESTAMP_NULL;
2766 }
2767
2768 initialize_coredump(skip_setup);
2769
2770 r = fixup_environment();
2771 if (r < 0) {
2772 log_emergency_errno(r, "Failed to fix up PID 1 environment: %m");
2773 error_message = "Failed to fix up PID1 environment";
2774 goto finish;
2775 }
2776
2777 /* Try to figure out if we can use colors with the console. No need to do that for user
2778 * instances since they never log into the console. */
2779 log_show_color(colors_enabled());
2780
2781 r = make_null_stdio();
2782 if (r < 0)
2783 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2784
2785 /* Load the kernel modules early. */
2786 if (!skip_setup)
2787 (void) kmod_setup();
2788
2789 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
2790 r = mount_setup(loaded_policy, skip_setup);
2791 if (r < 0) {
2792 error_message = "Failed to mount API filesystems";
2793 goto finish;
2794 }
2795
2796 /* The efivarfs is now mounted, let's read the random seed off it */
2797 (void) efi_take_random_seed();
2798
2799 /* Cache command-line options passed from EFI variables */
2800 if (!skip_setup)
2801 (void) cache_efi_options_variable();
2802 } else {
2803 /* Running as user instance */
2804 arg_system = false;
2805 log_set_target(LOG_TARGET_AUTO);
2806 log_open();
2807
2808 /* clear the kernel timestamp, because we are not PID 1 */
2809 kernel_timestamp = DUAL_TIMESTAMP_NULL;
2810
2811 if (mac_selinux_init() < 0) {
2812 error_message = "Failed to initialize SELinux support";
2813 goto finish;
2814 }
2815 }
2816
2817 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2818 * transitioning from the initrd to the main systemd or suchlike. */
2819 save_rlimits(&saved_rlimit_nofile, &saved_rlimit_memlock);
2820
2821 /* Reset all signal handlers. */
2822 (void) reset_all_signal_handlers();
2823 (void) ignore_signals(SIGNALS_IGNORE);
2824
2825 (void) parse_configuration(&saved_rlimit_nofile, &saved_rlimit_memlock);
2826
2827 r = parse_argv(argc, argv);
2828 if (r < 0) {
2829 error_message = "Failed to parse commandline arguments";
2830 goto finish;
2831 }
2832
2833 r = safety_checks();
2834 if (r < 0)
2835 goto finish;
2836
2837 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES, ACTION_BUS_INTROSPECT))
2838 pager_open(arg_pager_flags);
2839
2840 if (arg_action != ACTION_RUN)
2841 skip_setup = true;
2842
2843 if (arg_action == ACTION_HELP) {
2844 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
2845 goto finish;
2846 } else if (arg_action == ACTION_VERSION) {
2847 retval = version();
2848 goto finish;
2849 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
2850 unit_dump_config_items(stdout);
2851 retval = EXIT_SUCCESS;
2852 goto finish;
2853 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
2854 dump_bus_properties(stdout);
2855 retval = EXIT_SUCCESS;
2856 goto finish;
2857 } else if (arg_action == ACTION_BUS_INTROSPECT) {
2858 r = bus_manager_introspect_implementations(stdout, arg_bus_introspect);
2859 retval = r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
2860 goto finish;
2861 }
2862
2863 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
2864
2865 /* Move out of the way, so that we won't block unmounts */
2866 assert_se(chdir("/") == 0);
2867
2868 if (arg_action == ACTION_RUN) {
2869 if (!skip_setup) {
2870 /* Apply the systemd.clock_usec= kernel command line switch */
2871 apply_clock_update();
2872
2873 /* Apply random seed from kernel command line */
2874 cmdline_take_random_seed();
2875 }
2876
2877 /* A core pattern might have been specified via the cmdline. */
2878 initialize_core_pattern(skip_setup);
2879
2880 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2881 log_close();
2882
2883 /* Remember open file descriptors for later deserialization */
2884 r = collect_fds(&fds, &error_message);
2885 if (r < 0)
2886 goto finish;
2887
2888 /* Give up any control of the console, but make sure its initialized. */
2889 setup_console_terminal(skip_setup);
2890
2891 /* Open the logging devices, if possible and necessary */
2892 log_open();
2893 }
2894
2895 log_execution_mode(&first_boot);
2896
2897 r = initialize_runtime(skip_setup,
2898 first_boot,
2899 &saved_rlimit_nofile,
2900 &saved_rlimit_memlock,
2901 &error_message);
2902 if (r < 0)
2903 goto finish;
2904
2905 r = manager_new(arg_system ? LOOKUP_SCOPE_SYSTEM : LOOKUP_SCOPE_USER,
2906 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
2907 &m);
2908 if (r < 0) {
2909 log_emergency_errno(r, "Failed to allocate manager object: %m");
2910 error_message = "Failed to allocate manager object";
2911 goto finish;
2912 }
2913
2914 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
2915 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
2916 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
2917 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START)] = security_start_timestamp;
2918 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH)] = security_finish_timestamp;
2919
2920 set_manager_defaults(m);
2921 set_manager_settings(m);
2922 manager_set_first_boot(m, first_boot);
2923
2924 /* Remember whether we should queue the default job */
2925 queue_default_job = !arg_serialization || arg_switched_root;
2926
2927 before_startup = now(CLOCK_MONOTONIC);
2928
2929 r = manager_startup(m, arg_serialization, fds, /* root= */ NULL);
2930 if (r < 0) {
2931 error_message = "Failed to start up manager";
2932 goto finish;
2933 }
2934
2935 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2936 fds = fdset_free(fds);
2937 arg_serialization = safe_fclose(arg_serialization);
2938
2939 if (queue_default_job) {
2940 r = do_queue_default_job(m, &error_message);
2941 if (r < 0)
2942 goto finish;
2943 }
2944
2945 after_startup = now(CLOCK_MONOTONIC);
2946
2947 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2948 "Loaded units and determined initial transaction in %s.",
2949 FORMAT_TIMESPAN(after_startup - before_startup, 100 * USEC_PER_MSEC));
2950
2951 if (arg_action == ACTION_TEST) {
2952 manager_test_summary(m);
2953 retval = EXIT_SUCCESS;
2954 goto finish;
2955 }
2956
2957 r = invoke_main_loop(m,
2958 &saved_rlimit_nofile,
2959 &saved_rlimit_memlock,
2960 &retval,
2961 &shutdown_verb,
2962 &fds,
2963 &switch_root_dir,
2964 &switch_root_init,
2965 &error_message);
2966 assert(r < 0 || IN_SET(r, MANAGER_EXIT, /* MANAGER_OK is not expected here. */
2967 MANAGER_RELOAD,
2968 MANAGER_REEXECUTE,
2969 MANAGER_REBOOT,
2970 MANAGER_POWEROFF,
2971 MANAGER_HALT,
2972 MANAGER_KEXEC,
2973 MANAGER_SWITCH_ROOT));
2974
2975 finish:
2976 pager_close();
2977
2978 if (m) {
2979 arg_reboot_watchdog = manager_get_watchdog(m, WATCHDOG_REBOOT);
2980 arg_kexec_watchdog = manager_get_watchdog(m, WATCHDOG_KEXEC);
2981 m = manager_free(m);
2982 }
2983
2984 mac_selinux_finish();
2985
2986 if (IN_SET(r, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT))
2987 r = do_reexecute(r,
2988 argc, argv,
2989 &saved_rlimit_nofile,
2990 &saved_rlimit_memlock,
2991 fds,
2992 switch_root_dir,
2993 switch_root_init,
2994 &error_message); /* This only returns if reexecution failed */
2995
2996 arg_serialization = safe_fclose(arg_serialization);
2997 fds = fdset_free(fds);
2998
2999 saved_env = strv_free(saved_env);
3000
3001 #if HAVE_VALGRIND_VALGRIND_H
3002 /* If we are PID 1 and running under valgrind, then let's exit
3003 * here explicitly. valgrind will only generate nice output on
3004 * exit(), not on exec(), hence let's do the former not the
3005 * latter here. */
3006 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
3007 /* Cleanup watchdog_device strings for valgrind. We need them
3008 * in become_shutdown() so normally we cannot free them yet. */
3009 watchdog_free_device();
3010 arg_watchdog_device = mfree(arg_watchdog_device);
3011 reset_arguments();
3012 return retval;
3013 }
3014 #endif
3015
3016 #if HAS_FEATURE_ADDRESS_SANITIZER
3017 __lsan_do_leak_check();
3018 #endif
3019
3020 /* Try to invoke the shutdown binary unless we already failed.
3021 * If we failed above, we want to freeze after finishing cleanup. */
3022 if (r >= 0 && shutdown_verb) {
3023 r = become_shutdown(shutdown_verb, retval);
3024 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3025 error_message = "Failed to execute shutdown binary";
3026 }
3027
3028 watchdog_free_device();
3029 arg_watchdog_device = mfree(arg_watchdog_device);
3030
3031 if (getpid_cached() == 1) {
3032 if (error_message)
3033 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
3034 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
3035 "%s.", error_message);
3036 freeze_or_exit_or_reboot();
3037 }
3038
3039 reset_arguments();
3040 return retval;
3041 }
3042