]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
socket: rename ffs_xyz to usbffs_xyz
[thirdparty/systemd.git] / src / core / main.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
60918275 2
a7334b09
LP
3/***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 16 Lesser General Public License for more details.
a7334b09 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
60918275 22#include <errno.h>
3dfc9763 23#include <fcntl.h>
f170852a 24#include <getopt.h>
97c4f35c 25#include <signal.h>
3dfc9763
LP
26#include <stdio.h>
27#include <string.h>
664f88a7 28#include <sys/mount.h>
3dfc9763
LP
29#include <sys/prctl.h>
30#include <sys/stat.h>
31#include <unistd.h>
b64a3d86
LP
32#ifdef HAVE_SECCOMP
33#include <seccomp.h>
34#endif
3dfc9763
LP
35#ifdef HAVE_VALGRIND_VALGRIND_H
36#include <valgrind/valgrind.h>
37#endif
54b434b1 38
718db961 39#include "sd-daemon.h"
718db961 40#include "sd-bus.h"
3dfc9763 41
d9d93745 42#include "architecture.h"
3dfc9763
LP
43#include "build.h"
44#include "bus-error.h"
45#include "bus-util.h"
ec8927ca 46#include "capability.h"
24efb112 47#include "clock-util.h"
3dfc9763
LP
48#include "conf-parser.h"
49#include "dbus-manager.h"
50#include "def.h"
51#include "env-util.h"
52#include "fdset.h"
718db961 53#include "fileio.h"
24882e06 54#include "formats-util.h"
3dfc9763
LP
55#include "hostname-setup.h"
56#include "ima-setup.h"
57#include "killall.h"
58#include "kmod-setup.h"
d7b8eec7 59#include "load-fragment.h"
3dfc9763 60#include "log.h"
b6e66135 61#include "loopback-setup.h"
b6e66135 62#include "machine-id-setup.h"
3dfc9763
LP
63#include "manager.h"
64#include "missing.h"
65#include "mount-setup.h"
66#include "pager.h"
67#include "process-util.h"
b6e66135 68#include "selinux-setup.h"
3dfc9763
LP
69#include "selinux-util.h"
70#include "signal-util.h"
ffbd2c4d 71#include "smack-setup.h"
3dfc9763
LP
72#include "special.h"
73#include "strv.h"
74#include "switch-root.h"
75#include "terminal-util.h"
76#include "virt.h"
77#include "watchdog.h"
b6e66135 78
f170852a
LP
79static enum {
80 ACTION_RUN,
e965d56d 81 ACTION_HELP,
9ba0bc4e 82 ACTION_VERSION,
e537352b 83 ACTION_TEST,
4288f619
LP
84 ACTION_DUMP_CONFIGURATION_ITEMS,
85 ACTION_DONE
fa0f4d8a 86} arg_action = ACTION_RUN;
fa0f4d8a 87static char *arg_default_unit = NULL;
b2c23da8 88static ManagerRunningAs arg_running_as = _MANAGER_RUNNING_AS_INVALID;
fa0f4d8a
LP
89static bool arg_dump_core = true;
90static bool arg_crash_shell = false;
91static int arg_crash_chvt = -1;
92static bool arg_confirm_spawn = false;
b6e2f329 93static ShowStatus arg_show_status = _SHOW_STATUS_UNSET;
bf4df7c3 94static bool arg_switched_root = false;
b87c2aa6 95static int arg_no_pager = -1;
0c85a4f3 96static char ***arg_join_controllers = NULL;
706343f4 97static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
0a494f1f 98static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
1f19a534
OS
99static usec_t arg_default_restart_usec = DEFAULT_RESTART_USEC;
100static usec_t arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
101static usec_t arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
3f41e1e5
LN
102static usec_t arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
103static unsigned arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
e96d6be7
LP
104static usec_t arg_runtime_watchdog = 0;
105static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
97d0e5f8 106static char **arg_default_environment = NULL;
517d56b1 107static struct rlimit *arg_default_rlimit[_RLIMIT_MAX] = {};
ec8927ca 108static uint64_t arg_capability_bounding_set_drop = 0;
3a43da28 109static nsec_t arg_timer_slack_nsec = NSEC_INFINITY;
bd8f585b 110static usec_t arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
d3b1c508
LP
111static Set* arg_syscall_archs = NULL;
112static FILE* arg_serialization = NULL;
085afe36
LP
113static bool arg_default_cpu_accounting = false;
114static bool arg_default_blockio_accounting = false;
115static bool arg_default_memory_accounting = false;
03a7b521 116static bool arg_default_tasks_accounting = false;
4fc935ca 117
b87c2aa6
ZJS
118static void pager_open_if_enabled(void) {
119
120 if (arg_no_pager <= 0)
121 return;
122
123 pager_open(false);
124}
125
919ce0b7 126noreturn static void crash(int sig) {
97c4f35c 127
abb26902
LP
128 if (getpid() != 1)
129 /* Pass this on immediately, if this is not PID 1 */
92ca4cac 130 (void) raise(sig);
abb26902 131 else if (!arg_dump_core)
4104970e 132 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig));
97c4f35c 133 else {
b92bea5d 134 struct sigaction sa = {
189d5bac 135 .sa_handler = nop_signal_handler,
b92bea5d
ZJS
136 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
137 };
97c4f35c
LP
138 pid_t pid;
139
6f5e3f35 140 /* We want to wait for the core process, hence let's enable SIGCHLD */
92ca4cac 141 (void) sigaction(SIGCHLD, &sa, NULL);
6f5e3f35 142
ee05e779 143 pid = raw_clone(SIGCHLD, NULL);
e62d8c39 144 if (pid < 0)
56f64d95 145 log_emergency_errno(errno, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig));
97c4f35c 146 else if (pid == 0) {
92ca4cac
LP
147 struct rlimit rl = {
148 .rlim_cur = RLIM_INFINITY,
149 .rlim_max = RLIM_INFINITY,
150 };
97c4f35c
LP
151
152 /* Enable default signal handler for core dump */
92ca4cac
LP
153 sa = (struct sigaction) {
154 .sa_handler = SIG_DFL,
155 };
156 (void) sigaction(sig, &sa, NULL);
97c4f35c
LP
157
158 /* Don't limit the core dump size */
92ca4cac 159 (void) setrlimit(RLIMIT_CORE, &rl);
97c4f35c
LP
160
161 /* Just to be sure... */
e62d9b81 162 (void) chdir("/");
97c4f35c
LP
163
164 /* Raise the signal again */
ee05e779 165 pid = raw_getpid();
92ca4cac 166 (void) kill(pid, sig); /* raise() would kill the parent */
97c4f35c
LP
167
168 assert_not_reached("We shouldn't be here...");
92ca4cac 169 _exit(EXIT_FAILURE);
4fc935ca 170 } else {
8e12a6ae
LP
171 siginfo_t status;
172 int r;
4fc935ca
LP
173
174 /* Order things nicely. */
e62d8c39
ZJS
175 r = wait_for_terminate(pid, &status);
176 if (r < 0)
da927ba9 177 log_emergency_errno(r, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig));
8e12a6ae 178 else if (status.si_code != CLD_DUMPED)
ee05e779
ZJS
179 log_emergency("Caught <%s>, core dump failed (child "PID_FMT", code=%s, status=%i/%s).",
180 signal_to_string(sig),
181 pid, sigchld_code_to_string(status.si_code),
182 status.si_status,
183 strna(status.si_code == CLD_EXITED
184 ? exit_status_to_string(status.si_status, EXIT_STATUS_FULL)
185 : signal_to_string(status.si_status)));
4fc935ca 186 else
4104970e 187 log_emergency("Caught <%s>, dumped core as pid "PID_FMT".", signal_to_string(sig), pid);
97c4f35c
LP
188 }
189 }
190
fa0f4d8a 191 if (arg_crash_chvt)
92ca4cac 192 (void) chvt(arg_crash_chvt);
601f6a1e 193
fa0f4d8a 194 if (arg_crash_shell) {
b92bea5d
ZJS
195 struct sigaction sa = {
196 .sa_handler = SIG_IGN,
197 .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
198 };
6f5e3f35 199 pid_t pid;
8c43883a 200
4fc935ca 201 log_info("Executing crash shell in 10s...");
92ca4cac 202 (void) sleep(10);
4fc935ca 203
6f5e3f35 204 /* Let the kernel reap children for us */
92ca4cac 205 (void) sigaction(SIGCHLD, &sa, NULL);
8c43883a 206
ee05e779 207 pid = raw_clone(SIGCHLD, NULL);
cd3bd60a 208 if (pid < 0)
56f64d95 209 log_emergency_errno(errno, "Failed to fork off crash shell: %m");
6f5e3f35 210 else if (pid == 0) {
92ca4cac
LP
211 (void) make_console_stdio();
212 (void) execle("/bin/sh", "/bin/sh", NULL, environ);
6f5e3f35 213
ee05e779 214 log_emergency_errno(errno, "execle() failed: %m");
92ca4cac 215 _exit(EXIT_FAILURE);
ee05e779
ZJS
216 } else
217 log_info("Successfully spawned crash shell as PID "PID_FMT".", pid);
4fc935ca
LP
218 }
219
4104970e 220 log_emergency("Freezing execution.");
97c4f35c
LP
221 freeze();
222}
223
224static void install_crash_handler(void) {
297d563d 225 static const struct sigaction sa = {
b92bea5d 226 .sa_handler = crash,
297d563d 227 .sa_flags = SA_NODEFER, /* So that we can raise the signal again from the signal handler */
b92bea5d 228 };
297d563d 229 int r;
97c4f35c 230
297d563d
LP
231 /* We ignore the return value here, since, we don't mind if we
232 * cannot set up a crash handler */
233 r = sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
234 if (r < 0)
235 log_debug_errno(r, "I had trouble setting up the crash handler, ignoring: %m");
97c4f35c 236}
f170852a 237
56d96fc0
LP
238static int console_setup(void) {
239 _cleanup_close_ int tty_fd = -1;
240 int r;
80876c20 241
512947d4 242 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
23bbb0de
MS
243 if (tty_fd < 0)
244 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
80876c20 245
56d96fc0
LP
246 /* We don't want to force text mode. plymouth may be showing
247 * pictures already from initrd. */
512947d4 248 r = reset_terminal_fd(tty_fd, false);
23bbb0de
MS
249 if (r < 0)
250 return log_error_errno(r, "Failed to reset /dev/console: %m");
843d2643 251
56d96fc0 252 return 0;
80876c20
LP
253}
254
059cb385 255static int parse_proc_cmdline_item(const char *key, const char *value) {
f170852a
LP
256
257 static const char * const rlmap[] = {
ed370f5d 258 "emergency", SPECIAL_EMERGENCY_TARGET,
099663ff 259 "-b", SPECIAL_EMERGENCY_TARGET,
5329ab10 260 "rescue", SPECIAL_RESCUE_TARGET,
ed370f5d
LP
261 "single", SPECIAL_RESCUE_TARGET,
262 "-s", SPECIAL_RESCUE_TARGET,
263 "s", SPECIAL_RESCUE_TARGET,
264 "S", SPECIAL_RESCUE_TARGET,
265 "1", SPECIAL_RESCUE_TARGET,
d5d8429a
LP
266 "2", SPECIAL_MULTI_USER_TARGET,
267 "3", SPECIAL_MULTI_USER_TARGET,
268 "4", SPECIAL_MULTI_USER_TARGET,
269 "5", SPECIAL_GRAPHICAL_TARGET,
f170852a 270 };
059cb385 271 int r;
f170852a 272
059cb385 273 assert(key);
5192bd19 274
059cb385 275 if (streq(key, "systemd.unit") && value) {
bf4df7c3
LP
276
277 if (!in_initrd())
e6e242ad 278 return free_and_strdup(&arg_default_unit, value);
bf4df7c3 279
059cb385 280 } else if (streq(key, "rd.systemd.unit") && value) {
bf4df7c3 281
ca05941b 282 if (in_initrd())
e6e242ad 283 return free_and_strdup(&arg_default_unit, value);
f170852a 284
059cb385 285 } else if (streq(key, "systemd.dump_core") && value) {
4fc935ca 286
059cb385 287 r = parse_boolean(value);
fb472900 288 if (r < 0)
059cb385 289 log_warning("Failed to parse dump core switch %s. Ignoring.", value);
4fc935ca 290 else
fa0f4d8a 291 arg_dump_core = r;
4fc935ca 292
059cb385 293 } else if (streq(key, "systemd.crash_shell") && value) {
4fc935ca 294
059cb385 295 r = parse_boolean(value);
fb472900 296 if (r < 0)
059cb385 297 log_warning("Failed to parse crash shell switch %s. Ignoring.", value);
4fc935ca 298 else
fa0f4d8a 299 arg_crash_shell = r;
5e7ee61c 300
059cb385 301 } else if (streq(key, "systemd.crash_chvt") && value) {
5e7ee61c 302
059cb385
LP
303 if (safe_atoi(value, &r) < 0)
304 log_warning("Failed to parse crash chvt switch %s. Ignoring.", value);
5e7ee61c 305 else
059cb385 306 arg_crash_chvt = r;
5e7ee61c 307
059cb385 308 } else if (streq(key, "systemd.confirm_spawn") && value) {
601f6a1e 309
059cb385
LP
310 r = parse_boolean(value);
311 if (r < 0)
312 log_warning("Failed to parse confirm spawn switch %s. Ignoring.", value);
601f6a1e 313 else
059cb385 314 arg_confirm_spawn = r;
601f6a1e 315
059cb385 316 } else if (streq(key, "systemd.show_status") && value) {
9e58ff9c 317
059cb385 318 r = parse_show_status(value, &arg_show_status);
d450b6f2 319 if (r < 0)
059cb385
LP
320 log_warning("Failed to parse show status switch %s. Ignoring.", value);
321
322 } else if (streq(key, "systemd.default_standard_output") && value) {
0a494f1f 323
059cb385 324 r = exec_output_from_string(value);
fb472900 325 if (r < 0)
059cb385 326 log_warning("Failed to parse default standard output switch %s. Ignoring.", value);
0a494f1f
LP
327 else
328 arg_default_std_output = r;
0a494f1f 329
059cb385
LP
330 } else if (streq(key, "systemd.default_standard_error") && value) {
331
332 r = exec_output_from_string(value);
fb472900 333 if (r < 0)
059cb385 334 log_warning("Failed to parse default standard error switch %s. Ignoring.", value);
0a494f1f
LP
335 else
336 arg_default_std_error = r;
9e7c5357 337
059cb385
LP
338 } else if (streq(key, "systemd.setenv") && value) {
339
340 if (env_assignment_is_valid(value)) {
e21fea24
KS
341 char **env;
342
059cb385 343 env = strv_env_set(arg_default_environment, value);
e21fea24
KS
344 if (env)
345 arg_default_environment = env;
346 else
279d3c9c 347 log_warning_errno(ENOMEM, "Setting environment variable '%s' failed, ignoring: %m", value);
e21fea24 348 } else
059cb385 349 log_warning("Environment variable name '%s' is not valid. Ignoring.", value);
9e58ff9c 350
059cb385 351 } else if (streq(key, "quiet") && !value) {
d7b15e0a 352
b6e2f329 353 if (arg_show_status == _SHOW_STATUS_UNSET)
d450b6f2 354 arg_show_status = SHOW_STATUS_AUTO;
059cb385
LP
355
356 } else if (streq(key, "debug") && !value) {
d7b15e0a 357
1de1c9c3
LP
358 /* Note that log_parse_environment() handles 'debug'
359 * too, and sets the log level to LOG_DEBUG. */
d7b15e0a 360
75f86906 361 if (detect_container() > 0)
b2103dcc 362 log_set_target(LOG_TARGET_CONSOLE);
059cb385
LP
363
364 } else if (!in_initrd() && !value) {
f170852a
LP
365 unsigned i;
366
367 /* SysV compatibility */
f170852a 368 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
059cb385 369 if (streq(key, rlmap[i]))
e6e242ad 370 return free_and_strdup(&arg_default_unit, rlmap[i+1]);
f170852a
LP
371 }
372
373 return 0;
374}
375
e8e581bf
ZJS
376#define DEFINE_SETTER(name, func, descr) \
377 static int name(const char *unit, \
378 const char *filename, \
379 unsigned line, \
380 const char *section, \
71a61510 381 unsigned section_line, \
e8e581bf
ZJS
382 const char *lvalue, \
383 int ltype, \
384 const char *rvalue, \
385 void *data, \
386 void *userdata) { \
387 \
388 int r; \
389 \
390 assert(filename); \
391 assert(lvalue); \
392 assert(rvalue); \
393 \
394 r = func(rvalue); \
395 if (r < 0) \
d1cefe0a
LP
396 log_syntax(unit, LOG_ERR, filename, line, r, \
397 "Invalid " descr "'%s': %m", \
398 rvalue); \
e8e581bf
ZJS
399 \
400 return 0; \
401 }
487393e9 402
e8e581bf
ZJS
403DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level")
404DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target")
405DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" )
406DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location")
487393e9 407
4d7213b2
LP
408static int config_parse_cpu_affinity2(
409 const char *unit,
410 const char *filename,
411 unsigned line,
412 const char *section,
413 unsigned section_line,
414 const char *lvalue,
415 int ltype,
416 const char *rvalue,
417 void *data,
418 void *userdata) {
487393e9 419
4b40bc38 420 _cleanup_cpu_free_ cpu_set_t *c = NULL;
f5c72b73 421 int ncpus;
487393e9 422
f5c72b73 423 ncpus = parse_cpu_set(rvalue, &c, unit, filename, line, lvalue);
487393e9 424
f5c72b73
FB
425 if (ncpus < 0)
426 return ncpus;
487393e9 427
f5c72b73
FB
428 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
429 log_warning("Failed to set CPU affinity: %m");
487393e9 430
487393e9
LP
431 return 0;
432}
433
4d7213b2
LP
434static int config_parse_show_status(
435 const char* unit,
436 const char *filename,
437 unsigned line,
438 const char *section,
439 unsigned section_line,
440 const char *lvalue,
441 int ltype,
442 const char *rvalue,
443 void *data,
444 void *userdata) {
445
446 int k;
447 ShowStatus *b = data;
448
449 assert(filename);
450 assert(lvalue);
451 assert(rvalue);
452 assert(data);
453
454 k = parse_show_status(rvalue, b);
455 if (k < 0) {
456 log_syntax(unit, LOG_ERR, filename, line, -k,
457 "Failed to parse show status setting, ignoring: %s", rvalue);
458 return 0;
459 }
460
461 return 0;
462}
463
e8e581bf
ZJS
464static int config_parse_join_controllers(const char *unit,
465 const char *filename,
466 unsigned line,
467 const char *section,
71a61510 468 unsigned section_line,
e8e581bf
ZJS
469 const char *lvalue,
470 int ltype,
471 const char *rvalue,
472 void *data,
473 void *userdata) {
0c85a4f3 474
3875c85b 475 const char *whole_rvalue = rvalue;
0c85a4f3 476 unsigned n = 0;
0c85a4f3
LP
477
478 assert(filename);
479 assert(lvalue);
480 assert(rvalue);
481
fe382237 482 arg_join_controllers = strv_free_free(arg_join_controllers);
0c85a4f3 483
d4ebeb4f
FB
484 for (;;) {
485 _cleanup_free_ char *word = NULL;
486 char **l;
487 int r;
0c85a4f3 488
d4ebeb4f 489 r = extract_first_word(&rvalue, &word, WHITESPACE, EXTRACT_QUOTES);
3875c85b
FB
490 if (r < 0) {
491 log_syntax(unit, LOG_ERR, filename, line, r, "Invalid value for %s: %s", lvalue, whole_rvalue);
d4ebeb4f 492 return r;
3875c85b 493 }
d4ebeb4f
FB
494 if (r == 0)
495 break;
0c85a4f3 496
d4ebeb4f 497 l = strv_split(word, ",");
1592ec21 498 if (!l)
aa8aeac0 499 return log_oom();
0c85a4f3
LP
500 strv_uniq(l);
501
502 if (strv_length(l) <= 1) {
503 strv_free(l);
504 continue;
505 }
506
507 if (!arg_join_controllers) {
508 arg_join_controllers = new(char**, 2);
509 if (!arg_join_controllers) {
510 strv_free(l);
14212119 511 return log_oom();
0c85a4f3
LP
512 }
513
514 arg_join_controllers[0] = l;
515 arg_join_controllers[1] = NULL;
516
517 n = 1;
518 } else {
519 char ***a;
520 char ***t;
521
522 t = new0(char**, n+2);
523 if (!t) {
524 strv_free(l);
14212119 525 return log_oom();
0c85a4f3
LP
526 }
527
528 n = 0;
529
530 for (a = arg_join_controllers; *a; a++) {
531
532 if (strv_overlap(*a, l)) {
e3e45d4f 533 if (strv_extend_strv(&l, *a) < 0) {
0c85a4f3
LP
534 strv_free(l);
535 strv_free_free(t);
14212119 536 return log_oom();
0c85a4f3
LP
537 }
538
0c85a4f3
LP
539 } else {
540 char **c;
541
542 c = strv_copy(*a);
543 if (!c) {
544 strv_free(l);
545 strv_free_free(t);
14212119 546 return log_oom();
0c85a4f3
LP
547 }
548
549 t[n++] = c;
550 }
551 }
552
553 t[n++] = strv_uniq(l);
554
555 strv_free_free(arg_join_controllers);
556 arg_join_controllers = t;
557 }
558 }
d4ebeb4f 559 if (!isempty(rvalue))
b2fadec6
ZJS
560 log_syntax(unit, LOG_ERR, filename, line, EINVAL,
561 "Trailing garbage, ignoring.");
0c85a4f3
LP
562
563 return 0;
564}
565
487393e9
LP
566static int parse_config_file(void) {
567
f975e971 568 const ConfigTableItem items[] = {
d3b1c508
LP
569 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
570 { "Manager", "LogTarget", config_parse_target, 0, NULL },
571 { "Manager", "LogColor", config_parse_color, 0, NULL },
572 { "Manager", "LogLocation", config_parse_location, 0, NULL },
573 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
574 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
575 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
576 { "Manager", "CrashChVT", config_parse_int, 0, &arg_crash_chvt },
577 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
578 { "Manager", "JoinControllers", config_parse_join_controllers, 0, &arg_join_controllers },
579 { "Manager", "RuntimeWatchdogSec", config_parse_sec, 0, &arg_runtime_watchdog },
580 { "Manager", "ShutdownWatchdogSec", config_parse_sec, 0, &arg_shutdown_watchdog },
581 { "Manager", "CapabilityBoundingSet", config_parse_bounding_set, 0, &arg_capability_bounding_set_drop },
89fffa27 582#ifdef HAVE_SECCOMP
d3b1c508 583 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
89fffa27 584#endif
d3b1c508 585 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
bd8f585b 586 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_default_timer_accuracy_usec },
d3b1c508
LP
587 { "Manager", "DefaultStandardOutput", config_parse_output, 0, &arg_default_std_output },
588 { "Manager", "DefaultStandardError", config_parse_output, 0, &arg_default_std_error },
589 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_default_timeout_start_usec },
590 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_default_timeout_stop_usec },
591 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_default_restart_usec },
592 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_default_start_limit_interval },
593 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_default_start_limit_burst },
594 { "Manager", "DefaultEnvironment", config_parse_environ, 0, &arg_default_environment },
595 { "Manager", "DefaultLimitCPU", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_CPU] },
596 { "Manager", "DefaultLimitFSIZE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_FSIZE] },
597 { "Manager", "DefaultLimitDATA", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_DATA] },
598 { "Manager", "DefaultLimitSTACK", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_STACK] },
599 { "Manager", "DefaultLimitCORE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_CORE] },
600 { "Manager", "DefaultLimitRSS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RSS] },
601 { "Manager", "DefaultLimitNOFILE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NOFILE] },
602 { "Manager", "DefaultLimitAS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_AS] },
603 { "Manager", "DefaultLimitNPROC", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NPROC] },
604 { "Manager", "DefaultLimitMEMLOCK", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_MEMLOCK] },
605 { "Manager", "DefaultLimitLOCKS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_LOCKS] },
606 { "Manager", "DefaultLimitSIGPENDING", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_SIGPENDING] },
607 { "Manager", "DefaultLimitMSGQUEUE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_MSGQUEUE] },
608 { "Manager", "DefaultLimitNICE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NICE] },
609 { "Manager", "DefaultLimitRTPRIO", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RTPRIO] },
610 { "Manager", "DefaultLimitRTTIME", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RTTIME] },
085afe36
LP
611 { "Manager", "DefaultCPUAccounting", config_parse_bool, 0, &arg_default_cpu_accounting },
612 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_default_blockio_accounting },
613 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_default_memory_accounting },
03a7b521 614 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_default_tasks_accounting },
d3b1c508 615 {}
487393e9
LP
616 };
617
1b907b5c 618 const char *fn, *conf_dirs_nulstr;
487393e9 619
b2c23da8
LP
620 fn = arg_running_as == MANAGER_SYSTEM ? PKGSYSCONFDIR "/system.conf" : PKGSYSCONFDIR "/user.conf";
621 conf_dirs_nulstr = arg_running_as == MANAGER_SYSTEM ? CONF_DIRS_NULSTR("systemd/system.conf") : CONF_DIRS_NULSTR("systemd/user.conf");
1b907b5c
JT
622 config_parse_many(fn, conf_dirs_nulstr, "Manager\0",
623 config_item_table_lookup, items, false, NULL);
487393e9 624
487393e9
LP
625 return 0;
626}
627
06af2a04
TB
628static void manager_set_defaults(Manager *m) {
629
630 assert(m);
631
632 m->default_timer_accuracy_usec = arg_default_timer_accuracy_usec;
633 m->default_std_output = arg_default_std_output;
634 m->default_std_error = arg_default_std_error;
635 m->default_timeout_start_usec = arg_default_timeout_start_usec;
636 m->default_timeout_stop_usec = arg_default_timeout_stop_usec;
637 m->default_restart_usec = arg_default_restart_usec;
638 m->default_start_limit_interval = arg_default_start_limit_interval;
639 m->default_start_limit_burst = arg_default_start_limit_burst;
640 m->default_cpu_accounting = arg_default_cpu_accounting;
641 m->default_blockio_accounting = arg_default_blockio_accounting;
642 m->default_memory_accounting = arg_default_memory_accounting;
03a7b521 643 m->default_tasks_accounting = arg_default_tasks_accounting;
06af2a04
TB
644
645 manager_set_default_rlimits(m, arg_default_rlimit);
646 manager_environment_add(m, NULL, arg_default_environment);
647}
648
f170852a
LP
649static int parse_argv(int argc, char *argv[]) {
650
651 enum {
652 ARG_LOG_LEVEL = 0x100,
653 ARG_LOG_TARGET,
bbe63281
LP
654 ARG_LOG_COLOR,
655 ARG_LOG_LOCATION,
2f198e2f 656 ARG_UNIT,
edb9aaa8 657 ARG_SYSTEM,
af2d49f7 658 ARG_USER,
e537352b 659 ARG_TEST,
b87c2aa6 660 ARG_NO_PAGER,
9ba0bc4e 661 ARG_VERSION,
80876c20 662 ARG_DUMP_CONFIGURATION_ITEMS,
9e58ff9c
LP
663 ARG_DUMP_CORE,
664 ARG_CRASH_SHELL,
a16e1123 665 ARG_CONFIRM_SPAWN,
9e58ff9c 666 ARG_SHOW_STATUS,
4288f619 667 ARG_DESERIALIZE,
2660882b 668 ARG_SWITCHED_ROOT,
0a494f1f
LP
669 ARG_DEFAULT_STD_OUTPUT,
670 ARG_DEFAULT_STD_ERROR
f170852a
LP
671 };
672
673 static const struct option options[] = {
a16e1123
LP
674 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
675 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
bbe63281
LP
676 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
677 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
2f198e2f 678 { "unit", required_argument, NULL, ARG_UNIT },
edb9aaa8 679 { "system", no_argument, NULL, ARG_SYSTEM },
af2d49f7 680 { "user", no_argument, NULL, ARG_USER },
a16e1123 681 { "test", no_argument, NULL, ARG_TEST },
b87c2aa6 682 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
a16e1123 683 { "help", no_argument, NULL, 'h' },
9ba0bc4e 684 { "version", no_argument, NULL, ARG_VERSION },
a16e1123 685 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
a5d87bf0
LP
686 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
687 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
688 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
6e98720f 689 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
a16e1123 690 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
2660882b 691 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
0a494f1f
LP
692 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
693 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
fb472900 694 {}
f170852a
LP
695 };
696
697 int c, r;
698
699 assert(argc >= 1);
700 assert(argv);
701
b770165a
LP
702 if (getpid() == 1)
703 opterr = 0;
704
099663ff 705 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
f170852a
LP
706
707 switch (c) {
708
709 case ARG_LOG_LEVEL:
fb472900
ZJS
710 r = log_set_max_level_from_string(optarg);
711 if (r < 0) {
f170852a
LP
712 log_error("Failed to parse log level %s.", optarg);
713 return r;
714 }
715
716 break;
717
718 case ARG_LOG_TARGET:
fb472900
ZJS
719 r = log_set_target_from_string(optarg);
720 if (r < 0) {
f170852a
LP
721 log_error("Failed to parse log target %s.", optarg);
722 return r;
723 }
724
725 break;
726
bbe63281
LP
727 case ARG_LOG_COLOR:
728
d0b170c8 729 if (optarg) {
fb472900
ZJS
730 r = log_show_color_from_string(optarg);
731 if (r < 0) {
d0b170c8
LP
732 log_error("Failed to parse log color setting %s.", optarg);
733 return r;
734 }
735 } else
736 log_show_color(true);
bbe63281
LP
737
738 break;
739
740 case ARG_LOG_LOCATION:
d0b170c8 741 if (optarg) {
fb472900
ZJS
742 r = log_show_location_from_string(optarg);
743 if (r < 0) {
d0b170c8
LP
744 log_error("Failed to parse log location setting %s.", optarg);
745 return r;
746 }
747 } else
748 log_show_location(true);
bbe63281
LP
749
750 break;
751
0a494f1f 752 case ARG_DEFAULT_STD_OUTPUT:
fb472900
ZJS
753 r = exec_output_from_string(optarg);
754 if (r < 0) {
0a494f1f
LP
755 log_error("Failed to parse default standard output setting %s.", optarg);
756 return r;
757 } else
758 arg_default_std_output = r;
759 break;
760
761 case ARG_DEFAULT_STD_ERROR:
fb472900
ZJS
762 r = exec_output_from_string(optarg);
763 if (r < 0) {
0a494f1f
LP
764 log_error("Failed to parse default standard error output setting %s.", optarg);
765 return r;
766 } else
767 arg_default_std_error = r;
768 break;
769
2f198e2f 770 case ARG_UNIT:
f170852a 771
e6e242ad 772 r = free_and_strdup(&arg_default_unit, optarg);
23bbb0de
MS
773 if (r < 0)
774 return log_error_errno(r, "Failed to set default unit %s: %m", optarg);
f170852a
LP
775
776 break;
777
edb9aaa8 778 case ARG_SYSTEM:
b2c23da8 779 arg_running_as = MANAGER_SYSTEM;
edb9aaa8 780 break;
a5dab5ce 781
af2d49f7 782 case ARG_USER:
b2c23da8 783 arg_running_as = MANAGER_USER;
a5dab5ce 784 break;
a5dab5ce 785
e965d56d 786 case ARG_TEST:
fa0f4d8a 787 arg_action = ACTION_TEST;
b87c2aa6
ZJS
788 if (arg_no_pager < 0)
789 arg_no_pager = true;
790 break;
791
792 case ARG_NO_PAGER:
793 arg_no_pager = true;
e965d56d
LP
794 break;
795
9ba0bc4e
ZJS
796 case ARG_VERSION:
797 arg_action = ACTION_VERSION;
798 break;
799
e537352b 800 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 801 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
802 break;
803
9e58ff9c 804 case ARG_DUMP_CORE:
a5d87bf0
LP
805 r = optarg ? parse_boolean(optarg) : 1;
806 if (r < 0) {
807 log_error("Failed to parse dump core boolean %s.", optarg);
808 return r;
809 }
810 arg_dump_core = r;
9e58ff9c
LP
811 break;
812
813 case ARG_CRASH_SHELL:
a5d87bf0
LP
814 r = optarg ? parse_boolean(optarg) : 1;
815 if (r < 0) {
816 log_error("Failed to parse crash shell boolean %s.", optarg);
817 return r;
818 }
819 arg_crash_shell = r;
9e58ff9c
LP
820 break;
821
80876c20 822 case ARG_CONFIRM_SPAWN:
a5d87bf0
LP
823 r = optarg ? parse_boolean(optarg) : 1;
824 if (r < 0) {
825 log_error("Failed to parse confirm spawn boolean %s.", optarg);
826 return r;
827 }
828 arg_confirm_spawn = r;
80876c20
LP
829 break;
830
9e58ff9c 831 case ARG_SHOW_STATUS:
d450b6f2
ZJS
832 if (optarg) {
833 r = parse_show_status(optarg, &arg_show_status);
834 if (r < 0) {
835 log_error("Failed to parse show status boolean %s.", optarg);
836 return r;
837 }
838 } else
839 arg_show_status = SHOW_STATUS_YES;
6e98720f 840 break;
a5d87bf0 841
a16e1123
LP
842 case ARG_DESERIALIZE: {
843 int fd;
844 FILE *f;
845
01e10de3
LP
846 r = safe_atoi(optarg, &fd);
847 if (r < 0 || fd < 0) {
a16e1123 848 log_error("Failed to parse deserialize option %s.", optarg);
01e10de3 849 return r < 0 ? r : -EINVAL;
a16e1123
LP
850 }
851
01e10de3
LP
852 fd_cloexec(fd, true);
853
854 f = fdopen(fd, "r");
4a62c710
MS
855 if (!f)
856 return log_error_errno(errno, "Failed to open serialization fd: %m");
a16e1123 857
74ca738f 858 safe_fclose(arg_serialization);
a16e1123 859
d3b1c508 860 arg_serialization = f;
a16e1123
LP
861
862 break;
863 }
864
2660882b 865 case ARG_SWITCHED_ROOT:
bf4df7c3 866 arg_switched_root = true;
d03bc1b8
HH
867 break;
868
f170852a 869 case 'h':
fa0f4d8a 870 arg_action = ACTION_HELP;
b87c2aa6
ZJS
871 if (arg_no_pager < 0)
872 arg_no_pager = true;
f170852a
LP
873 break;
874
1d2e23ab
LP
875 case 'D':
876 log_set_max_level(LOG_DEBUG);
877 break;
878
099663ff
LP
879 case 'b':
880 case 's':
881 case 'z':
882 /* Just to eat away the sysvinit kernel
883 * cmdline args without getopt() error
884 * messages that we'll parse in
885 * parse_proc_cmdline_word() or ignore. */
f170852a 886
099663ff 887 case '?':
601185b4 888 if (getpid() != 1)
099663ff 889 return -EINVAL;
601185b4
ZJS
890 else
891 return 0;
099663ff 892
601185b4
ZJS
893 default:
894 assert_not_reached("Unhandled option code.");
f170852a
LP
895 }
896
d821e6d6
LP
897 if (optind < argc && getpid() != 1) {
898 /* Hmm, when we aren't run as init system
899 * let's complain about excess arguments */
900
901 log_error("Excess arguments.");
902 return -EINVAL;
903 }
904
f170852a
LP
905 return 0;
906}
907
908static int help(void) {
909
2e33c433 910 printf("%s [OPTIONS...]\n\n"
af2d49f7 911 "Starts up and maintains the system or user services.\n\n"
e537352b 912 " -h --help Show this help\n"
e537352b 913 " --test Determine startup sequence, dump it and exit\n"
b87c2aa6 914 " --no-pager Do not pipe output into a pager\n"
80876c20 915 " --dump-configuration-items Dump understood unit configuration items\n"
9e58ff9c 916 " --unit=UNIT Set default unit\n"
edb9aaa8 917 " --system Run a system instance, even if PID != 1\n"
af2d49f7 918 " --user Run a user instance\n"
a5d87bf0
LP
919 " --dump-core[=0|1] Dump core on crash\n"
920 " --crash-shell[=0|1] Run shell on crash\n"
921 " --confirm-spawn[=0|1] Ask for confirmation when spawning processes\n"
6e98720f 922 " --show-status[=0|1] Show status updates on the console during bootup\n"
c1dc6153 923 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
9e58ff9c 924 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
2218198b 925 " --log-color[=0|1] Highlight important log messages\n"
0a494f1f
LP
926 " --log-location[=0|1] Include code location in log messages\n"
927 " --default-standard-output= Set default standard output for services\n"
928 " --default-standard-error= Set default standard error output for services\n",
5b6319dc 929 program_invocation_short_name);
f170852a
LP
930
931 return 0;
932}
933
b3680f49 934static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds, bool switching_root) {
48b90859
LP
935 _cleanup_fdset_free_ FDSet *fds = NULL;
936 _cleanup_fclose_ FILE *f = NULL;
a16e1123
LP
937 int r;
938
939 assert(m);
940 assert(_f);
941 assert(_fds);
942
6b78f9b4 943 r = manager_open_serialization(m, &f);
48b90859
LP
944 if (r < 0)
945 return log_error_errno(r, "Failed to create serialization file: %m");
a16e1123 946
71445ae7
LP
947 /* Make sure nothing is really destructed when we shut down */
948 m->n_reloading ++;
718db961 949 bus_manager_send_reloading(m, true);
71445ae7 950
6b78f9b4 951 fds = fdset_new();
48b90859
LP
952 if (!fds)
953 return log_oom();
a16e1123 954
b3680f49 955 r = manager_serialize(m, f, fds, switching_root);
48b90859
LP
956 if (r < 0)
957 return log_error_errno(r, "Failed to serialize state: %m");
a16e1123 958
48b90859
LP
959 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
960 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
a16e1123 961
6b78f9b4 962 r = fd_cloexec(fileno(f), false);
48b90859
LP
963 if (r < 0)
964 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
a16e1123 965
6b78f9b4 966 r = fdset_cloexec(fds, false);
48b90859
LP
967 if (r < 0)
968 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
a16e1123
LP
969
970 *_f = f;
971 *_fds = fds;
972
48b90859
LP
973 f = NULL;
974 fds = NULL;
a16e1123 975
48b90859 976 return 0;
a16e1123
LP
977}
978
4096d6f5
LP
979static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
980 struct rlimit nl;
981 int r;
982
983 assert(saved_rlimit);
984
985 /* Save the original RLIMIT_NOFILE so that we can reset it
986 * later when transitioning from the initrd to the main
987 * systemd or suchlike. */
4a62c710
MS
988 if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0)
989 return log_error_errno(errno, "Reading RLIMIT_NOFILE failed: %m");
4096d6f5
LP
990
991 /* Make sure forked processes get the default kernel setting */
992 if (!arg_default_rlimit[RLIMIT_NOFILE]) {
993 struct rlimit *rl;
994
995 rl = newdup(struct rlimit, saved_rlimit, 1);
996 if (!rl)
997 return log_oom();
998
999 arg_default_rlimit[RLIMIT_NOFILE] = rl;
1000 }
1001
1002 /* Bump up the resource limit for ourselves substantially */
1003 nl.rlim_cur = nl.rlim_max = 64*1024;
1004 r = setrlimit_closest(RLIMIT_NOFILE, &nl);
23bbb0de
MS
1005 if (r < 0)
1006 return log_error_errno(r, "Setting RLIMIT_NOFILE failed: %m");
4096d6f5
LP
1007
1008 return 0;
1009}
1010
6ee5bbf8 1011static void test_mtab(void) {
6ee5bbf8 1012
5b4c0131
LP
1013 static const char ok[] =
1014 "/proc/self/mounts\0"
1015 "/proc/mounts\0"
1016 "../proc/self/mounts\0"
1017 "../proc/mounts\0";
80758717 1018
5b4c0131
LP
1019 _cleanup_free_ char *p = NULL;
1020 int r;
6ee5bbf8 1021
5b4c0131
LP
1022 /* Check that /etc/mtab is a symlink to the right place or
1023 * non-existing. But certainly not a file, or a symlink to
1024 * some weird place... */
6ee5bbf8 1025
5b4c0131
LP
1026 r = readlink_malloc("/etc/mtab", &p);
1027 if (r == -ENOENT)
1028 return;
1029 if (r >= 0 && nulstr_contains(ok, p))
1030 return;
6ee5bbf8 1031
bcce7187
DM
1032 log_error("/etc/mtab is not a symlink or not pointing to /proc/self/mounts. "
1033 "This is not supported anymore. "
1034 "Please make sure to replace this file by a symlink to avoid incorrect or misleading mount(8) output.");
1035 freeze();
80758717
LP
1036}
1037
1038static void test_usr(void) {
80758717 1039
ed1c99fc 1040 /* Check that /usr is not a separate fs */
80758717 1041
871c44a7
LP
1042 if (dir_is_empty("/usr") <= 0)
1043 return;
1044
8b173b5e 1045 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
871c44a7
LP
1046 "Some things will probably break (sometimes even silently) in mysterious ways. "
1047 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1048}
1049
a07fdfa3
LP
1050static int initialize_join_controllers(void) {
1051 /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
1052 * + "net_prio". We'd like to add "cpuset" to the mix, but
f131770b 1053 * "cpuset" doesn't really work for groups with no initialized
a07fdfa3
LP
1054 * attributes. */
1055
1056 arg_join_controllers = new(char**, 3);
1057 if (!arg_join_controllers)
1058 return -ENOMEM;
1059
1060 arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
fe382237
LP
1061 if (!arg_join_controllers[0])
1062 goto oom;
a6b26d90 1063
fe382237
LP
1064 arg_join_controllers[1] = strv_new("net_cls", "net_prio", NULL);
1065 if (!arg_join_controllers[1])
1066 goto oom;
a07fdfa3 1067
fe382237 1068 arg_join_controllers[2] = NULL;
a07fdfa3 1069 return 0;
fe382237
LP
1070
1071oom:
1072 arg_join_controllers = strv_free_free(arg_join_controllers);
1073 return -ENOMEM;
a07fdfa3
LP
1074}
1075
d3b1c508
LP
1076static int enforce_syscall_archs(Set *archs) {
1077#ifdef HAVE_SECCOMP
1078 scmp_filter_ctx *seccomp;
1079 Iterator i;
1080 void *id;
1081 int r;
1082
1083 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1084 if (!seccomp)
1085 return log_oom();
1086
1087 SET_FOREACH(id, arg_syscall_archs, i) {
1088 r = seccomp_arch_add(seccomp, PTR_TO_UINT32(id) - 1);
1089 if (r == -EEXIST)
1090 continue;
1091 if (r < 0) {
da927ba9 1092 log_error_errno(r, "Failed to add architecture to seccomp: %m");
d3b1c508
LP
1093 goto finish;
1094 }
1095 }
1096
8a8bf3c0
LP
1097 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1098 if (r < 0) {
da927ba9 1099 log_error_errno(r, "Failed to unset NO_NEW_PRIVS: %m");
8a8bf3c0
LP
1100 goto finish;
1101 }
1102
d3b1c508
LP
1103 r = seccomp_load(seccomp);
1104 if (r < 0)
da927ba9 1105 log_error_errno(r, "Failed to add install architecture seccomp: %m");
d3b1c508
LP
1106
1107finish:
1108 seccomp_release(seccomp);
1109 return r;
1110#else
1111 return 0;
1112#endif
1113}
1114
b6e2f329
LP
1115static int status_welcome(void) {
1116 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1117 int r;
1118
1119 r = parse_env_file("/etc/os-release", NEWLINE,
1120 "PRETTY_NAME", &pretty_name,
1121 "ANSI_COLOR", &ansi_color,
1122 NULL);
ece174c5 1123 if (r == -ENOENT)
5ae4d543
LP
1124 r = parse_env_file("/usr/lib/os-release", NEWLINE,
1125 "PRETTY_NAME", &pretty_name,
1126 "ANSI_COLOR", &ansi_color,
1127 NULL);
b6e2f329
LP
1128
1129 if (r < 0 && r != -ENOENT)
da927ba9 1130 log_warning_errno(r, "Failed to read os-release file: %m");
b6e2f329
LP
1131
1132 return status_printf(NULL, false, false,
1133 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1134 isempty(ansi_color) ? "1" : ansi_color,
1135 isempty(pretty_name) ? "Linux" : pretty_name);
1136}
1137
fdd25311
LP
1138static int write_container_id(void) {
1139 const char *c;
1140
1141 c = getenv("container");
1142 if (isempty(c))
1143 return 0;
1144
4c1fc3e4 1145 return write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
fdd25311
LP
1146}
1147
60918275
LP
1148int main(int argc, char *argv[]) {
1149 Manager *m = NULL;
22f4096c 1150 int r, retval = EXIT_FAILURE;
9d76d730
LP
1151 usec_t before_startup, after_startup;
1152 char timespan[FORMAT_TIMESPAN_MAX];
a16e1123
LP
1153 FDSet *fds = NULL;
1154 bool reexecute = false;
b9080b03 1155 const char *shutdown_verb = NULL;
86caf095
LP
1156 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL;
1157 dual_timestamp userspace_timestamp = DUAL_TIMESTAMP_NULL;
1158 dual_timestamp kernel_timestamp = DUAL_TIMESTAMP_NULL;
1159 dual_timestamp security_start_timestamp = DUAL_TIMESTAMP_NULL;
1160 dual_timestamp security_finish_timestamp = DUAL_TIMESTAMP_NULL;
5d6b1584 1161 static char systemd[] = "systemd";
2660882b 1162 bool skip_setup = false;
d3b1c508 1163 unsigned j;
0b3325e7 1164 bool loaded_policy = false;
e96d6be7 1165 bool arm_reboot_watchdog = false;
bf4df7c3 1166 bool queue_default_job = false;
5f5c2f38 1167 bool empty_etc = false;
41669317 1168 char *switch_root_dir = NULL, *switch_root_init = NULL;
86caf095 1169 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0);
cb6531be 1170 const char *error_message = NULL;
27b14a22 1171
058dc6f3 1172#ifdef HAVE_SYSV_COMPAT
2cb1a60d 1173 if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
35b8ca3a 1174 /* This is compatibility support for SysV, where
2cb1a60d
LP
1175 * calling init as a user is identical to telinit. */
1176
1177 errno = -ENOENT;
1178 execv(SYSTEMCTL_BINARY_PATH, argv);
56f64d95 1179 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
2cb1a60d
LP
1180 return 1;
1181 }
058dc6f3 1182#endif
2cb1a60d 1183
c3a170f3
HH
1184 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
1185 dual_timestamp_get(&userspace_timestamp);
1186
0b3325e7
LP
1187 /* Determine if this is a reexecution or normal bootup. We do
1188 * the full command line parsing much later, so let's just
1189 * have a quick peek here. */
db813c2a
LP
1190 if (strv_find(argv+1, "--deserialize"))
1191 skip_setup = true;
0b3325e7 1192
2660882b
LP
1193 /* If we have switched root, do all the special setup
1194 * things */
db813c2a
LP
1195 if (strv_find(argv+1, "--switched-root"))
1196 skip_setup = false;
d03bc1b8 1197
f3b6a3ed
LP
1198 /* If we get started via the /sbin/init symlink then we are
1199 called 'init'. After a subsequent reexecution we are then
1200 called 'systemd'. That is confusing, hence let's call us
1201 systemd right-away. */
f3b6a3ed
LP
1202 program_invocation_short_name = systemd;
1203 prctl(PR_SET_NAME, systemd);
5d6b1584 1204
9a0e6896
LP
1205 saved_argv = argv;
1206 saved_argc = argc;
f3b6a3ed 1207
2cc59dbf 1208 log_show_color(isatty(STDERR_FILENO) > 0);
c1dc6153 1209 log_set_upgrade_syslog_to_journal(true);
bbe63281 1210
90dc8c2e
MG
1211 /* Disable the umask logic */
1212 if (getpid() == 1)
1213 umask(0);
1214
75f86906 1215 if (getpid() == 1 && detect_container() <= 0) {
4f8d551f 1216
a866073d 1217 /* Running outside of a container as PID 1 */
b2c23da8 1218 arg_running_as = MANAGER_SYSTEM;
a866073d
LP
1219 make_null_stdio();
1220 log_set_target(LOG_TARGET_KMSG);
1221 log_open();
1222
21bf2ab0 1223 if (in_initrd())
c3a170f3 1224 initrd_timestamp = userspace_timestamp;
c3ba6250 1225
2660882b 1226 if (!skip_setup) {
8f838d8a 1227 mount_setup_early();
c2e0d600 1228 dual_timestamp_get(&security_start_timestamp);
cb6531be
ZJS
1229 if (mac_selinux_setup(&loaded_policy) < 0) {
1230 error_message = "Failed to load SELinux policy";
0b3325e7 1231 goto finish;
cb6531be
ZJS
1232 } else if (ima_setup() < 0) {
1233 error_message = "Failed to load IMA policy";
81611586 1234 goto finish;
cb6531be
ZJS
1235 } else if (mac_smack_setup(&loaded_policy) < 0) {
1236 error_message = "Failed to load SMACK policy";
ffbd2c4d 1237 goto finish;
cb6531be 1238 }
c2e0d600 1239 dual_timestamp_get(&security_finish_timestamp);
81611586 1240 }
0b3325e7 1241
cb6531be
ZJS
1242 if (mac_selinux_init(NULL) < 0) {
1243 error_message = "Failed to initialize SELinux policy";
0ff4cdd9 1244 goto finish;
cb6531be 1245 }
7948c4df 1246
72edcff5 1247 if (!skip_setup) {
24efb112 1248 if (clock_is_localtime() > 0) {
0b3325e7 1249 int min;
7948c4df 1250
c264aeab
KS
1251 /*
1252 * The very first call of settimeofday() also does a time warp in the kernel.
1253 *
1254 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on
1255 * external tools to take care of maintaining the RTC and do all adjustments.
1256 * This matches the behavior of Windows, which leaves the RTC alone if the
1257 * registry tells that the RTC runs in UTC.
1258 */
24efb112 1259 r = clock_set_timezone(&min);
0b3325e7 1260 if (r < 0)
da927ba9 1261 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
0b3325e7
LP
1262 else
1263 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
19e65613
KS
1264 } else if (!in_initrd()) {
1265 /*
c264aeab 1266 * Do a dummy very first call to seal the kernel's time warp magic.
19e65613
KS
1267 *
1268 * Do not call this this from inside the initrd. The initrd might not
1269 * carry /etc/adjtime with LOCAL, but the real system could be set up
1270 * that way. In such case, we need to delay the time-warp or the sealing
1271 * until we reach the real system.
c264aeab
KS
1272 *
1273 * Do no set the kernel's timezone. The concept of local time cannot
1274 * be supported reliably, the time will jump or be incorrect at every daylight
1275 * saving time change. All kernel local time concepts will be treated
1276 * as UTC that way.
19e65613 1277 */
c264aeab 1278 clock_reset_timewarp();
72edcff5
KS
1279 }
1280 }
a866073d
LP
1281
1282 /* Set the default for later on, but don't actually
1283 * open the logs like this for now. Note that if we
1284 * are transitioning from the initrd there might still
1285 * be journal fd open, and we shouldn't attempt
1286 * opening that before we parsed /proc/cmdline which
1287 * might redirect output elsewhere. */
1288 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1289
1290 } else if (getpid() == 1) {
a866073d 1291 /* Running inside a container, as PID 1 */
b2c23da8 1292 arg_running_as = MANAGER_SYSTEM;
a866073d 1293 log_set_target(LOG_TARGET_CONSOLE);
99f09825 1294 log_close_console(); /* force reopen of /dev/console */
a866073d
LP
1295 log_open();
1296
1297 /* For the later on, see above... */
1298 log_set_target(LOG_TARGET_JOURNAL);
1299
c3a170f3
HH
1300 /* clear the kernel timestamp,
1301 * because we are in a container */
1302 kernel_timestamp.monotonic = 0ULL;
1303 kernel_timestamp.realtime = 0ULL;
a866073d 1304
c3a170f3 1305 } else {
a866073d 1306 /* Running as user instance */
b2c23da8 1307 arg_running_as = MANAGER_USER;
eeecf6e6 1308 log_set_target(LOG_TARGET_AUTO);
871e5809 1309 log_open();
c3a170f3
HH
1310
1311 /* clear the kernel timestamp,
1312 * because we are not PID 1 */
6513d561 1313 kernel_timestamp = DUAL_TIMESTAMP_NULL;
bbe63281 1314 }
a5dab5ce 1315
0c85a4f3 1316 /* Initialize default unit */
e6e242ad 1317 r = free_and_strdup(&arg_default_unit, SPECIAL_DEFAULT_TARGET);
6afa301b 1318 if (r < 0) {
da927ba9 1319 log_emergency_errno(r, "Failed to set default unit %s: %m", SPECIAL_DEFAULT_TARGET);
cb6531be 1320 error_message = "Failed to set default unit";
f170852a 1321 goto finish;
14212119 1322 }
60918275 1323
a07fdfa3 1324 r = initialize_join_controllers();
cb6531be 1325 if (r < 0) {
ff9b60f3 1326 error_message = "Failed to initialize cgroup controllers";
0c85a4f3 1327 goto finish;
cb6531be 1328 }
0c85a4f3 1329
f170852a
LP
1330 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1331 * /proc/$PID/fd is available. */
c1dae1b3 1332 if (getpid() == 1) {
f84f9974
LP
1333
1334 /* Load the kernel modules early, so that we kdbus.ko is loaded before kdbusfs shall be mounted */
2e75e2a8
DM
1335 if (!skip_setup)
1336 kmod_setup();
2e75e2a8 1337
0c85a4f3 1338 r = mount_setup(loaded_policy);
cb6531be
ZJS
1339 if (r < 0) {
1340 error_message = "Failed to mount API filesystems";
8efe3c01 1341 goto finish;
cb6531be 1342 }
0c85a4f3 1343 }
4ade7963
LP
1344
1345 /* Reset all signal handlers. */
ce30c8dc
LP
1346 (void) reset_all_signal_handlers();
1347 (void) ignore_signals(SIGNALS_IGNORE, -1);
078e4539 1348
cb6531be
ZJS
1349 if (parse_config_file() < 0) {
1350 error_message = "Failed to parse config file";
487393e9 1351 goto finish;
cb6531be 1352 }
487393e9 1353
b2c23da8 1354 if (arg_running_as == MANAGER_SYSTEM) {
b5884878
LP
1355 r = parse_proc_cmdline(parse_proc_cmdline_item);
1356 if (r < 0)
da927ba9 1357 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
b5884878 1358 }
f170852a 1359
1de1c9c3
LP
1360 /* Note that this also parses bits from the kernel command
1361 * line, including "debug". */
f170852a
LP
1362 log_parse_environment();
1363
cb6531be
ZJS
1364 if (parse_argv(argc, argv) < 0) {
1365 error_message = "Failed to parse commandline arguments";
f170852a 1366 goto finish;
cb6531be 1367 }
f170852a 1368
6bae23a0
TB
1369 if (arg_action == ACTION_TEST &&
1370 geteuid() == 0) {
b5c6cf87
LP
1371 log_error("Don't run test mode as root.");
1372 goto finish;
1373 }
1374
b2c23da8 1375 if (arg_running_as == MANAGER_USER &&
6bae23a0
TB
1376 arg_action == ACTION_RUN &&
1377 sd_booted() <= 0) {
1378 log_error("Trying to run as user instance, but the system has not been booted with systemd.");
1379 goto finish;
1380 }
1381
b2c23da8 1382 if (arg_running_as == MANAGER_SYSTEM &&
fe783b03
LP
1383 arg_action == ACTION_RUN &&
1384 running_in_chroot() > 0) {
1385 log_error("Cannot be run in a chroot() environment.");
1386 goto finish;
1387 }
1388
0d8c31ff
ZJS
1389 if (arg_action == ACTION_TEST)
1390 skip_setup = true;
1391
b87c2aa6
ZJS
1392 pager_open_if_enabled();
1393
fa0f4d8a 1394 if (arg_action == ACTION_HELP) {
f170852a
LP
1395 retval = help();
1396 goto finish;
9ba0bc4e
ZJS
1397 } else if (arg_action == ACTION_VERSION) {
1398 retval = version();
1399 goto finish;
fa0f4d8a 1400 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
e537352b 1401 unit_dump_config_items(stdout);
22f4096c 1402 retval = EXIT_SUCCESS;
e537352b 1403 goto finish;
fa0f4d8a 1404 } else if (arg_action == ACTION_DONE) {
22f4096c 1405 retval = EXIT_SUCCESS;
4288f619 1406 goto finish;
f170852a
LP
1407 }
1408
b2c23da8 1409 if (arg_running_as == MANAGER_USER &&
8be28fb1
KS
1410 !getenv("XDG_RUNTIME_DIR")) {
1411 log_error("Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
1412 goto finish;
1413 }
1414
fa0f4d8a 1415 assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
f170852a 1416
871e5809
LP
1417 /* Close logging fds, in order not to confuse fdset below */
1418 log_close();
1419
a16e1123 1420 /* Remember open file descriptors for later deserialization */
01e10de3
LP
1421 r = fdset_new_fill(&fds);
1422 if (r < 0) {
da927ba9 1423 log_emergency_errno(r, "Failed to allocate fd set: %m");
cb6531be 1424 error_message = "Failed to allocate fd set";
01e10de3
LP
1425 goto finish;
1426 } else
1427 fdset_cloexec(fds, true);
a16e1123 1428
d3b1c508
LP
1429 if (arg_serialization)
1430 assert_se(fdset_remove(fds, fileno(arg_serialization)) >= 0);
a16e1123 1431
b2c23da8 1432 if (arg_running_as == MANAGER_SYSTEM)
80876c20
LP
1433 /* Become a session leader if we aren't one yet. */
1434 setsid();
4ade7963 1435
befb5b6a 1436 /* Move out of the way, so that we won't block unmounts */
d250afe7 1437 assert_se(chdir("/") == 0);
befb5b6a 1438
2146621b
LP
1439 /* Reset the console, but only if this is really init and we
1440 * are freshly booted */
b2c23da8 1441 if (arg_running_as == MANAGER_SYSTEM && arg_action == ACTION_RUN) {
56d96fc0
LP
1442
1443 /* If we are init, we connect stdin/stdout/stderr to
1444 * /dev/null and make sure we don't have a controlling
1445 * tty. */
1446 release_terminal();
1447
1448 if (getpid() == 1 && !skip_setup)
1449 console_setup();
1450 }
4ade7963 1451
18149b9f 1452 /* Open the logging devices, if possible and necessary */
843d2643 1453 log_open();
4ade7963 1454
b6e2f329
LP
1455 if (arg_show_status == _SHOW_STATUS_UNSET)
1456 arg_show_status = SHOW_STATUS_YES;
1457
5373d602
LP
1458 /* Make sure we leave a core dump without panicing the
1459 * kernel. */
ab422445 1460 if (getpid() == 1) {
4fc935ca 1461 install_crash_handler();
97c4f35c 1462
0c85a4f3
LP
1463 r = mount_cgroup_controllers(arg_join_controllers);
1464 if (r < 0)
1465 goto finish;
1466 }
1467
b2c23da8 1468 if (arg_running_as == MANAGER_SYSTEM) {
75f86906 1469 int v;
c20f5ac7 1470
0d8c31ff
ZJS
1471 log_info(PACKAGE_STRING " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
1472 arg_action == ACTION_TEST ? "test " : "" );
c20f5ac7 1473
75f86906
LP
1474 v = detect_virtualization();
1475 if (v > 0)
1476 log_info("Detected virtualization %s.", virtualization_to_string(v));
c20f5ac7 1477
fdd25311
LP
1478 write_container_id();
1479
d3f86679 1480 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
d9d93745 1481
26a1efdf
LP
1482 if (in_initrd())
1483 log_info("Running in initial RAM disk.");
1484
3408ba01
LP
1485 /* Let's check whether /etc is already populated. We
1486 * don't actually really check for that, but use
1487 * /etc/machine-id as flag file. This allows container
1488 * managers and installers to provision a couple of
1489 * files already. If the container manager wants to
1490 * provision the machine ID itself it should pass
ee33e53a 1491 * $container_uuid to PID 1. */
3408ba01 1492
baa1bdf7 1493 empty_etc = access("/etc/machine-id", F_OK) < 0;
5f5c2f38
LP
1494 if (empty_etc)
1495 log_info("Running with unpopulated /etc.");
d8160f21 1496 } else {
1f97091d
LP
1497 _cleanup_free_ char *t;
1498
1499 t = uid_to_name(getuid());
0d8c31ff
ZJS
1500 log_debug(PACKAGE_STRING " running in %suser mode for user "UID_FMT"/%s. (" SYSTEMD_FEATURES ")",
1501 arg_action == ACTION_TEST ? " test" : "", getuid(), t);
d8160f21 1502 }
a5dab5ce 1503
b2c23da8 1504 if (arg_running_as == MANAGER_SYSTEM && !skip_setup) {
031886ed 1505 if (arg_show_status > 0)
888c6216
LP
1506 status_welcome();
1507
888c6216 1508 hostname_setup();
489388fb 1509 machine_id_setup(NULL);
888c6216 1510 loopback_setup();
490aed58 1511
6ee5bbf8 1512 test_mtab();
80758717 1513 test_usr();
af5bc85d 1514 }
302e8c4c 1515
b2c23da8 1516 if (arg_running_as == MANAGER_SYSTEM && arg_runtime_watchdog > 0)
e96d6be7
LP
1517 watchdog_set_timeout(&arg_runtime_watchdog);
1518
3a43da28 1519 if (arg_timer_slack_nsec != NSEC_INFINITY)
aa0f64ac 1520 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
56f64d95 1521 log_error_errno(errno, "Failed to adjust timer slack: %m");
aa0f64ac 1522
ec8927ca 1523 if (arg_capability_bounding_set_drop) {
31c885e9 1524 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set_drop);
ec8927ca 1525 if (r < 0) {
da927ba9 1526 log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
cb6531be 1527 error_message = "Failed to drop capability bounding set of usermode helpers";
ec8927ca
LP
1528 goto finish;
1529 }
31c885e9 1530 r = capability_bounding_set_drop(arg_capability_bounding_set_drop, true);
939b8f14 1531 if (r < 0) {
da927ba9 1532 log_emergency_errno(r, "Failed to drop capability bounding set: %m");
cb6531be 1533 error_message = "Failed to drop capability bounding set";
939b8f14
LP
1534 goto finish;
1535 }
ec8927ca
LP
1536 }
1537
d3b1c508
LP
1538 if (arg_syscall_archs) {
1539 r = enforce_syscall_archs(arg_syscall_archs);
cb6531be
ZJS
1540 if (r < 0) {
1541 error_message = "Failed to set syscall architectures";
d3b1c508 1542 goto finish;
cb6531be 1543 }
d3b1c508
LP
1544 }
1545
61b9b203 1546 if (arg_running_as == MANAGER_USER)
d4447f4d 1547 /* Become reaper of our children */
61b9b203 1548 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
56f64d95 1549 log_warning_errno(errno, "Failed to make us a subreaper: %m");
d4447f4d 1550
b2c23da8 1551 if (arg_running_as == MANAGER_SYSTEM) {
4096d6f5
LP
1552 bump_rlimit_nofile(&saved_rlimit_nofile);
1553
5f5c2f38 1554 if (empty_etc) {
304b3079 1555 r = unit_file_preset_all(UNIT_FILE_SYSTEM, false, NULL, UNIT_FILE_PRESET_ENABLE_ONLY, false, NULL, 0);
5f5c2f38 1556 if (r < 0)
da927ba9 1557 log_warning_errno(r, "Failed to populate /etc with preset unit settings, ignoring: %m");
5f5c2f38
LP
1558 else
1559 log_info("Populated /etc with preset unit settings.");
1560 }
1561 }
1562
0d8c31ff 1563 r = manager_new(arg_running_as, arg_action == ACTION_TEST, &m);
e96d6be7 1564 if (r < 0) {
da927ba9 1565 log_emergency_errno(r, "Failed to allocate manager object: %m");
cb6531be 1566 error_message = "Failed to allocate manager object";
60918275
LP
1567 goto finish;
1568 }
1569
9e58ff9c 1570 m->confirm_spawn = arg_confirm_spawn;
e96d6be7
LP
1571 m->runtime_watchdog = arg_runtime_watchdog;
1572 m->shutdown_watchdog = arg_shutdown_watchdog;
c3a170f3
HH
1573 m->userspace_timestamp = userspace_timestamp;
1574 m->kernel_timestamp = kernel_timestamp;
c3a170f3 1575 m->initrd_timestamp = initrd_timestamp;
c2e0d600
TA
1576 m->security_start_timestamp = security_start_timestamp;
1577 m->security_finish_timestamp = security_finish_timestamp;
9e58ff9c 1578
06af2a04 1579 manager_set_defaults(m);
27d340c7 1580 manager_set_show_status(m, arg_show_status);
e2680723 1581 manager_set_first_boot(m, empty_etc);
27d340c7 1582
bf4df7c3 1583 /* Remember whether we should queue the default job */
d3b1c508 1584 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 1585
9d76d730
LP
1586 before_startup = now(CLOCK_MONOTONIC);
1587
d3b1c508 1588 r = manager_startup(m, arg_serialization, fds);
e96d6be7 1589 if (r < 0)
da927ba9 1590 log_error_errno(r, "Failed to fully start up daemon: %m");
a16e1123 1591
bf4df7c3
LP
1592 /* This will close all file descriptors that were opened, but
1593 * not claimed by any unit. */
2feceb5e 1594 fds = fdset_free(fds);
f50e0a01 1595
74ca738f 1596 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
1597
1598 if (queue_default_job) {
718db961 1599 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1c27d3f3 1600 Unit *target = NULL;
bacbccb7 1601 Job *default_unit_job;
398ef8ba 1602
fa0f4d8a 1603 log_debug("Activating default unit: %s", arg_default_unit);
a16e1123 1604
e96d6be7 1605 r = manager_load_unit(m, arg_default_unit, NULL, &error, &target);
718db961
LP
1606 if (r < 0)
1607 log_error("Failed to load default target: %s", bus_error_message(&error, r));
1608 else if (target->load_state == UNIT_ERROR || target->load_state == UNIT_NOT_FOUND)
c33b3297 1609 log_error_errno(target->load_error, "Failed to load default target: %m");
ac155bb8 1610 else if (target->load_state == UNIT_MASKED)
6daf4f90 1611 log_error("Default target masked.");
27b14a22 1612
ac155bb8 1613 if (!target || target->load_state != UNIT_LOADED) {
a16e1123 1614 log_info("Trying to load rescue target...");
1c27d3f3 1615
e96d6be7
LP
1616 r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target);
1617 if (r < 0) {
4104970e 1618 log_emergency("Failed to load rescue target: %s", bus_error_message(&error, r));
cb6531be 1619 error_message = "Failed to load rescue target";
a16e1123 1620 goto finish;
11ddb6f4 1621 } else if (target->load_state == UNIT_ERROR || target->load_state == UNIT_NOT_FOUND) {
c33b3297 1622 log_emergency_errno(target->load_error, "Failed to load rescue target: %m");
cb6531be 1623 error_message = "Failed to load rescue target";
1c27d3f3 1624 goto finish;
ac155bb8 1625 } else if (target->load_state == UNIT_MASKED) {
4104970e 1626 log_emergency("Rescue target masked.");
cb6531be 1627 error_message = "Rescue target masked";
00dc5d76 1628 goto finish;
a16e1123
LP
1629 }
1630 }
37d88da7 1631
ac155bb8 1632 assert(target->load_state == UNIT_LOADED);
00dc5d76 1633
fa0f4d8a 1634 if (arg_action == ACTION_TEST) {
40d50879 1635 printf("-> By units:\n");
a16e1123
LP
1636 manager_dump_units(m, stdout, "\t");
1637 }
1638
95f1b47d 1639 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, false, &error, &default_unit_job);
ab17a050 1640 if (r == -EPERM) {
718db961 1641 log_debug("Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
ab17a050
LP
1642
1643 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &error, &default_unit_job);
1644 if (r < 0) {
4104970e 1645 log_emergency("Failed to start default target: %s", bus_error_message(&error, r));
cb6531be 1646 error_message = "Failed to start default target";
ab17a050
LP
1647 goto finish;
1648 }
1649 } else if (r < 0) {
4104970e 1650 log_emergency("Failed to isolate default target: %s", bus_error_message(&error, r));
cb6531be 1651 error_message = "Failed to isolate default target";
37d88da7
LP
1652 goto finish;
1653 }
ab17a050 1654
bacbccb7 1655 m->default_unit_job_id = default_unit_job->id;
60918275 1656
07672f49
LP
1657 after_startup = now(CLOCK_MONOTONIC);
1658 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
1659 "Loaded units and determined initial transaction in %s.",
fdb14b7e 1660 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 1661
fa0f4d8a 1662 if (arg_action == ACTION_TEST) {
40d50879 1663 printf("-> By jobs:\n");
a16e1123 1664 manager_dump_jobs(m, stdout, "\t");
22f4096c 1665 retval = EXIT_SUCCESS;
a16e1123
LP
1666 goto finish;
1667 }
e965d56d 1668 }
d46de8a1 1669
a16e1123 1670 for (;;) {
e96d6be7
LP
1671 r = manager_loop(m);
1672 if (r < 0) {
da927ba9 1673 log_emergency_errno(r, "Failed to run main loop: %m");
cb6531be 1674 error_message = "Failed to run main loop";
a16e1123
LP
1675 goto finish;
1676 }
11dd41ce 1677
a16e1123 1678 switch (m->exit_code) {
e965d56d 1679
a16e1123 1680 case MANAGER_RELOAD:
e015090f 1681 log_info("Reloading.");
06af2a04
TB
1682
1683 r = parse_config_file();
1684 if (r < 0)
1685 log_error("Failed to parse config file.");
1686
1687 manager_set_defaults(m);
1688
e96d6be7
LP
1689 r = manager_reload(m);
1690 if (r < 0)
da927ba9 1691 log_error_errno(r, "Failed to reload: %m");
a16e1123 1692 break;
cea8e32e 1693
a16e1123 1694 case MANAGER_REEXECUTE:
664f88a7 1695
cb6531be 1696 if (prepare_reexecute(m, &arg_serialization, &fds, false) < 0) {
6b9af963 1697 error_message = "Failed to prepare for reexecution";
a16e1123 1698 goto finish;
cb6531be 1699 }
60918275 1700
a16e1123 1701 reexecute = true;
e015090f 1702 log_notice("Reexecuting.");
a16e1123
LP
1703 goto finish;
1704
664f88a7
LP
1705 case MANAGER_SWITCH_ROOT:
1706 /* Steal the switch root parameters */
41669317 1707 switch_root_dir = m->switch_root;
664f88a7
LP
1708 switch_root_init = m->switch_root_init;
1709 m->switch_root = m->switch_root_init = NULL;
1710
1711 if (!switch_root_init)
cb6531be 1712 if (prepare_reexecute(m, &arg_serialization, &fds, true) < 0) {
6b9af963 1713 error_message = "Failed to prepare for reexecution";
664f88a7 1714 goto finish;
cb6531be 1715 }
664f88a7
LP
1716
1717 reexecute = true;
1718 log_notice("Switching root.");
1719 goto finish;
1720
287419c1 1721 case MANAGER_EXIT:
97792515
LP
1722 retval = m->return_value;
1723
8ebfe0cb 1724 if (m->running_as == MANAGER_USER) {
8ebfe0cb
DH
1725 log_debug("Exit.");
1726 goto finish;
1727 }
1728
1729 /* fallthrough */
b9080b03
FF
1730 case MANAGER_REBOOT:
1731 case MANAGER_POWEROFF:
1732 case MANAGER_HALT:
1733 case MANAGER_KEXEC: {
1734 static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
287419c1 1735 [MANAGER_EXIT] = "exit",
b9080b03
FF
1736 [MANAGER_REBOOT] = "reboot",
1737 [MANAGER_POWEROFF] = "poweroff",
1738 [MANAGER_HALT] = "halt",
1739 [MANAGER_KEXEC] = "kexec"
1740 };
1741
1742 assert_se(shutdown_verb = table[m->exit_code]);
e96d6be7 1743 arm_reboot_watchdog = m->exit_code == MANAGER_REBOOT;
b9080b03
FF
1744
1745 log_notice("Shutting down.");
1746 goto finish;
1747 }
1748
a16e1123
LP
1749 default:
1750 assert_not_reached("Unknown exit code.");
1751 }
1752 }
f170852a 1753
60918275 1754finish:
b87c2aa6
ZJS
1755 pager_close();
1756
97792515 1757 if (m)
81f5fc2d 1758 arg_shutdown_watchdog = m->shutdown_watchdog;
fe382237 1759
06d8d842 1760 m = manager_free(m);
60918275 1761
1f6b4113 1762 for (j = 0; j < ELEMENTSOF(arg_default_rlimit); j++)
a1e58e8e 1763 arg_default_rlimit[j] = mfree(arg_default_rlimit[j]);
c93ff2e9 1764
97b11eed 1765 arg_default_unit = mfree(arg_default_unit);
fe382237 1766 arg_join_controllers = strv_free_free(arg_join_controllers);
97b11eed 1767 arg_default_environment = strv_free(arg_default_environment);
525d3cc7 1768 arg_syscall_archs = set_free(arg_syscall_archs);
d3b1c508 1769
cc56fafe 1770 mac_selinux_finish();
b2bb3dbe 1771
a16e1123 1772 if (reexecute) {
664f88a7 1773 const char **args;
e564a982 1774 unsigned i, args_size;
a16e1123 1775
664f88a7
LP
1776 /* Close and disarm the watchdog, so that the new
1777 * instance can reinitialize it, but doesn't get
1778 * rebooted while we do that */
1779 watchdog_close(true);
a16e1123 1780
4096d6f5
LP
1781 /* Reset the RLIMIT_NOFILE to the kernel default, so
1782 * that the new systemd can pass the kernel default to
1783 * its child processes */
1784 if (saved_rlimit_nofile.rlim_cur > 0)
92ca4cac 1785 (void) setrlimit(RLIMIT_NOFILE, &saved_rlimit_nofile);
4096d6f5 1786
41669317 1787 if (switch_root_dir) {
cee530bb
LP
1788 /* Kill all remaining processes from the
1789 * initrd, but don't wait for them, so that we
1790 * can handle the SIGCHLD for them after
1791 * deserializing. */
0bee65f0 1792 broadcast_signal(SIGTERM, false, true);
bd3fa1d2 1793
5a4bf02f
HH
1794 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1795 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
41669317 1796 if (r < 0)
da927ba9 1797 log_error_errno(r, "Failed to switch root, trying to continue: %m");
41669317 1798 }
a16e1123 1799
d03bc1b8 1800 args_size = MAX(6, argc+1);
e564a982 1801 args = newa(const char*, args_size);
a16e1123 1802
664f88a7 1803 if (!switch_root_init) {
5ffa8c81 1804 char sfd[DECIMAL_STR_MAX(int) + 1];
a16e1123 1805
664f88a7
LP
1806 /* First try to spawn ourselves with the right
1807 * path, and with full serialization. We do
1808 * this only if the user didn't specify an
1809 * explicit init to spawn. */
edb9aaa8 1810
d3b1c508 1811 assert(arg_serialization);
664f88a7 1812 assert(fds);
edb9aaa8 1813
5ffa8c81 1814 xsprintf(sfd, "%i", fileno(arg_serialization));
edb9aaa8 1815
664f88a7
LP
1816 i = 0;
1817 args[i++] = SYSTEMD_BINARY_PATH;
41669317 1818 if (switch_root_dir)
2660882b 1819 args[i++] = "--switched-root";
b2c23da8 1820 args[i++] = arg_running_as == MANAGER_SYSTEM ? "--system" : "--user";
664f88a7
LP
1821 args[i++] = "--deserialize";
1822 args[i++] = sfd;
1823 args[i++] = NULL;
edb9aaa8 1824
ce8aba56
KS
1825 /* do not pass along the environment we inherit from the kernel or initrd */
1826 if (switch_root_dir)
92ca4cac 1827 (void) clearenv();
ce8aba56 1828
e564a982 1829 assert(i <= args_size);
92ca4cac 1830 (void) execv(args[0], (char* const*) args);
664f88a7 1831 }
6e98720f 1832
664f88a7
LP
1833 /* Try the fallback, if there is any, without any
1834 * serialization. We pass the original argv[] and
1835 * envp[]. (Well, modulo the ordering changes due to
1836 * getopt() in argv[], and some cleanups in envp[],
1837 * but let's hope that doesn't matter.) */
a16e1123 1838
74ca738f 1839 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 1840 fds = fdset_free(fds);
a16e1123 1841
a504223d 1842 /* Reopen the console */
92ca4cac 1843 (void) make_console_stdio();
a504223d 1844
d3b1c508 1845 for (j = 1, i = 1; j < (unsigned) argc; j++)
664f88a7 1846 args[i++] = argv[j];
a16e1123 1847 args[i++] = NULL;
e564a982 1848 assert(i <= args_size);
b8f83232 1849
1b6d7fa7 1850 /* Reenable any blocked signals, especially important
5a85ca1c 1851 * if we switch from initial ramdisk to init=... */
ce30c8dc
LP
1852 (void) reset_all_signal_handlers();
1853 (void) reset_signal_mask();
5a85ca1c 1854
b8f83232
LP
1855 if (switch_root_init) {
1856 args[0] = switch_root_init;
92ca4cac 1857 (void) execv(args[0], (char* const*) args);
56f64d95 1858 log_warning_errno(errno, "Failed to execute configured init, trying fallback: %m");
b8f83232
LP
1859 }
1860
1861 args[0] = "/sbin/init";
92ca4cac 1862 (void) execv(args[0], (char* const*) args);
a16e1123 1863
745e2fb7
KS
1864 if (errno == ENOENT) {
1865 log_warning("No /sbin/init, trying fallback");
b8f83232 1866
745e2fb7
KS
1867 args[0] = "/bin/sh";
1868 args[1] = NULL;
92ca4cac 1869 (void) execv(args[0], (char* const*) args);
56f64d95 1870 log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
745e2fb7 1871 } else
56f64d95 1872 log_warning_errno(errno, "Failed to execute /sbin/init, giving up: %m");
a16e1123
LP
1873 }
1874
74ca738f 1875 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 1876 fds = fdset_free(fds);
a16e1123 1877
54b434b1
LP
1878#ifdef HAVE_VALGRIND_VALGRIND_H
1879 /* If we are PID 1 and running under valgrind, then let's exit
1880 * here explicitly. valgrind will only generate nice output on
1881 * exit(), not on exec(), hence let's do the former not the
1882 * latter here. */
1883 if (getpid() == 1 && RUNNING_ON_VALGRIND)
1884 return 0;
1885#endif
1886
b9080b03 1887 if (shutdown_verb) {
b1e90ec5 1888 char log_level[DECIMAL_STR_MAX(int) + 1];
287419c1
AC
1889 char exit_code[DECIMAL_STR_MAX(uint8_t) + 1];
1890 const char* command_line[11] = {
b9080b03
FF
1891 SYSTEMD_SHUTDOWN_BINARY_PATH,
1892 shutdown_verb,
b1e90ec5
ZJS
1893 "--log-level", log_level,
1894 "--log-target",
b9080b03 1895 };
b1e90ec5 1896 unsigned pos = 5;
e3e45d4f 1897 _cleanup_strv_free_ char **env_block = NULL;
15bd5aee
LP
1898
1899 assert(command_line[pos] == NULL);
e3e45d4f 1900 env_block = strv_copy(environ);
b9080b03 1901
5ffa8c81 1902 xsprintf(log_level, "%d", log_get_max_level());
b1e90ec5
ZJS
1903
1904 switch (log_get_target()) {
92ca4cac 1905
b1e90ec5
ZJS
1906 case LOG_TARGET_KMSG:
1907 case LOG_TARGET_JOURNAL_OR_KMSG:
1908 case LOG_TARGET_SYSLOG_OR_KMSG:
1909 command_line[pos++] = "kmsg";
1910 break;
1911
10f00ff1
ILG
1912 case LOG_TARGET_NULL:
1913 command_line[pos++] = "null";
1914 break;
1915
b1e90ec5
ZJS
1916 case LOG_TARGET_CONSOLE:
1917 default:
1918 command_line[pos++] = "console";
1919 break;
1920 };
1921
1922 if (log_get_show_color())
1923 command_line[pos++] = "--log-color";
1924
1925 if (log_get_show_location())
1926 command_line[pos++] = "--log-location";
1927
287419c1
AC
1928 if (streq(shutdown_verb, "exit")) {
1929 command_line[pos++] = "--exit-code";
1930 command_line[pos++] = exit_code;
97792515 1931 xsprintf(exit_code, "%d", retval);
287419c1
AC
1932 }
1933
26abdc73 1934 assert(pos < ELEMENTSOF(command_line));
b1e90ec5 1935
e96d6be7 1936 if (arm_reboot_watchdog && arg_shutdown_watchdog > 0) {
e3e45d4f 1937 char *e;
d18f337c 1938
e96d6be7
LP
1939 /* If we reboot let's set the shutdown
1940 * watchdog and tell the shutdown binary to
1941 * repeatedly ping it */
c2cc6b9a
LP
1942 r = watchdog_set_timeout(&arg_shutdown_watchdog);
1943 watchdog_close(r < 0);
e96d6be7 1944
e3e45d4f
SP
1945 /* Tell the binary how often to ping, ignore failure */
1946 if (asprintf(&e, "WATCHDOG_USEC="USEC_FMT, arg_shutdown_watchdog) > 0)
92ca4cac 1947 (void) strv_push(&env_block, e);
e3e45d4f 1948 } else
e96d6be7
LP
1949 watchdog_close(true);
1950
66713f77
LP
1951 /* Avoid the creation of new processes forked by the
1952 * kernel; at this point, we will not listen to the
1953 * signals anyway */
75f86906 1954 if (detect_container() <= 0)
e155a0aa 1955 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
ad929bcc 1956
d18f337c 1957 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
56f64d95 1958 log_error_errno(errno, "Failed to execute shutdown binary, %s: %m",
b1e90ec5 1959 getpid() == 1 ? "freezing" : "quitting");
b9080b03
FF
1960 }
1961
cb6531be
ZJS
1962 if (getpid() == 1) {
1963 if (error_message)
1964 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 1965 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
cb6531be 1966 "%s, freezing.", error_message);
c3b3c274 1967 freeze();
cb6531be 1968 }
c3b3c274 1969
60918275
LP
1970 return retval;
1971}