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