]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
sysext: refuse empty release ID to avoid triggering assertion
[thirdparty/systemd.git] / src / core / main.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
60918275 3#include <errno.h>
3dfc9763 4#include <fcntl.h>
f170852a 5#include <getopt.h>
d4a402e4 6#include <linux/oom.h>
664f88a7 7#include <sys/mount.h>
3dfc9763 8#include <sys/prctl.h>
40efaaed 9#include <sys/utsname.h>
3dfc9763 10#include <unistd.h>
349cc4a5 11#if HAVE_SECCOMP
b64a3d86
LP
12#include <seccomp.h>
13#endif
349cc4a5 14#if HAVE_VALGRIND_VALGRIND_H
3dfc9763
LP
15#include <valgrind/valgrind.h>
16#endif
54b434b1 17
718db961 18#include "sd-bus.h"
cf0fbc49 19#include "sd-daemon.h"
b2e7486c 20#include "sd-messages.h"
3dfc9763 21
b5efdb8a 22#include "alloc-util.h"
2ffadd3c 23#include "apparmor-setup.h"
d9d93745 24#include "architecture.h"
b1994387
ILG
25#if HAVE_LIBBPF
26#include "bpf-lsm.h"
27#endif
3dfc9763
LP
28#include "build.h"
29#include "bus-error.h"
30#include "bus-util.h"
430f0182 31#include "capability-util.h"
a88c5b8a 32#include "cgroup-util.h"
24efb112 33#include "clock-util.h"
3dfc9763 34#include "conf-parser.h"
618234a5 35#include "cpu-set-util.h"
898c9a6f 36#include "crash-handler.h"
3dfc9763 37#include "dbus-manager.h"
c18ecf03 38#include "dbus.h"
3dfc9763 39#include "def.h"
32429805 40#include "dev-setup.h"
c18ecf03 41#include "efi-random.h"
209b2592 42#include "efivars.h"
eee8b7ab 43#include "emergency-action.h"
3dfc9763 44#include "env-util.h"
57b7a260 45#include "exit-status.h"
3ffd4af2 46#include "fd-util.h"
3dfc9763 47#include "fdset.h"
718db961 48#include "fileio.h"
f97b34a6 49#include "format-util.h"
f4f15635 50#include "fs-util.h"
d247f232 51#include "hexdecoct.h"
3dfc9763
LP
52#include "hostname-setup.h"
53#include "ima-setup.h"
4b9a4b01 54#include "import-creds.h"
3dfc9763
LP
55#include "killall.h"
56#include "kmod-setup.h"
eefc66aa 57#include "limits-util.h"
d7b8eec7 58#include "load-fragment.h"
3dfc9763 59#include "log.h"
b6e66135 60#include "loopback-setup.h"
b6e66135 61#include "machine-id-setup.h"
898c9a6f 62#include "main.h"
3dfc9763 63#include "manager.h"
2a341bb9 64#include "manager-dump.h"
a01ba4b2 65#include "manager-serialize.h"
35cd0ba5 66#include "mkdir-label.h"
3dfc9763 67#include "mount-setup.h"
d58ad743 68#include "os-util.h"
3dfc9763 69#include "pager.h"
614b022c 70#include "parse-argument.h"
6bedfcbb 71#include "parse-util.h"
7d5ceb64 72#include "path-util.h"
294bf0c3 73#include "pretty-print.h"
4e731273 74#include "proc-cmdline.h"
3dfc9763 75#include "process-util.h"
d247f232 76#include "random-util.h"
78f22b97 77#include "rlimit-util.h"
349cc4a5 78#if HAVE_SECCOMP
83f12b27
FS
79#include "seccomp-util.h"
80#endif
b6e66135 81#include "selinux-setup.h"
3dfc9763
LP
82#include "selinux-util.h"
83#include "signal-util.h"
ffbd2c4d 84#include "smack-setup.h"
3dfc9763 85#include "special.h"
8fcde012 86#include "stat-util.h"
15a5e950 87#include "stdio-util.h"
3dfc9763
LP
88#include "strv.h"
89#include "switch-root.h"
a8b627aa 90#include "sysctl-util.h"
3dfc9763 91#include "terminal-util.h"
b10abe4b 92#include "time-util.h"
8612da97 93#include "umask-util.h"
b1d4f8e1 94#include "user-util.h"
9ce17593 95#include "util.h"
3dfc9763
LP
96#include "virt.h"
97#include "watchdog.h"
b6e66135 98
7e11a95e
EV
99#if HAS_FEATURE_ADDRESS_SANITIZER
100#include <sanitizer/lsan_interface.h>
101#endif
102
3a0f06c4
ZJS
103#define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
104
f170852a
LP
105static enum {
106 ACTION_RUN,
e965d56d 107 ACTION_HELP,
9ba0bc4e 108 ACTION_VERSION,
e537352b 109 ACTION_TEST,
bbc1acab
YW
110 ACTION_DUMP_CONFIGURATION_ITEMS,
111 ACTION_DUMP_BUS_PROPERTIES,
5c08257b 112 ACTION_BUS_INTROSPECT,
fa0f4d8a 113} arg_action = ACTION_RUN;
fb39af4c 114
5c08257b
ZJS
115static const char *arg_bus_introspect = NULL;
116
45250e66
LP
117/* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
118 * defaults are assigned in reset_arguments() below. */
fb39af4c
ZJS
119static char *arg_default_unit;
120static bool arg_system;
898c9a6f
LP
121bool arg_dump_core;
122int arg_crash_chvt;
123bool arg_crash_shell;
124bool arg_crash_reboot;
fb39af4c
ZJS
125static char *arg_confirm_spawn;
126static ShowStatus arg_show_status;
36cf4507 127static StatusUnitFormat arg_status_unit_format;
fb39af4c
ZJS
128static bool arg_switched_root;
129static PagerFlags arg_pager_flags;
130static bool arg_service_watchdogs;
131static ExecOutput arg_default_std_output;
132static ExecOutput arg_default_std_error;
133static usec_t arg_default_restart_usec;
134static usec_t arg_default_timeout_start_usec;
135static usec_t arg_default_timeout_stop_usec;
136static usec_t arg_default_timeout_abort_usec;
137static bool arg_default_timeout_abort_set;
138static usec_t arg_default_start_limit_interval;
139static unsigned arg_default_start_limit_burst;
140static usec_t arg_runtime_watchdog;
65224c1d 141static usec_t arg_reboot_watchdog;
acafd7d8 142static usec_t arg_kexec_watchdog;
5717062e 143static usec_t arg_pretimeout_watchdog;
fb39af4c 144static char *arg_early_core_pattern;
aff3a9e1 145static char *arg_watchdog_pretimeout_governor;
fb39af4c
ZJS
146static char *arg_watchdog_device;
147static char **arg_default_environment;
d55ed7de 148static char **arg_manager_environment;
fb39af4c
ZJS
149static struct rlimit *arg_default_rlimit[_RLIMIT_MAX];
150static uint64_t arg_capability_bounding_set;
151static bool arg_no_new_privs;
152static nsec_t arg_timer_slack_nsec;
153static usec_t arg_default_timer_accuracy_usec;
154static Set* arg_syscall_archs;
155static FILE* arg_serialization;
156static int arg_default_cpu_accounting;
157static bool arg_default_io_accounting;
158static bool arg_default_ip_accounting;
159static bool arg_default_blockio_accounting;
160static bool arg_default_memory_accounting;
161static bool arg_default_tasks_accounting;
3a0f06c4 162static TasksMax arg_default_tasks_max;
fb39af4c
ZJS
163static sd_id128_t arg_machine_id;
164static EmergencyAction arg_cad_burst_action;
165static OOMPolicy arg_default_oom_policy;
166static CPUSet arg_cpu_affinity;
b070c7c0 167static NUMAPolicy arg_numa_policy;
3753325b 168static usec_t arg_clock_usec;
d247f232
LP
169static void *arg_random_seed;
170static size_t arg_random_seed_size;
d4a402e4
LP
171static int arg_default_oom_score_adjust;
172static bool arg_default_oom_score_adjust_set;
61fbbac1 173
0e06a031
LP
174/* A copy of the original environment block */
175static char **saved_env = NULL;
176
a9fd4cd1
FB
177static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
178 const struct rlimit *saved_rlimit_memlock);
4fc935ca 179
f70e6fb4
ZJS
180static 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
56d96fc0
LP
210static int console_setup(void) {
211 _cleanup_close_ int tty_fd = -1;
212 int r;
80876c20 213
512947d4 214 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
23bbb0de
MS
215 if (tty_fd < 0)
216 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
80876c20 217
56d96fc0
LP
218 /* We don't want to force text mode. plymouth may be showing
219 * pictures already from initrd. */
512947d4 220 r = reset_terminal_fd(tty_fd, false);
23bbb0de
MS
221 if (r < 0)
222 return log_error_errno(r, "Failed to reset /dev/console: %m");
843d2643 223
56d96fc0 224 return 0;
80876c20
LP
225}
226
ee48dbd5 227static int set_machine_id(const char *m) {
e042eab7 228 sd_id128_t t;
8b26cdbd 229 assert(m);
ee48dbd5 230
e042eab7 231 if (sd_id128_from_string(m, &t) < 0)
ee48dbd5
NC
232 return -EINVAL;
233
e042eab7 234 if (sd_id128_is_null(t))
ee48dbd5
NC
235 return -EINVAL;
236
e042eab7 237 arg_machine_id = t;
ee48dbd5
NC
238 return 0;
239}
240
96287a49 241static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
059cb385 242 int r;
f170852a 243
059cb385 244 assert(key);
5192bd19 245
1d84ad94 246 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
bf4df7c3 247
1d84ad94
LP
248 if (proc_cmdline_value_missing(key, value))
249 return 0;
bf4df7c3 250
1d84ad94
LP
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);
cd57038a
ZJS
253 else if (in_initrd() == !!startswith(key, "rd."))
254 return free_and_strdup_warn(&arg_default_unit, value);
f170852a 255
1d84ad94 256 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
4fc935ca 257
1d84ad94 258 r = value ? parse_boolean(value) : true;
fb472900 259 if (r < 0)
5e1ee764 260 log_warning_errno(r, "Failed to parse dump core switch %s, ignoring: %m", value);
4fc935ca 261 else
fa0f4d8a 262 arg_dump_core = r;
4fc935ca 263
c6885f5f
FB
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))
614b022c 270 (void) parse_path_argument(value, false, &arg_early_core_pattern);
c6885f5f
FB
271 else
272 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value);
273
1d84ad94 274 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
b9e74c39 275
1d84ad94
LP
276 if (!value)
277 arg_crash_chvt = 0; /* turn on */
5e1ee764 278 else {
a07a7324 279 r = parse_crash_chvt(value, &arg_crash_chvt);
5e1ee764
YW
280 if (r < 0)
281 log_warning_errno(r, "Failed to parse crash chvt switch %s, ignoring: %m", value);
282 }
b9e74c39 283
1d84ad94 284 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
4fc935ca 285
1d84ad94 286 r = value ? parse_boolean(value) : true;
fb472900 287 if (r < 0)
5e1ee764 288 log_warning_errno(r, "Failed to parse crash shell switch %s, ignoring: %m", value);
4fc935ca 289 else
fa0f4d8a 290 arg_crash_shell = r;
5e7ee61c 291
1d84ad94 292 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
5e7ee61c 293
1d84ad94 294 r = value ? parse_boolean(value) : true;
b9e74c39 295 if (r < 0)
5e1ee764 296 log_warning_errno(r, "Failed to parse crash reboot switch %s, ignoring: %m", value);
5e7ee61c 297 else
b9e74c39 298 arg_crash_reboot = r;
5e7ee61c 299
1d84ad94
LP
300 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
301 char *s;
7d5ceb64 302
1d84ad94 303 r = parse_confirm_spawn(value, &s);
059cb385 304 if (r < 0)
5e1ee764
YW
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);
601f6a1e 308
2a12e32e
JK
309 } else if (proc_cmdline_key_streq(key, "systemd.service_watchdogs")) {
310
311 r = value ? parse_boolean(value) : true;
312 if (r < 0)
5e1ee764 313 log_warning_errno(r, "Failed to parse service watchdog switch %s, ignoring: %m", value);
2a12e32e
JK
314 else
315 arg_service_watchdogs = r;
316
1d84ad94 317 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
9e58ff9c 318
1d84ad94
LP
319 if (value) {
320 r = parse_show_status(value, &arg_show_status);
321 if (r < 0)
5e1ee764 322 log_warning_errno(r, "Failed to parse show status switch %s, ignoring: %m", value);
1d84ad94
LP
323 } else
324 arg_show_status = SHOW_STATUS_YES;
059cb385 325
36cf4507
ZJS
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
1d84ad94
LP
337 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
338
339 if (proc_cmdline_value_missing(key, value))
340 return 0;
0a494f1f 341
059cb385 342 r = exec_output_from_string(value);
fb472900 343 if (r < 0)
5e1ee764 344 log_warning_errno(r, "Failed to parse default standard output switch %s, ignoring: %m", value);
0a494f1f
LP
345 else
346 arg_default_std_output = r;
0a494f1f 347
1d84ad94
LP
348 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
349
350 if (proc_cmdline_value_missing(key, value))
351 return 0;
059cb385
LP
352
353 r = exec_output_from_string(value);
fb472900 354 if (r < 0)
5e1ee764 355 log_warning_errno(r, "Failed to parse default standard error switch %s, ignoring: %m", value);
0a494f1f
LP
356 else
357 arg_default_std_error = r;
9e7c5357 358
1d84ad94
LP
359 } else if (streq(key, "systemd.setenv")) {
360
361 if (proc_cmdline_value_missing(key, value))
362 return 0;
059cb385 363
b70935ac
ZJS
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)
1d84ad94 369 return log_oom();
b70935ac 370 }
9e58ff9c 371
1d84ad94
LP
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)
5e1ee764 379 log_warning_errno(r, "MachineID '%s' is not valid, ignoring: %m", value);
ee48dbd5 380
1d84ad94
LP
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)
5e1ee764 388 log_warning_errno(r, "Failed to parse default start timeout '%s', ignoring: %m", value);
1d84ad94
LP
389
390 if (arg_default_timeout_start_usec <= 0)
391 arg_default_timeout_start_usec = USEC_INFINITY;
ee48dbd5 392
68d58f38
LP
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)
162392b7 400 log_warning_errno(r, "Failed to parse CPU affinity mask '%s', ignoring: %m", value);
68d58f38 401
8a2c1fbf
EJ
402 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_device")) {
403
404 if (proc_cmdline_value_missing(key, value))
405 return 0;
406
614b022c 407 (void) parse_path_argument(value, false, &arg_watchdog_device);
8a2c1fbf 408
b3aa73e4
FB
409 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_sec")) {
410
411 if (proc_cmdline_value_missing(key, value))
412 return 0;
413
8a85c5b6
FB
414 if (streq(value, "default"))
415 arg_runtime_watchdog = USEC_INFINITY;
c91c95e6
LP
416 else if (streq(value, "off"))
417 arg_runtime_watchdog = 0;
8a85c5b6
FB
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;
b3aa73e4 427
5717062e
CK
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
aff3a9e1
LB
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
3753325b
LP
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
d247f232
LP
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
f5fbe71d 475 r = unbase64mem(value, SIZE_MAX, &p, &sz);
d247f232
LP
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
059cb385 483 } else if (streq(key, "quiet") && !value) {
d7b15e0a 484
7a293242 485 if (arg_show_status == _SHOW_STATUS_INVALID)
0d066dd1 486 arg_show_status = SHOW_STATUS_ERROR;
059cb385
LP
487
488 } else if (streq(key, "debug") && !value) {
d7b15e0a 489
1de1c9c3
LP
490 /* Note that log_parse_environment() handles 'debug'
491 * too, and sets the log level to LOG_DEBUG. */
d7b15e0a 492
75f86906 493 if (detect_container() > 0)
b2103dcc 494 log_set_target(LOG_TARGET_CONSOLE);
059cb385 495
dcd61450 496 } else if (!value) {
e2c9a131 497 const char *target;
f170852a 498
ceae6295 499 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
e2c9a131
EV
500 target = runlevel_to_target(key);
501 if (target)
cd57038a 502 return free_and_strdup_warn(&arg_default_unit, target);
f170852a
LP
503 }
504
505 return 0;
506}
507
e8e581bf
ZJS
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, \
71a61510 513 unsigned section_line, \
e8e581bf
ZJS
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) \
d1cefe0a
LP
528 log_syntax(unit, LOG_ERR, filename, line, r, \
529 "Invalid " descr "'%s': %m", \
530 rvalue); \
e8e581bf
ZJS
531 \
532 return 0; \
533 }
487393e9 534
a6ecbf83
FB
535DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level");
536DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target");
c5673ed0 537DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color");
a6ecbf83 538DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location");
c5673ed0 539DEFINE_SETTER(config_parse_time, log_show_time_from_string, "time");
487393e9 540
a61d6874
ZJS
541static 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}
487393e9 560
d4a402e4
LP
561static 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
a61d6874 592static int parse_config_file(void) {
f975e971 593 const ConfigTableItem items[] = {
3f87eaa5
YW
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 },
349cc4a5 619#if HAVE_SECCOMP
3f87eaa5 620 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
89fffa27 621#endif
3f87eaa5
YW
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 },
d3b1c508 661 {}
487393e9
LP
662 };
663
e94a009c
YW
664 _cleanup_strv_free_ char **files = NULL, **dirs = NULL;
665 const char *suffix;
f70e6fb4 666 int r;
75eb6154 667
e94a009c 668 if (arg_system)
f70e6fb4 669 suffix = "system.conf.d";
e94a009c
YW
670 else {
671 r = manager_find_user_config_paths(&files, &dirs);
f70e6fb4
ZJS
672 if (r < 0)
673 return log_error_errno(r, "Failed to determine config file paths: %m");
e94a009c 674
f70e6fb4
ZJS
675 suffix = "user.conf.d";
676 }
75eb6154 677
f70e6fb4 678 (void) config_parse_many(
e94a009c
YW
679 (const char* const*) (files ?: STRV_MAKE(PKGSYSCONFDIR "/system.conf")),
680 (const char* const*) (dirs ?: CONF_PATHS_STRV("systemd")),
681 suffix,
4f9ff96a
LP
682 "Manager\0",
683 config_item_table_lookup, items,
684 CONFIG_PARSE_WARN,
685 NULL,
686 NULL);
36c16a7c 687
f70e6fb4
ZJS
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. */
36c16a7c
LP
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;
487393e9 694
487393e9
LP
695 return 0;
696}
697
85cb4151 698static void set_manager_defaults(Manager *m) {
06af2a04
TB
699
700 assert(m);
701
5b65ae15
LP
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
06af2a04
TB
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;
dc653bf4
JK
711 m->default_timeout_abort_usec = arg_default_timeout_abort_usec;
712 m->default_timeout_abort_set = arg_default_timeout_abort_set;
06af2a04
TB
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;
a88c5b8a
CD
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
13c31542 724 m->default_io_accounting = arg_default_io_accounting;
377bfd2d 725 m->default_ip_accounting = arg_default_ip_accounting;
06af2a04
TB
726 m->default_blockio_accounting = arg_default_blockio_accounting;
727 m->default_memory_accounting = arg_default_memory_accounting;
03a7b521 728 m->default_tasks_accounting = arg_default_tasks_accounting;
0af20ea2 729 m->default_tasks_max = arg_default_tasks_max;
afcfaa69 730 m->default_oom_policy = arg_default_oom_policy;
d4a402e4
LP
731 m->default_oom_score_adjust_set = arg_default_oom_score_adjust_set;
732 m->default_oom_score_adjust = arg_default_oom_score_adjust;
06af2a04 733
79a224c4
LP
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);
06af2a04
TB
738}
739
7b46fc6a 740static void set_manager_settings(Manager *m) {
aff3a9e1 741 int r;
7b46fc6a
LP
742
743 assert(m);
744
986935cf
FB
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). */
5b65ae15 748
7b46fc6a 749 m->confirm_spawn = arg_confirm_spawn;
2a12e32e 750 m->service_watchdogs = arg_service_watchdogs;
7b46fc6a
LP
751 m->cad_burst_action = arg_cad_burst_action;
752
986935cf
FB
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);
5717062e 756 manager_set_watchdog(m, WATCHDOG_PRETIMEOUT, arg_pretimeout_watchdog);
aff3a9e1
LB
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);
986935cf 760
7365a296 761 manager_set_show_status(m, arg_show_status, "commandline");
36cf4507 762 m->status_unit_format = arg_status_unit_format;
7b46fc6a
LP
763}
764
f170852a 765static int parse_argv(int argc, char *argv[]) {
f170852a
LP
766 enum {
767 ARG_LOG_LEVEL = 0x100,
768 ARG_LOG_TARGET,
bbe63281
LP
769 ARG_LOG_COLOR,
770 ARG_LOG_LOCATION,
c5673ed0 771 ARG_LOG_TIME,
2f198e2f 772 ARG_UNIT,
edb9aaa8 773 ARG_SYSTEM,
af2d49f7 774 ARG_USER,
e537352b 775 ARG_TEST,
b87c2aa6 776 ARG_NO_PAGER,
9ba0bc4e 777 ARG_VERSION,
80876c20 778 ARG_DUMP_CONFIGURATION_ITEMS,
bbc1acab 779 ARG_DUMP_BUS_PROPERTIES,
5c08257b 780 ARG_BUS_INTROSPECT,
9e58ff9c 781 ARG_DUMP_CORE,
b9e74c39 782 ARG_CRASH_CHVT,
9e58ff9c 783 ARG_CRASH_SHELL,
b9e74c39 784 ARG_CRASH_REBOOT,
a16e1123 785 ARG_CONFIRM_SPAWN,
9e58ff9c 786 ARG_SHOW_STATUS,
4288f619 787 ARG_DESERIALIZE,
2660882b 788 ARG_SWITCHED_ROOT,
0a494f1f 789 ARG_DEFAULT_STD_OUTPUT,
ee48dbd5 790 ARG_DEFAULT_STD_ERROR,
2a12e32e
JK
791 ARG_MACHINE_ID,
792 ARG_SERVICE_WATCHDOGS,
f170852a
LP
793 };
794
795 static const struct option options[] = {
a16e1123
LP
796 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
797 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
bbe63281
LP
798 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
799 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
c5673ed0 800 { "log-time", optional_argument, NULL, ARG_LOG_TIME },
2f198e2f 801 { "unit", required_argument, NULL, ARG_UNIT },
edb9aaa8 802 { "system", no_argument, NULL, ARG_SYSTEM },
af2d49f7 803 { "user", no_argument, NULL, ARG_USER },
a16e1123 804 { "test", no_argument, NULL, ARG_TEST },
b87c2aa6 805 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
a16e1123 806 { "help", no_argument, NULL, 'h' },
9ba0bc4e 807 { "version", no_argument, NULL, ARG_VERSION },
a16e1123 808 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
bbc1acab 809 { "dump-bus-properties", no_argument, NULL, ARG_DUMP_BUS_PROPERTIES },
5c08257b 810 { "bus-introspect", required_argument, NULL, ARG_BUS_INTROSPECT },
a5d87bf0 811 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
b9e74c39 812 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
a5d87bf0 813 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
b9e74c39 814 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
a5d87bf0 815 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
6e98720f 816 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
a16e1123 817 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
2660882b 818 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
0a494f1f
LP
819 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
820 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
ee48dbd5 821 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
2a12e32e 822 { "service-watchdogs", required_argument, NULL, ARG_SERVICE_WATCHDOGS },
fb472900 823 {}
f170852a
LP
824 };
825
826 int c, r;
9a9ca408 827 bool user_arg_seen = false;
f170852a
LP
828
829 assert(argc >= 1);
830 assert(argv);
831
df0ff127 832 if (getpid_cached() == 1)
b770165a
LP
833 opterr = 0;
834
099663ff 835 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
f170852a
LP
836
837 switch (c) {
838
839 case ARG_LOG_LEVEL:
fb472900 840 r = log_set_max_level_from_string(optarg);
2b5107e1
ZJS
841 if (r < 0)
842 return log_error_errno(r, "Failed to parse log level \"%s\": %m", optarg);
f170852a
LP
843
844 break;
845
846 case ARG_LOG_TARGET:
fb472900 847 r = log_set_target_from_string(optarg);
2b5107e1
ZJS
848 if (r < 0)
849 return log_error_errno(r, "Failed to parse log target \"%s\": %m", optarg);
f170852a
LP
850
851 break;
852
bbe63281
LP
853 case ARG_LOG_COLOR:
854
d0b170c8 855 if (optarg) {
fb472900 856 r = log_show_color_from_string(optarg);
2b5107e1
ZJS
857 if (r < 0)
858 return log_error_errno(r, "Failed to parse log color setting \"%s\": %m",
859 optarg);
d0b170c8
LP
860 } else
861 log_show_color(true);
bbe63281
LP
862
863 break;
864
865 case ARG_LOG_LOCATION:
d0b170c8 866 if (optarg) {
fb472900 867 r = log_show_location_from_string(optarg);
2b5107e1
ZJS
868 if (r < 0)
869 return log_error_errno(r, "Failed to parse log location setting \"%s\": %m",
870 optarg);
d0b170c8
LP
871 } else
872 log_show_location(true);
bbe63281
LP
873
874 break;
875
c5673ed0
DS
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
0a494f1f 888 case ARG_DEFAULT_STD_OUTPUT:
fb472900 889 r = exec_output_from_string(optarg);
2b5107e1
ZJS
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;
0a494f1f
LP
894 break;
895
896 case ARG_DEFAULT_STD_ERROR:
fb472900 897 r = exec_output_from_string(optarg);
2b5107e1
ZJS
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;
0a494f1f
LP
902 break;
903
2f198e2f 904 case ARG_UNIT:
e6e242ad 905 r = free_and_strdup(&arg_default_unit, optarg);
23bbb0de 906 if (r < 0)
2b5107e1 907 return log_error_errno(r, "Failed to set default unit \"%s\": %m", optarg);
f170852a
LP
908
909 break;
910
edb9aaa8 911 case ARG_SYSTEM:
463d0d15 912 arg_system = true;
edb9aaa8 913 break;
a5dab5ce 914
af2d49f7 915 case ARG_USER:
463d0d15 916 arg_system = false;
9a9ca408 917 user_arg_seen = true;
a5dab5ce 918 break;
a5dab5ce 919
e965d56d 920 case ARG_TEST:
fa0f4d8a 921 arg_action = ACTION_TEST;
b87c2aa6
ZJS
922 break;
923
924 case ARG_NO_PAGER:
0221d68a 925 arg_pager_flags |= PAGER_DISABLE;
e965d56d
LP
926 break;
927
9ba0bc4e
ZJS
928 case ARG_VERSION:
929 arg_action = ACTION_VERSION;
930 break;
931
e537352b 932 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 933 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
934 break;
935
bbc1acab
YW
936 case ARG_DUMP_BUS_PROPERTIES:
937 arg_action = ACTION_DUMP_BUS_PROPERTIES;
938 break;
939
5c08257b
ZJS
940 case ARG_BUS_INTROSPECT:
941 arg_bus_introspect = optarg;
942 arg_action = ACTION_BUS_INTROSPECT;
943 break;
944
9e58ff9c 945 case ARG_DUMP_CORE:
599c7c54
ZJS
946 r = parse_boolean_argument("--dump-core", optarg, &arg_dump_core);
947 if (r < 0)
948 return r;
b9e74c39
LP
949 break;
950
951 case ARG_CRASH_CHVT:
a07a7324 952 r = parse_crash_chvt(optarg, &arg_crash_chvt);
b9e74c39 953 if (r < 0)
2b5107e1
ZJS
954 return log_error_errno(r, "Failed to parse crash virtual terminal index: \"%s\": %m",
955 optarg);
9e58ff9c
LP
956 break;
957
958 case ARG_CRASH_SHELL:
599c7c54
ZJS
959 r = parse_boolean_argument("--crash-shell", optarg, &arg_crash_shell);
960 if (r < 0)
961 return r;
b9e74c39
LP
962 break;
963
964 case ARG_CRASH_REBOOT:
599c7c54
ZJS
965 r = parse_boolean_argument("--crash-reboot", optarg, &arg_crash_reboot);
966 if (r < 0)
967 return r;
9e58ff9c
LP
968 break;
969
80876c20 970 case ARG_CONFIRM_SPAWN:
7d5ceb64
FB
971 arg_confirm_spawn = mfree(arg_confirm_spawn);
972
973 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
974 if (r < 0)
2b5107e1
ZJS
975 return log_error_errno(r, "Failed to parse confirm spawn option: \"%s\": %m",
976 optarg);
80876c20
LP
977 break;
978
2a12e32e 979 case ARG_SERVICE_WATCHDOGS:
599c7c54 980 r = parse_boolean_argument("--service-watchdogs=", optarg, &arg_service_watchdogs);
2a12e32e 981 if (r < 0)
599c7c54 982 return r;
2a12e32e
JK
983 break;
984
9e58ff9c 985 case ARG_SHOW_STATUS:
d450b6f2
ZJS
986 if (optarg) {
987 r = parse_show_status(optarg, &arg_show_status);
ac7ec288 988 if (r < 0)
2b5107e1
ZJS
989 return log_error_errno(r, "Failed to parse show status boolean: \"%s\": %m",
990 optarg);
d450b6f2
ZJS
991 } else
992 arg_show_status = SHOW_STATUS_YES;
6e98720f 993 break;
a5d87bf0 994
a16e1123
LP
995 case ARG_DESERIALIZE: {
996 int fd;
997 FILE *f;
998
01e10de3 999 r = safe_atoi(optarg, &fd);
2b5107e1
ZJS
1000 if (r < 0)
1001 log_error_errno(r, "Failed to parse deserialize option \"%s\": %m", optarg);
baaa35ad
ZJS
1002 if (fd < 0)
1003 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1004 "Invalid deserialize fd: %d",
1005 fd);
a16e1123 1006
b9e74c39 1007 (void) fd_cloexec(fd, true);
01e10de3
LP
1008
1009 f = fdopen(fd, "r");
4a62c710 1010 if (!f)
2b5107e1 1011 return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
a16e1123 1012
74ca738f 1013 safe_fclose(arg_serialization);
d3b1c508 1014 arg_serialization = f;
a16e1123
LP
1015
1016 break;
1017 }
1018
2660882b 1019 case ARG_SWITCHED_ROOT:
bf4df7c3 1020 arg_switched_root = true;
d03bc1b8
HH
1021 break;
1022
ee48dbd5
NC
1023 case ARG_MACHINE_ID:
1024 r = set_machine_id(optarg);
54500613 1025 if (r < 0)
2b5107e1 1026 return log_error_errno(r, "MachineID '%s' is not valid: %m", optarg);
ee48dbd5
NC
1027 break;
1028
f170852a 1029 case 'h':
fa0f4d8a 1030 arg_action = ACTION_HELP;
f170852a
LP
1031 break;
1032
1d2e23ab
LP
1033 case 'D':
1034 log_set_max_level(LOG_DEBUG);
1035 break;
1036
099663ff
LP
1037 case 'b':
1038 case 's':
1039 case 'z':
cd57038a
ZJS
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 */
099663ff 1043 case '?':
df0ff127 1044 if (getpid_cached() != 1)
099663ff 1045 return -EINVAL;
601185b4
ZJS
1046 else
1047 return 0;
099663ff 1048
601185b4 1049 default:
04499a70 1050 assert_not_reached();
f170852a
LP
1051 }
1052
d7a0f1f4 1053 if (optind < argc && getpid_cached() != 1)
9a9ca408
ZJS
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)
baaa35ad 1058 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
9a9ca408 1059 "Explicit --user argument required to run as user manager.");
d821e6d6 1060
f170852a
LP
1061 return 0;
1062}
1063
1064static int help(void) {
37ec0fdd
LP
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();
f170852a 1071
2e33c433 1072 printf("%s [OPTIONS...]\n\n"
7ae47326
ZJS
1073 "%sStarts and monitors system and user services.%s\n\n"
1074 "This program takes no positional arguments.\n\n"
1075 "%sOptions%s:\n"
e537352b 1076 " -h --help Show this help\n"
cb4069d9 1077 " --version Show version\n"
cd69e88b 1078 " --test Determine initial transaction, dump it and exit\n"
03b3b55e
ZJS
1079 " --system Combined with --test: operate in system mode\n"
1080 " --user Combined with --test: operate in user mode\n"
80876c20 1081 " --dump-configuration-items Dump understood unit configuration items\n"
bbc1acab 1082 " --dump-bus-properties Dump exposed bus properties\n"
5c08257b 1083 " --bus-introspect=PATH Write XML introspection data\n"
9e58ff9c 1084 " --unit=UNIT Set default unit\n"
b9e74c39
LP
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"
03b3b55e
ZJS
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"
b9e74c39
LP
1095 " --log-color[=BOOL] Highlight important log messages\n"
1096 " --log-location[=BOOL] Include code location in log messages\n"
c5673ed0 1097 " --log-time[=BOOL] Prefix log messages with current time\n"
0a494f1f 1098 " --default-standard-output= Set default standard output for services\n"
37ec0fdd 1099 " --default-standard-error= Set default standard error output for services\n"
03b3b55e 1100 " --no-pager Do not pipe output into a pager\n"
bc556335
DDM
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);
f170852a
LP
1108
1109 return 0;
1110}
1111
2cc856ac
LP
1112static int prepare_reexecute(
1113 Manager *m,
1114 FILE **ret_f,
1115 FDSet **ret_fds,
1116 bool switching_root) {
1117
48b90859
LP
1118 _cleanup_fdset_free_ FDSet *fds = NULL;
1119 _cleanup_fclose_ FILE *f = NULL;
a16e1123
LP
1120 int r;
1121
1122 assert(m);
2cc856ac
LP
1123 assert(ret_f);
1124 assert(ret_fds);
a16e1123 1125
6b78f9b4 1126 r = manager_open_serialization(m, &f);
48b90859
LP
1127 if (r < 0)
1128 return log_error_errno(r, "Failed to create serialization file: %m");
a16e1123 1129
71445ae7 1130 /* Make sure nothing is really destructed when we shut down */
313cefa1 1131 m->n_reloading++;
718db961 1132 bus_manager_send_reloading(m, true);
71445ae7 1133
6b78f9b4 1134 fds = fdset_new();
48b90859
LP
1135 if (!fds)
1136 return log_oom();
a16e1123 1137
b3680f49 1138 r = manager_serialize(m, f, fds, switching_root);
48b90859 1139 if (r < 0)
d68c645b 1140 return r;
a16e1123 1141
48b90859
LP
1142 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1143 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
a16e1123 1144
6b78f9b4 1145 r = fd_cloexec(fileno(f), false);
48b90859
LP
1146 if (r < 0)
1147 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
a16e1123 1148
6b78f9b4 1149 r = fdset_cloexec(fds, false);
48b90859
LP
1150 if (r < 0)
1151 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
a16e1123 1152
2cc856ac
LP
1153 *ret_f = TAKE_PTR(f);
1154 *ret_fds = TAKE_PTR(fds);
a16e1123 1155
48b90859 1156 return 0;
a16e1123
LP
1157}
1158
a8b627aa
LP
1159static void bump_file_max_and_nr_open(void) {
1160
ff3a7019
ZJS
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. */
a8b627aa
LP
1166
1167#if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
a8b627aa
LP
1168 int r;
1169#endif
1170
1171#if BUMP_PROC_SYS_FS_FILE_MAX
409607c1
ZJS
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.) */
56e8419a 1174 r = sysctl_writef("fs/file-max", "%li\n", LONG_MAX);
a8b627aa
LP
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
a8b627aa
LP
1179#if BUMP_PROC_SYS_FS_NR_OPEN
1180 int v = INT_MAX;
1181
ff3a7019
ZJS
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... 🤯 */
a8b627aa
LP
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
56e8419a 1208 r = sysctl_writef("fs/nr_open", "%i\n", v);
a8b627aa
LP
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
eadb4f19 1225static int bump_rlimit_nofile(const struct rlimit *saved_rlimit) {
cda7faa9 1226 struct rlimit new_rlimit;
9264cc39 1227 int r, nr;
4096d6f5 1228
52d62075
LP
1229 /* Get the underlying absolute limit the kernel enforces */
1230 nr = read_nr_open();
1231
cda7faa9
LP
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
52d62075
LP
1245 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1246 * both hard and soft. */
cda7faa9 1247 r = setrlimit_closest(RLIMIT_NOFILE, &new_rlimit);
23bbb0de 1248 if (r < 0)
3ce40911 1249 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5
LP
1250
1251 return 0;
1252}
1253
eadb4f19 1254static int bump_rlimit_memlock(const struct rlimit *saved_rlimit) {
cda7faa9 1255 struct rlimit new_rlimit;
04d1ee0f 1256 uint64_t mm;
fb3ae275
LP
1257 int r;
1258
ff3a7019
ZJS
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. */
fb3ae275 1262
cda7faa9
LP
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
ff3a7019
ZJS
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. */
04d1ee0f 1270
cda7faa9 1271 new_rlimit = (struct rlimit) {
04d1ee0f
LP
1272 .rlim_cur = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_cur, mm),
1273 .rlim_max = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_max, mm),
cda7faa9
LP
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);
fb3ae275
LP
1283 if (r < 0)
1284 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1285
1286 return 0;
1287}
1288
80758717 1289static void test_usr(void) {
80758717 1290
796ac4c1 1291 /* Check that /usr is either on the same file system as / or mounted already. */
80758717 1292
db55bbf2 1293 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
871c44a7
LP
1294 return;
1295
8b173b5e 1296 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
871c44a7
LP
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
d3b1c508 1301static int enforce_syscall_archs(Set *archs) {
349cc4a5 1302#if HAVE_SECCOMP
d3b1c508
LP
1303 int r;
1304
83f12b27
FS
1305 if (!is_seccomp_available())
1306 return 0;
1307
469830d1 1308 r = seccomp_restrict_archs(arg_syscall_archs);
d3b1c508 1309 if (r < 0)
469830d1 1310 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
d3b1c508 1311#endif
469830d1 1312 return 0;
d3b1c508
LP
1313}
1314
b6e2f329
LP
1315static int status_welcome(void) {
1316 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1317 int r;
1318
5ca02bfc 1319 if (!show_status_on(arg_show_status))
fd8c85c6
LP
1320 return 0;
1321
d58ad743
LP
1322 r = parse_os_release(NULL,
1323 "PRETTY_NAME", &pretty_name,
209c1470 1324 "ANSI_COLOR", &ansi_color);
d58ad743
LP
1325 if (r < 0)
1326 log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1327 "Failed to read os-release file, ignoring: %m");
b6e2f329 1328
dc9b5816 1329 if (log_get_show_color())
a885727a 1330 return status_printf(NULL, 0,
dc9b5816
ZJS
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
a885727a 1335 return status_printf(NULL, 0,
dc9b5816
ZJS
1336 "\nWelcome to %s!\n",
1337 isempty(pretty_name) ? "Linux" : pretty_name);
b6e2f329
LP
1338}
1339
fdd25311
LP
1340static int write_container_id(void) {
1341 const char *c;
7756528e 1342 int r = 0; /* avoid false maybe-uninitialized warning */
fdd25311
LP
1343
1344 c = getenv("container");
1345 if (isempty(c))
1346 return 0;
1347
8612da97
LP
1348 RUN_WITH_UMASK(0022)
1349 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
19854865 1350 if (r < 0)
f1f849b0 1351 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
19854865
LP
1352
1353 return 1;
1354}
1355
1356static int bump_unix_max_dgram_qlen(void) {
1357 _cleanup_free_ char *qlen = NULL;
1358 unsigned long v;
1359 int r;
1360
ff3a7019
ZJS
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. */
19854865
LP
1364
1365 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1366 if (r < 0)
ff3a7019
ZJS
1367 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1368 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
19854865
LP
1369
1370 r = safe_atolu(qlen, &v);
1371 if (r < 0)
3130fca5 1372 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen);
19854865
LP
1373
1374 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1375 return 0;
1376
ff3a7019
ZJS
1377 r = write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER,
1378 "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN);
19854865
LP
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;
fdd25311
LP
1384}
1385
32391275
FB
1386static int fixup_environment(void) {
1387 _cleanup_free_ char *term = NULL;
4dc63c4b 1388 const char *t;
32391275
FB
1389 int r;
1390
43db615b
LP
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. */
84af7821
LP
1396 if (detect_container() > 0)
1397 return 0;
1398
ff3a7019
ZJS
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.
32391275 1402 *
43db615b 1403 * However if TERM was configured through the kernel command line then leave it alone. */
1d84ad94 1404 r = proc_cmdline_get_key("TERM", 0, &term);
32391275
FB
1405 if (r < 0)
1406 return r;
32391275 1407
4dc63c4b
LP
1408 t = term ?: default_term_for_tty("/dev/console");
1409
1410 if (setenv("TERM", t, 1) < 0)
32391275
FB
1411 return -errno;
1412
9d48671c 1413 /* The kernels sets HOME=/ for init. Let's undo this. */
44ee03d1
ZJS
1414 if (path_equal_ptr(getenv("HOME"), "/"))
1415 assert_se(unsetenv("HOME") == 0);
9d48671c 1416
32391275
FB
1417 return 0;
1418}
1419
6808a0bc
LP
1420static 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
2306d177 1428 if (!invoked_as(argv, "init"))
6808a0bc
LP
1429 return;
1430
1431 execv(SYSTEMCTL_BINARY_PATH, argv);
1432 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
a45d7127 1433 exit(EXIT_FAILURE);
6808a0bc
LP
1434#endif
1435}
1436
4a36297c
LP
1437static int become_shutdown(
1438 const char *shutdown_verb,
7eb35049 1439 int retval) {
4a36297c
LP
1440
1441 char log_level[DECIMAL_STR_MAX(int) + 1],
e73c54b8
JK
1442 exit_code[DECIMAL_STR_MAX(uint8_t) + 1],
1443 timeout[DECIMAL_STR_MAX(usec_t) + 1];
4a36297c 1444
e73c54b8 1445 const char* command_line[13] = {
4a36297c
LP
1446 SYSTEMD_SHUTDOWN_BINARY_PATH,
1447 shutdown_verb,
e73c54b8 1448 "--timeout", timeout,
4a36297c
LP
1449 "--log-level", log_level,
1450 "--log-target",
1451 };
1452
1453 _cleanup_strv_free_ char **env_block = NULL;
f16890f8 1454 usec_t watchdog_timer = 0;
e73c54b8 1455 size_t pos = 7;
4a36297c
LP
1456 int r;
1457
7eb35049 1458 assert(shutdown_verb);
234519ae 1459 assert(!command_line[pos]);
4a36297c
LP
1460 env_block = strv_copy(environ);
1461
1462 xsprintf(log_level, "%d", log_get_max_level());
e73c54b8 1463 xsprintf(timeout, "%" PRI_USEC "us", arg_default_timeout_stop_usec);
4a36297c
LP
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
c5673ed0
DS
1489 if (log_get_show_time())
1490 command_line[pos++] = "--log-time";
1491
4a36297c
LP
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
acafd7d8 1500 if (streq(shutdown_verb, "reboot"))
65224c1d 1501 watchdog_timer = arg_reboot_watchdog;
acafd7d8
LB
1502 else if (streq(shutdown_verb, "kexec"))
1503 watchdog_timer = arg_kexec_watchdog;
1504
f16890f8 1505 /* If we reboot or kexec let's set the shutdown watchdog and tell the
5717062e
CK
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);
aff3a9e1 1509 (void) watchdog_setup_pretimeout_governor(NULL);
f16890f8
FB
1510 r = watchdog_setup(watchdog_timer);
1511 watchdog_close(r < 0);
4a36297c 1512
f16890f8
FB
1513 /* Tell the binary how often to ping, ignore failure */
1514 (void) strv_extendf(&env_block, "WATCHDOG_USEC="USEC_FMT, watchdog_timer);
8a2c1fbf 1515
f16890f8
FB
1516 if (arg_watchdog_device)
1517 (void) strv_extendf(&env_block, "WATCHDOG_DEVICE=%s", arg_watchdog_device);
4a36297c 1518
3178d23d
FB
1519 /* Avoid the creation of new processes forked by the kernel; at this
1520 * point, we will not listen to the signals anyway */
4a36297c
LP
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
e839bafd
LP
1528static void initialize_clock(void) {
1529 int r;
1530
3753325b
LP
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
e839bafd
LP
1534 if (clock_is_localtime(NULL) > 0) {
1535 int min;
1536
ff3a7019 1537 /* The very first call of settimeofday() also does a time warp in the kernel.
e839bafd 1538 *
ff3a7019
ZJS
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.
e839bafd
LP
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
d46b79bb 1549 } else if (!in_initrd())
e839bafd
LP
1550 /*
1551 * Do a dummy very first call to seal the kernel's time warp magic.
1552 *
ff3a7019
ZJS
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.
e839bafd 1556 *
ff3a7019
ZJS
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.
e839bafd
LP
1560 */
1561 (void) clock_reset_timewarp();
e839bafd 1562
b10abe4b
EI
1563 ClockChangeDirection change_dir;
1564 r = clock_apply_epoch(&change_dir);
1565 if (r > 0 && change_dir == CLOCK_CHANGE_FORWARD)
e839bafd 1566 log_info("System time before build time, advancing clock.");
b10abe4b
EI
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));
e839bafd
LP
1575}
1576
3753325b 1577static void apply_clock_update(void) {
3753325b
LP
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
45250e66
LP
1584 if (getpid_cached() != 1)
1585 return;
1586
52bb308c 1587 if (clock_settime(CLOCK_REALTIME, TIMESPEC_STORE(arg_clock_usec)) < 0)
3753325b 1588 log_error_errno(errno, "Failed to set system clock to time specified on kernel command line: %m");
04f5c018 1589 else
3753325b 1590 log_info("Set system clock to %s, as specified on the kernel command line.",
04f5c018 1591 FORMAT_TIMESTAMP(arg_clock_usec));
3753325b
LP
1592}
1593
d247f232 1594static void cmdline_take_random_seed(void) {
d247f232
LP
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
61bd7d1e 1611 r = random_write_entropy(-1, arg_random_seed, arg_random_seed_size, true);
d247f232
LP
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"
ff3a7019
ZJS
1618 "Note that the seed provided this way is accessible to unprivileged programs. "
1619 "This functionality should not be used outside of testing environments.");
d247f232
LP
1620}
1621
1e41242e 1622static void initialize_coredump(bool skip_setup) {
752bcb77 1623#if ENABLE_COREDUMP
1e41242e
LP
1624 if (getpid_cached() != 1)
1625 return;
1626
ff3a7019
ZJS
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. */
1e41242e
LP
1629 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1630 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1631
ff3a7019
ZJS
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. */
1e41242e 1635 if (!skip_setup)
e557b1a6 1636 disable_coredumps();
752bcb77 1637#endif
1e41242e
LP
1638}
1639
c6885f5f
FB
1640static 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
57512c89 1649 r = write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern, WRITE_STRING_FILE_DISABLE_BUFFER);
c6885f5f 1650 if (r < 0)
ff3a7019
ZJS
1651 log_warning_errno(r, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1652 arg_early_core_pattern);
c6885f5f
FB
1653}
1654
61fbbac1
ZJS
1655static 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
667030bf
ZJS
1663 mask = cpu_set_to_range_string(&arg_cpu_affinity);
1664 log_debug("Setting CPU affinity to {%s}.", strnull(mask));
61fbbac1
ZJS
1665
1666 if (sched_setaffinity(0, arg_cpu_affinity.allocated, arg_cpu_affinity.set) < 0)
6b1fa539 1667 log_warning_errno(errno, "Failed to set CPU affinity, ignoring: %m");
61fbbac1
ZJS
1668}
1669
b070c7c0
MS
1670static 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);
667030bf 1681 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy), strnull(nodes));
b070c7c0
MS
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)
6b1fa539 1688 log_warning_errno(r, "Failed to set NUMA memory policy, ignoring: %m");
b070c7c0
MS
1689}
1690
19fd72df
LP
1691static void filter_args(
1692 const char* dst[],
1693 size_t *dst_index,
1694 char **src,
1695 int argc) {
1696
846f1da4 1697 assert(dst);
19fd72df 1698 assert(dst_index);
846f1da4
ZJS
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. */
19fd72df 1732 dst[(*dst_index)++] = src[i];
846f1da4
ZJS
1733 }
1734}
1735
1e3eee8c
ZJS
1736static int do_reexecute(
1737 ManagerObjective objective,
3c7878f9 1738 int argc,
846f1da4 1739 char* argv[],
3c7878f9
LP
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
19fd72df 1747 size_t i, args_size;
3c7878f9
LP
1748 const char **args;
1749 int r;
1750
1e3eee8c 1751 assert(IN_SET(objective, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT));
19fd72df 1752 assert(argc >= 0);
3c7878f9
LP
1753 assert(saved_rlimit_nofile);
1754 assert(saved_rlimit_memlock);
1755 assert(ret_error_message);
1756
ff3a7019
ZJS
1757 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1758 * rebooted while we do that */
3c7878f9
LP
1759 watchdog_close(true);
1760
ddfa8b0b
LP
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)
3c7878f9 1764 (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
ddfa8b0b 1765 if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
3c7878f9
LP
1766 (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
1767
1768 if (switch_root_dir) {
ff3a7019
ZJS
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. */
e73c54b8 1771 broadcast_signal(SIGTERM, false, true, arg_default_timeout_stop_usec);
3c7878f9
LP
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
846f1da4 1779 args_size = argc + 6;
3c7878f9
LP
1780 args = newa(const char*, args_size);
1781
1782 if (!switch_root_init) {
846f1da4 1783 char sfd[DECIMAL_STR_MAX(int)];
3c7878f9 1784
ff3a7019
ZJS
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. */
3c7878f9
LP
1787
1788 assert(arg_serialization);
1789 assert(fds);
1790
1791 xsprintf(sfd, "%i", fileno(arg_serialization));
1792
846f1da4
ZJS
1793 i = 1; /* Leave args[0] empty for now. */
1794 filter_args(args, &i, argv, argc);
1795
3c7878f9
LP
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 /*
ff3a7019
ZJS
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().
3c7878f9
LP
1810 */
1811 valgrind_summary_hack();
1812
846f1da4 1813 args[0] = SYSTEMD_BINARY_PATH;
3c7878f9 1814 (void) execv(args[0], (char* const*) args);
1e3eee8c
ZJS
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
846f1da4 1821 log_debug_errno(errno, "Failed to execute our own binary %s, trying fallback: %m", args[0]);
3c7878f9
LP
1822 }
1823
ff3a7019
ZJS
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.) */
3c7878f9
LP
1827
1828 arg_serialization = safe_fclose(arg_serialization);
1829 fds = fdset_free(fds);
1830
1831 /* Reopen the console */
1832 (void) make_console_stdio();
1833
846f1da4
ZJS
1834 i = 1; /* Leave args[0] empty for now. */
1835 for (int j = 1; j <= argc; j++)
3c7878f9 1836 args[i++] = argv[j];
3c7878f9
LP
1837 assert(i <= args_size);
1838
5238e957 1839 /* Re-enable any blocked signals, especially important if we switch from initial ramdisk to init=... */
3c7878f9
LP
1840 (void) reset_all_signal_handlers();
1841 (void) reset_signal_mask();
595225af 1842 (void) rlimit_nofile_safe();
3c7878f9
LP
1843
1844 if (switch_root_init) {
1845 args[0] = switch_root_init;
a5cede8c 1846 (void) execve(args[0], (char* const*) args, saved_env);
846f1da4 1847 log_warning_errno(errno, "Failed to execute configured init %s, trying fallback: %m", args[0]);
3c7878f9
LP
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
1e3eee8c 1858 *ret_error_message = "Failed to execute fallback shell";
3c7878f9
LP
1859 if (r == -ENOENT) {
1860 log_warning("No /sbin/init, trying fallback");
1861
1862 args[0] = "/bin/sh";
1863 args[1] = NULL;
a5cede8c 1864 (void) execve(args[0], (char* const*) args, saved_env);
1e3eee8c 1865 return log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
3c7878f9 1866 } else
6b1fa539 1867 return log_error_errno(r, "Failed to execute /sbin/init, giving up: %m");
3c7878f9
LP
1868}
1869
7eb35049
LP
1870static int invoke_main_loop(
1871 Manager *m,
a9fd4cd1
FB
1872 const struct rlimit *saved_rlimit_nofile,
1873 const struct rlimit *saved_rlimit_memlock,
7eb35049
LP
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);
a9fd4cd1
FB
1884 assert(saved_rlimit_nofile);
1885 assert(saved_rlimit_memlock);
7eb35049
LP
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 (;;) {
5409c6fc
ZJS
1894 int objective = manager_loop(m);
1895 if (objective < 0) {
7eb35049 1896 *ret_error_message = "Failed to run main loop";
5409c6fc 1897 return log_emergency_errno(objective, "Failed to run main loop: %m");
7eb35049
LP
1898 }
1899
5409c6fc 1900 switch (objective) {
7eb35049 1901
a6ecbf83 1902 case MANAGER_RELOAD: {
bda7d78b 1903 LogTarget saved_log_target;
a6ecbf83
FB
1904 int saved_log_level;
1905
7eb35049
LP
1906 log_info("Reloading.");
1907
ff3a7019
ZJS
1908 /* First, save any overridden log level/target, then parse the configuration file,
1909 * which might change the log level to new settings. */
bda7d78b 1910
a6ecbf83 1911 saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
bda7d78b 1912 saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
a6ecbf83 1913
a9fd4cd1 1914 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
7eb35049
LP
1915
1916 set_manager_defaults(m);
986935cf 1917 set_manager_settings(m);
7eb35049 1918
61fbbac1 1919 update_cpu_affinity(false);
b070c7c0 1920 update_numa_policy(false);
61fbbac1 1921
a6ecbf83
FB
1922 if (saved_log_level >= 0)
1923 manager_override_log_level(m, saved_log_level);
bda7d78b
FB
1924 if (saved_log_target >= 0)
1925 manager_override_log_target(m, saved_log_target);
a6ecbf83 1926
5409c6fc 1927 if (manager_reload(m) < 0)
ff3a7019
ZJS
1928 /* Reloading failed before the point of no return.
1929 * Let's continue running as if nothing happened. */
7a35fa24 1930 m->objective = MANAGER_OK;
7eb35049 1931
5409c6fc 1932 continue;
a6ecbf83 1933 }
7eb35049
LP
1934
1935 case MANAGER_REEXECUTE:
7eb35049
LP
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
7eb35049
LP
1944 *ret_retval = EXIT_SUCCESS;
1945 *ret_shutdown_verb = NULL;
1946 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1947
5409c6fc 1948 return objective;
7eb35049
LP
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
7eb35049
LP
1962 *ret_retval = EXIT_SUCCESS;
1963 *ret_shutdown_verb = NULL;
1964
1965 /* Steal the switch root parameters */
49052946
YW
1966 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
1967 *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
7eb35049 1968
5409c6fc 1969 return objective;
7eb35049
LP
1970
1971 case MANAGER_EXIT:
7eb35049
LP
1972 if (MANAGER_IS_USER(m)) {
1973 log_debug("Exit.");
1974
7eb35049
LP
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
5409c6fc 1980 return objective;
7eb35049
LP
1981 }
1982
1983 _fallthrough_;
1984 case MANAGER_REBOOT:
1985 case MANAGER_POWEROFF:
1986 case MANAGER_HALT:
1987 case MANAGER_KEXEC: {
5409c6fc 1988 static const char* const table[_MANAGER_OBJECTIVE_MAX] = {
af41e508
LP
1989 [MANAGER_EXIT] = "exit",
1990 [MANAGER_REBOOT] = "reboot",
7eb35049 1991 [MANAGER_POWEROFF] = "poweroff",
af41e508
LP
1992 [MANAGER_HALT] = "halt",
1993 [MANAGER_KEXEC] = "kexec",
7eb35049
LP
1994 };
1995
1996 log_notice("Shutting down.");
1997
7eb35049 1998 *ret_retval = m->return_value;
af41e508 1999 assert_se(*ret_shutdown_verb = table[m->objective]);
7eb35049
LP
2000 *ret_fds = NULL;
2001 *ret_switch_root_dir = *ret_switch_root_init = NULL;
2002
5409c6fc 2003 return objective;
7eb35049
LP
2004 }
2005
2006 default:
04499a70 2007 assert_not_reached();
7eb35049
LP
2008 }
2009 }
2010}
2011
31aef7ff
LP
2012static void log_execution_mode(bool *ret_first_boot) {
2013 assert(ret_first_boot);
2014
2015 if (arg_system) {
40efaaed 2016 struct utsname uts;
31aef7ff
LP
2017 int v;
2018
e7b18106 2019 log_info("systemd " GIT_VERSION " running in %ssystem mode (%s)",
91b79ba8
ZJS
2020 arg_action == ACTION_TEST ? "test " : "",
2021 systemd_features);
31aef7ff
LP
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 {
583cef3b
HS
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 }
31aef7ff 2053 }
40efaaed 2054
5180394b 2055 assert_se(uname(&uts) >= 0);
40efaaed
LP
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);
31aef7ff 2062 } else {
b9e90f3a 2063 if (DEBUG_LOGGING) {
c2b2df60 2064 _cleanup_free_ char *t = NULL;
31aef7ff 2065
b9e90f3a 2066 t = uid_to_name(getuid());
91b79ba8
ZJS
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);
b9e90f3a 2070 }
31aef7ff
LP
2071
2072 *ret_first_boot = false;
2073 }
2074}
2075
5afbaa36
LP
2076static int initialize_runtime(
2077 bool skip_setup,
3023f2fe 2078 bool first_boot,
5afbaa36
LP
2079 struct rlimit *saved_rlimit_nofile,
2080 struct rlimit *saved_rlimit_memlock,
2081 const char **ret_error_message) {
5afbaa36
LP
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
2d776038
LP
2093 if (arg_action != ACTION_RUN)
2094 return 0;
2095
61fbbac1 2096 update_cpu_affinity(skip_setup);
b070c7c0 2097 update_numa_policy(skip_setup);
61fbbac1 2098
3c3c6cb9 2099 if (arg_system) {
5238e957 2100 /* Make sure we leave a core dump without panicking the kernel. */
3c3c6cb9 2101 install_crash_handler();
5afbaa36 2102
3c3c6cb9 2103 if (!skip_setup) {
143fadf3 2104 r = mount_cgroup_controllers();
3c3c6cb9
LP
2105 if (r < 0) {
2106 *ret_error_message = "Failed to mount cgroup hierarchies";
2107 return r;
2108 }
2109
2110 status_welcome();
b6fad306 2111 (void) hostname_setup(true);
3023f2fe
HS
2112 /* Force transient machine-id on first boot. */
2113 machine_id_setup(NULL, first_boot, arg_machine_id, NULL);
df883de9 2114 (void) loopback_setup();
3c3c6cb9 2115 bump_unix_max_dgram_qlen();
a8b627aa 2116 bump_file_max_and_nr_open();
3c3c6cb9
LP
2117 test_usr();
2118 write_container_id();
2119 }
8a2c1fbf 2120
3c3c6cb9
LP
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 }
32429805
LP
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
e813a74a 2138 (void) mkdir_p_label(p, 0755);
32429805 2139 (void) make_inaccessible_nodes(p, UID_INVALID, GID_INVALID);
3c3c6cb9 2140 }
5afbaa36
LP
2141
2142 if (arg_timer_slack_nsec != NSEC_INFINITY)
2143 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
3a671cd1 2144 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
5afbaa36
LP
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
39362f6f
JB
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
5afbaa36
LP
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)
6b1fa539 2178 log_warning_errno(errno, "Failed to make us a subreaper, ignoring: %m");
5afbaa36 2179
a17c1712
LP
2180 /* Bump up RLIMIT_NOFILE for systemd itself */
2181 (void) bump_rlimit_nofile(saved_rlimit_nofile);
2182 (void) bump_rlimit_memlock(saved_rlimit_memlock);
5afbaa36 2183
4b9a4b01
LP
2184 /* Pull credentials from various sources into a common credential directory */
2185 if (arg_system && !skip_setup)
2186 (void) import_credentials();
2187
5afbaa36
LP
2188 return 0;
2189}
2190
6acca5fc
LP
2191static 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;
f1d075dc
ZJS
2196 const char *unit;
2197 Job *job;
2198 Unit *target;
6acca5fc
LP
2199 int r;
2200
8755dbad 2201 if (arg_default_unit)
f1d075dc 2202 unit = arg_default_unit;
8755dbad 2203 else if (in_initrd())
f1d075dc 2204 unit = SPECIAL_INITRD_TARGET;
8755dbad 2205 else
f1d075dc 2206 unit = SPECIAL_DEFAULT_TARGET;
8755dbad 2207
f1d075dc 2208 log_debug("Activating default unit: %s", unit);
8755dbad 2209
f1d075dc 2210 r = manager_load_startable_unit_or_warn(m, unit, NULL, &target);
8755dbad
ZJS
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 ".");
6acca5fc 2216
8755dbad
ZJS
2217 r = manager_load_startable_unit_or_warn(m, SPECIAL_DEFAULT_TARGET, NULL, &target);
2218 }
4109ede7 2219 if (r < 0) {
8755dbad 2220 log_info("Falling back to " SPECIAL_RESCUE_TARGET ".");
6acca5fc 2221
4109ede7 2222 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
6acca5fc 2223 if (r < 0) {
8755dbad
ZJS
2224 *ret_error_message = r == -ERFKILL ? SPECIAL_RESCUE_TARGET " masked"
2225 : "Failed to load " SPECIAL_RESCUE_TARGET;
4109ede7 2226 return r;
6acca5fc
LP
2227 }
2228 }
2229
2230 assert(target->load_state == UNIT_LOADED);
2231
f1d075dc 2232 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &job);
6acca5fc
LP
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
f1d075dc 2238 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &job);
6acca5fc
LP
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));
c86c31d9
ZJS
2247 } else
2248 log_info("Queued %s job for default target %s.",
2249 job_type_to_string(job->type),
04d232d8 2250 unit_status_string(job->unit, NULL));
6acca5fc 2251
f1d075dc 2252 m->default_unit_job_id = job->id;
6acca5fc
LP
2253
2254 return 0;
2255}
2256
a9fd4cd1
FB
2257static 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
2270static 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
2314static 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
852b6250
LP
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
a9fd4cd1
FB
2335 arg_default_rlimit[RLIMIT_MEMLOCK] = rl;
2336}
2337
d55ed7de 2338static void setenv_manager_environment(void) {
d55ed7de
ZJS
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
fb39af4c
ZJS
2350static void reset_arguments(void) {
2351 /* Frees/resets arg_* variables, with a few exceptions commented below. */
970777b5
LP
2352
2353 arg_default_unit = mfree(arg_default_unit);
fb39af4c
ZJS
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;
970777b5 2361 arg_confirm_spawn = mfree(arg_confirm_spawn);
fb39af4c 2362 arg_show_status = _SHOW_STATUS_INVALID;
36cf4507 2363 arg_status_unit_format = STATUS_UNIT_FORMAT_DEFAULT;
fb39af4c
ZJS
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;
65224c1d 2377 arg_reboot_watchdog = 10 * USEC_PER_MINUTE;
acafd7d8 2378 arg_kexec_watchdog = 0;
5717062e 2379 arg_pretimeout_watchdog = 0;
fb39af4c
ZJS
2380 arg_early_core_pattern = NULL;
2381 arg_watchdog_device = NULL;
aff3a9e1 2382 arg_watchdog_pretimeout_governor = mfree(arg_watchdog_pretimeout_governor);
fb39af4c 2383
970777b5 2384 arg_default_environment = strv_free(arg_default_environment);
d55ed7de 2385 arg_manager_environment = strv_free(arg_manager_environment);
fb39af4c
ZJS
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
970777b5 2393 arg_syscall_archs = set_free(arg_syscall_archs);
61fbbac1 2394
fb39af4c
ZJS
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;
3a0f06c4 2403 arg_default_tasks_max = DEFAULT_TASKS_MAX;
fb39af4c
ZJS
2404 arg_machine_id = (sd_id128_t) {};
2405 arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
2406 arg_default_oom_policy = OOM_STOP;
2407
61fbbac1 2408 cpu_set_reset(&arg_cpu_affinity);
b070c7c0 2409 numa_policy_reset(&arg_numa_policy);
d247f232
LP
2410
2411 arg_random_seed = mfree(arg_random_seed);
2412 arg_random_seed_size = 0;
33d943d1 2413 arg_clock_usec = 0;
d4a402e4
LP
2414
2415 arg_default_oom_score_adjust_set = false;
2416}
2417
2418static 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;
970777b5
LP
2443}
2444
a9fd4cd1
FB
2445static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
2446 const struct rlimit *saved_rlimit_memlock) {
97d1fb94
LP
2447 int r;
2448
a9fd4cd1
FB
2449 assert(saved_rlimit_nofile);
2450 assert(saved_rlimit_memlock);
2451
fb39af4c
ZJS
2452 /* Assign configuration defaults */
2453 reset_arguments();
2454
97d1fb94 2455 r = parse_config_file();
470a5e6d
ZJS
2456 if (r < 0)
2457 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
97d1fb94
LP
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
a9fd4cd1
FB
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
97d1fb94
LP
2469 /* Note that this also parses bits from the kernel command line, including "debug". */
2470 log_parse_environment();
2471
db33214b 2472 /* Initialize the show status setting if it hasn't been set explicitly yet */
7a293242 2473 if (arg_show_status == _SHOW_STATUS_INVALID)
db33214b
LP
2474 arg_show_status = SHOW_STATUS_YES;
2475
d4a402e4
LP
2476 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2477 determine_default_oom_score_adjust();
2478
d55ed7de
ZJS
2479 /* Push variables into the manager environment block */
2480 setenv_manager_environment();
2481
a4303b40
DDM
2482 /* Parse log environment variables again to take into account any new environment variables. */
2483 log_parse_environment();
2484
97d1fb94
LP
2485 return 0;
2486}
2487
b0d7c989
LP
2488static int safety_checks(void) {
2489
febf46a4 2490 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2491 arg_action != ACTION_RUN)
2492 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2493 "Unsupported execution mode while PID 1.");
febf46a4
LP
2494
2495 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2496 !arg_system)
2497 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2498 "Can't run --user mode as PID 1.");
febf46a4
LP
2499
2500 if (arg_action == ACTION_RUN &&
2501 arg_system &&
baaa35ad
ZJS
2502 getpid_cached() != 1)
2503 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2504 "Can't run system mode unless PID 1.");
febf46a4 2505
b0d7c989 2506 if (arg_action == ACTION_TEST &&
baaa35ad
ZJS
2507 geteuid() == 0)
2508 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2509 "Don't run test mode as root.");
b0d7c989
LP
2510
2511 if (!arg_system &&
2512 arg_action == ACTION_RUN &&
baaa35ad
ZJS
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.");
b0d7c989
LP
2516
2517 if (!arg_system &&
2518 arg_action == ACTION_RUN &&
baaa35ad
ZJS
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.");
b0d7c989
LP
2522
2523 if (arg_system &&
2524 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2525 running_in_chroot() > 0)
2526 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2527 "Cannot be run in a chroot() environment.");
b0d7c989
LP
2528
2529 return 0;
2530}
2531
74da609f
LP
2532static 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
97149f40 2547 r = mac_selinux_setup(loaded_policy);
74da609f
LP
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
2ffadd3c
Y
2559 r = mac_apparmor_setup();
2560 if (r < 0) {
2561 *ret_error_message = "Failed to load AppArmor policy";
2562 return r;
2563 }
2564
74da609f
LP
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
efeb853f
LP
2575static 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
2e51b31c
LP
2595static 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
ff3a7019
ZJS
2603 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2604 * controlling tty. */
2e51b31c
LP
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
aa40ff07
LP
2612static bool early_skip_setup_check(int argc, char *argv[]) {
2613 bool found_deserialize = false;
aa40ff07 2614
ff3a7019
ZJS
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. */
aa40ff07 2618
431733b8 2619 for (int i = 1; i < argc; i++)
aa40ff07
LP
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;
aa40ff07
LP
2624
2625 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2626}
2627
0e06a031
LP
2628static 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
60918275 2639int main(int argc, char *argv[]) {
5409c6fc
ZJS
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;
ddfa8b0b
LP
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! */
5409c6fc 2651 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false;
625e8690 2652 char *switch_root_dir = NULL, *switch_root_init = NULL;
9d76d730 2653 usec_t before_startup, after_startup;
625e8690 2654 static char systemd[] = "systemd";
625e8690
LP
2655 const char *shutdown_verb = NULL, *error_message = NULL;
2656 int r, retval = EXIT_FAILURE;
2657 Manager *m = NULL;
a16e1123 2658 FDSet *fds = NULL;
27b14a22 2659
61b9769b 2660 assert_se(argc > 0 && !isempty(argv[0]));
cf3095ac 2661
d72a8f10 2662 /* SysV compatibility: redirect init → telinit */
6808a0bc 2663 redirect_telinit(argc, argv);
2cb1a60d 2664
d72a8f10 2665 /* Take timestamps early on */
c3a170f3
HH
2666 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2667 dual_timestamp_get(&userspace_timestamp);
2668
d72a8f10 2669 /* Figure out whether we need to do initialize the system, or if we already did that because we are
ff3a7019 2670 * reexecuting. */
aa40ff07 2671 skip_setup = early_skip_setup_check(argc, argv);
d03bc1b8 2672
ff3a7019
ZJS
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. */
f3b6a3ed 2676 program_invocation_short_name = systemd;
eee8b7ab 2677 (void) prctl(PR_SET_NAME, systemd);
5d6b1584 2678
d72a8f10 2679 /* Save the original command line */
36fea155 2680 save_argc_argv(argc, argv);
f3b6a3ed 2681
0e06a031
LP
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 }
a5cede8c 2689
6fdb8de4 2690 /* Make sure that if the user says "syslog" we actually log to the journal. */
c1dc6153 2691 log_set_upgrade_syslog_to_journal(true);
bbe63281 2692
df0ff127 2693 if (getpid_cached() == 1) {
b5752d23
LP
2694 /* When we run as PID 1 force system mode */
2695 arg_system = true;
2696
48a601fe 2697 /* Disable the umask logic */
90dc8c2e
MG
2698 umask(0);
2699
ff3a7019
ZJS
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). */
d075092f
LP
2702 log_set_prohibit_ipc(true);
2703
ff3a7019
ZJS
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. */
48a601fe 2708 log_set_always_reopen_console(true);
48a601fe 2709
92890452 2710 if (detect_container() <= 0) {
4f8d551f 2711
92890452 2712 /* Running outside of a container as PID 1 */
92890452
LP
2713 log_set_target(LOG_TARGET_KMSG);
2714 log_open();
a866073d 2715
92890452
LP
2716 if (in_initrd())
2717 initrd_timestamp = userspace_timestamp;
c3ba6250 2718
92890452
LP
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
0a2eef1e
LP
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
6123dfaa
ZJS
2731 disable_printk_ratelimit();
2732
92890452
LP
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;
d723cd65 2740 }
eee8b7ab 2741
92890452 2742 if (mac_selinux_init() < 0) {
a9ba0e32 2743 error_message = "Failed to initialize SELinux support";
96694e99 2744 goto finish;
92890452 2745 }
0b3325e7 2746
92890452
LP
2747 if (!skip_setup)
2748 initialize_clock();
2749
ff3a7019
ZJS
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. */
92890452
LP
2754 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2755
2756 } else {
2757 /* Running inside a container, as PID 1 */
92890452
LP
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
45250e66 2764 /* clear the kernel timestamp, because we are in a container */
92890452 2765 kernel_timestamp = DUAL_TIMESTAMP_NULL;
cb6531be 2766 }
7948c4df 2767
92890452 2768 initialize_coredump(skip_setup);
a866073d 2769
92890452
LP
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 }
a866073d 2776
ff3a7019
ZJS
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. */
3a18b604 2779 log_show_color(colors_enabled());
92890452 2780
c76cf844
AK
2781 r = make_null_stdio();
2782 if (r < 0)
92890452 2783 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
f84f9974 2784
a132bef0 2785 /* Load the kernel modules early. */
2e75e2a8 2786 if (!skip_setup)
e921a00d 2787 (void) kmod_setup();
2e75e2a8 2788
3196e423 2789 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
f74349d8 2790 r = mount_setup(loaded_policy, skip_setup);
cb6531be
ZJS
2791 if (r < 0) {
2792 error_message = "Failed to mount API filesystems";
8efe3c01 2793 goto finish;
cb6531be 2794 }
c18ecf03
LP
2795
2796 /* The efivarfs is now mounted, let's read the random seed off it */
2797 (void) efi_take_random_seed();
209b2592
FB
2798
2799 /* Cache command-line options passed from EFI variables */
2800 if (!skip_setup)
2801 (void) cache_efi_options_variable();
3196e423
LP
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 }
0c85a4f3 2815 }
4ade7963 2816
a9fd4cd1
FB
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
4ade7963 2821 /* Reset all signal handlers. */
ce30c8dc 2822 (void) reset_all_signal_handlers();
9c274488 2823 (void) ignore_signals(SIGNALS_IGNORE);
078e4539 2824
ffe5c01e
FB
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";
f170852a 2830 goto finish;
ffe5c01e 2831 }
10c961b9 2832
b0d7c989
LP
2833 r = safety_checks();
2834 if (r < 0)
fe783b03 2835 goto finish;
fe783b03 2836
5c08257b 2837 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES, ACTION_BUS_INTROSPECT))
384c2c32 2838 pager_open(arg_pager_flags);
b0d7c989
LP
2839
2840 if (arg_action != ACTION_RUN)
74e7579c 2841 skip_setup = true;
b87c2aa6 2842
fa0f4d8a 2843 if (arg_action == ACTION_HELP) {
37ec0fdd 2844 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
f170852a 2845 goto finish;
9ba0bc4e
ZJS
2846 } else if (arg_action == ACTION_VERSION) {
2847 retval = version();
2848 goto finish;
fa0f4d8a 2849 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
e537352b 2850 unit_dump_config_items(stdout);
22f4096c 2851 retval = EXIT_SUCCESS;
e537352b 2852 goto finish;
bbc1acab
YW
2853 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
2854 dump_bus_properties(stdout);
2855 retval = EXIT_SUCCESS;
2856 goto finish;
5c08257b
ZJS
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;
f170852a
LP
2861 }
2862
4c701096 2863 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
f170852a 2864
5a2e0c62
LP
2865 /* Move out of the way, so that we won't block unmounts */
2866 assert_se(chdir("/") == 0);
2867
dea374e8 2868 if (arg_action == ACTION_RUN) {
d247f232
LP
2869 if (!skip_setup) {
2870 /* Apply the systemd.clock_usec= kernel command line switch */
45250e66 2871 apply_clock_update();
a70c72a0 2872
d247f232
LP
2873 /* Apply random seed from kernel command line */
2874 cmdline_take_random_seed();
2875 }
2876
c6885f5f
FB
2877 /* A core pattern might have been specified via the cmdline. */
2878 initialize_core_pattern(skip_setup);
2879
efeb853f 2880 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
a70c72a0
LP
2881 log_close();
2882
2883 /* Remember open file descriptors for later deserialization */
efeb853f
LP
2884 r = collect_fds(&fds, &error_message);
2885 if (r < 0)
dea374e8 2886 goto finish;
a16e1123 2887
2e51b31c
LP
2888 /* Give up any control of the console, but make sure its initialized. */
2889 setup_console_terminal(skip_setup);
56d96fc0 2890
a70c72a0
LP
2891 /* Open the logging devices, if possible and necessary */
2892 log_open();
56d96fc0 2893 }
4ade7963 2894
31aef7ff 2895 log_execution_mode(&first_boot);
a5dab5ce 2896
2d776038 2897 r = initialize_runtime(skip_setup,
3023f2fe 2898 first_boot,
2d776038
LP
2899 &saved_rlimit_nofile,
2900 &saved_rlimit_memlock,
2901 &error_message);
2902 if (r < 0)
2903 goto finish;
4096d6f5 2904
b380b643 2905 r = manager_new(arg_system ? LOOKUP_SCOPE_SYSTEM : LOOKUP_SCOPE_USER,
e0a3da1f
ZJS
2906 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
2907 &m);
e96d6be7 2908 if (r < 0) {
da927ba9 2909 log_emergency_errno(r, "Failed to allocate manager object: %m");
cb6531be 2910 error_message = "Failed to allocate manager object";
60918275
LP
2911 goto finish;
2912 }
2913
9f9f0342
LP
2914 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
2915 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
2916 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
d4ee7bd8
YW
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;
9e58ff9c 2919
85cb4151 2920 set_manager_defaults(m);
7b46fc6a 2921 set_manager_settings(m);
fd130612 2922 manager_set_first_boot(m, first_boot);
27d340c7 2923
bf4df7c3 2924 /* Remember whether we should queue the default job */
d3b1c508 2925 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 2926
9d76d730
LP
2927 before_startup = now(CLOCK_MONOTONIC);
2928
2a7cf953 2929 r = manager_startup(m, arg_serialization, fds, /* root= */ NULL);
58f88d92 2930 if (r < 0) {
cefb3eda 2931 error_message = "Failed to start up manager";
58f88d92
ZJS
2932 goto finish;
2933 }
a16e1123 2934
6acca5fc 2935 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2feceb5e 2936 fds = fdset_free(fds);
74ca738f 2937 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
2938
2939 if (queue_default_job) {
6acca5fc 2940 r = do_queue_default_job(m, &error_message);
718db961 2941 if (r < 0)
37d88da7 2942 goto finish;
6acca5fc 2943 }
ab17a050 2944
6acca5fc 2945 after_startup = now(CLOCK_MONOTONIC);
60918275 2946
6acca5fc
LP
2947 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2948 "Loaded units and determined initial transaction in %s.",
5291f26d 2949 FORMAT_TIMESPAN(after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 2950
6acca5fc 2951 if (arg_action == ACTION_TEST) {
2a341bb9 2952 manager_test_summary(m);
6acca5fc
LP
2953 retval = EXIT_SUCCESS;
2954 goto finish;
e965d56d 2955 }
d46de8a1 2956
5409c6fc
ZJS
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));
f170852a 2974
60918275 2975finish:
b87c2aa6
ZJS
2976 pager_close();
2977
92890452 2978 if (m) {
986935cf
FB
2979 arg_reboot_watchdog = manager_get_watchdog(m, WATCHDOG_REBOOT);
2980 arg_kexec_watchdog = manager_get_watchdog(m, WATCHDOG_KEXEC);
92890452
LP
2981 m = manager_free(m);
2982 }
60918275 2983
cc56fafe 2984 mac_selinux_finish();
b2bb3dbe 2985
5409c6fc 2986 if (IN_SET(r, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT))
1e3eee8c
ZJS
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 */
a16e1123 2995
74ca738f 2996 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2997 fds = fdset_free(fds);
a16e1123 2998
0e06a031
LP
2999 saved_env = strv_free(saved_env);
3000
349cc4a5 3001#if HAVE_VALGRIND_VALGRIND_H
54b434b1
LP
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. */
8a2c1fbf
EJ
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);
7d9eea2b 3011 reset_arguments();
27fe58b7 3012 return retval;
8a2c1fbf 3013 }
54b434b1
LP
3014#endif
3015
7e11a95e
EV
3016#if HAS_FEATURE_ADDRESS_SANITIZER
3017 __lsan_do_leak_check();
3018#endif
3019
5409c6fc
ZJS
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) {
7eb35049 3023 r = become_shutdown(shutdown_verb, retval);
4a36297c 3024 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
9b9881d7 3025 error_message = "Failed to execute shutdown binary";
b9080b03
FF
3026 }
3027
8a2c1fbf
EJ
3028 watchdog_free_device();
3029 arg_watchdog_device = mfree(arg_watchdog_device);
3030
df0ff127 3031 if (getpid_cached() == 1) {
cb6531be
ZJS
3032 if (error_message)
3033 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 3034 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
bb259772
LP
3035 "%s.", error_message);
3036 freeze_or_exit_or_reboot();
cb6531be 3037 }
c3b3c274 3038
7d9eea2b 3039 reset_arguments();
60918275
LP
3040 return retval;
3041}