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