main.c 74.7 KB
Newer Older
1
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
Lennart Poettering's avatar
Lennart Poettering committed
2

3 4 5 6 7 8
/***
  This file is part of systemd.

  Copyright 2010 Lennart Poettering

  systemd is free software; you can redistribute it and/or modify it
9 10
  under the terms of the GNU Lesser General Public License as published by
  the Free Software Foundation; either version 2.1 of the License, or
11 12 13 14 15
  (at your option) any later version.

  systemd is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
  Lesser General Public License for more details.
17

18
  You should have received a copy of the GNU Lesser General Public License
19 20 21
  along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/

22 23
#include <dbus/dbus.h>

Lennart Poettering's avatar
Lennart Poettering committed
24 25 26
#include <stdio.h>
#include <errno.h>
#include <string.h>
27
#include <unistd.h>
28 29
#include <sys/types.h>
#include <sys/stat.h>
30
#include <getopt.h>
31
#include <signal.h>
32
#include <sys/wait.h>
Lennart Poettering's avatar
Lennart Poettering committed
33
#include <fcntl.h>
34
#include <sys/prctl.h>
35
#include <sys/mount.h>
Lennart Poettering's avatar
Lennart Poettering committed
36 37

#include "manager.h"
38
#include "log.h"
39
#include "load-fragment.h"
40
#include "fdset.h"
41
#include "special.h"
42
#include "conf-parser.h"
43
#include "dbus-common.h"
44
#include "missing.h"
45
#include "label.h"
46
#include "build.h"
47
#include "strv.h"
48
#include "def.h"
49
#include "virt.h"
50
#include "watchdog.h"
51
#include "path-util.h"
52
#include "switch-root.h"
53
#include "capability.h"
54
#include "killall.h"
55 56 57
#include "env-util.h"
#include "hwclock.h"
#include "sd-daemon.h"
58
#include "sd-messages.h"
Lennart Poettering's avatar
Lennart Poettering committed
59

60 61
#include "mount-setup.h"
#include "loopback-setup.h"
62
#ifdef HAVE_KMOD
63
#include "kmod-setup.h"
64
#endif
65 66 67 68 69
#include "hostname-setup.h"
#include "machine-id-setup.h"
#include "locale-setup.h"
#include "selinux-setup.h"
#include "ima-setup.h"
70
#include "fileio.h"
71
#include "smack-setup.h"
72
#include "efivars.h"
73

74 75
static enum {
        ACTION_RUN,
Lennart Poettering's avatar
Lennart Poettering committed
76
        ACTION_HELP,
77
        ACTION_VERSION,
78
        ACTION_TEST,
79 80
        ACTION_DUMP_CONFIGURATION_ITEMS,
        ACTION_DONE
81
} arg_action = ACTION_RUN;
82

83
static char *arg_default_unit = NULL;
84
static SystemdRunningAs arg_running_as = _SYSTEMD_RUNNING_AS_INVALID;
85 86 87 88 89

static bool arg_dump_core = true;
static bool arg_crash_shell = false;
static int arg_crash_chvt = -1;
static bool arg_confirm_spawn = false;
90
static bool arg_show_status = true;
91
static bool arg_switched_root = false;
92
static char **arg_default_controllers = NULL;
93
static char ***arg_join_controllers = NULL;
94
static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
95
static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
96 97
static usec_t arg_runtime_watchdog = 0;
static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
98
static struct rlimit *arg_default_rlimit[RLIMIT_NLIMITS] = {};
99
static uint64_t arg_capability_bounding_set_drop = 0;
100
static nsec_t arg_timer_slack_nsec = (nsec_t) -1;
101

102
static FILE* serialization = NULL;
Lennart Poettering's avatar
Lennart Poettering committed
103

104 105 106
static void nop_handler(int sig) {
}

107
_noreturn_ static void crash(int sig) {
108

109
        if (!arg_dump_core)
110
                log_error("Caught <%s>, not dumping core.", signal_to_string(sig));
111
        else {
112 113 114 115
                struct sigaction sa = {
                        .sa_handler = nop_handler,
                        .sa_flags = SA_NOCLDSTOP|SA_RESTART,
                };
116 117
                pid_t pid;

118 119 120
                /* We want to wait for the core process, hence let's enable SIGCHLD */
                assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);

Zbigniew Jędrzejewski-Szmek's avatar
Zbigniew Jędrzejewski-Szmek committed
121 122
                pid = fork();
                if (pid < 0)
123
                        log_error("Caught <%s>, cannot fork for core dump: %s", signal_to_string(sig), strerror(errno));
124 125

                else if (pid == 0) {
126
                        struct rlimit rl = {};
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

                        /* Enable default signal handler for core dump */
                        zero(sa);
                        sa.sa_handler = SIG_DFL;
                        assert_se(sigaction(sig, &sa, NULL) == 0);

                        /* Don't limit the core dump size */
                        rl.rlim_cur = RLIM_INFINITY;
                        rl.rlim_max = RLIM_INFINITY;
                        setrlimit(RLIMIT_CORE, &rl);

                        /* Just to be sure... */
                        assert_se(chdir("/") == 0);

                        /* Raise the signal again */
                        raise(sig);

                        assert_not_reached("We shouldn't be here...");
                        _exit(1);
146 147

                } else {
148 149
                        siginfo_t status;
                        int r;
150 151

                        /* Order things nicely. */
Zbigniew Jędrzejewski-Szmek's avatar
Zbigniew Jędrzejewski-Szmek committed
152 153
                        r = wait_for_terminate(pid, &status);
                        if (r < 0)
154
                                log_error("Caught <%s>, waitpid() failed: %s", signal_to_string(sig), strerror(-r));
155
                        else if (status.si_code != CLD_DUMPED)
156
                                log_error("Caught <%s>, core dump failed.", signal_to_string(sig));
157
                        else
158
                                log_error("Caught <%s>, dumped core as pid %lu.", signal_to_string(sig), (unsigned long) pid);
159 160 161
                }
        }

162 163
        if (arg_crash_chvt)
                chvt(arg_crash_chvt);
164

165
        if (arg_crash_shell) {
166 167 168 169
                struct sigaction sa = {
                        .sa_handler = SIG_IGN,
                        .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
                };
170
                pid_t pid;
171

172 173 174
                log_info("Executing crash shell in 10s...");
                sleep(10);

175 176
                /* Let the kernel reap children for us */
                assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
177

178 179
                pid = fork();
                if (pid < 0)
180
                        log_error("Failed to fork off crash shell: %m");
181
                else if (pid == 0) {
182
                        make_console_stdio();
183 184
                        execl("/bin/sh", "/bin/sh", NULL);

185
                        log_error("execl() failed: %m");
186 187
                        _exit(1);
                }
188

189
                log_info("Successfully spawned crash shell as pid %lu.", (unsigned long) pid);
190 191 192
        }

        log_info("Freezing execution.");
193 194 195 196
        freeze();
}

static void install_crash_handler(void) {
197 198 199 200
        struct sigaction sa = {
                .sa_handler = crash,
                .sa_flags = SA_NODEFER,
        };
201

Lennart Poettering's avatar
Lennart Poettering committed
202
        sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
203
}
204

205 206
static int console_setup(bool do_reset) {
        int tty_fd, r;
Lennart Poettering's avatar
Lennart Poettering committed
207

208 209
        /* If we are init, we connect stdin/stdout/stderr to /dev/null
         * and make sure we don't have a controlling tty. */
Lennart Poettering's avatar
Lennart Poettering committed
210

211 212 213 214
        release_terminal();

        if (!do_reset)
                return 0;
Lennart Poettering's avatar
Lennart Poettering committed
215

216 217
        tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
        if (tty_fd < 0) {
218 219 220
                log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
                return -tty_fd;
        }
Lennart Poettering's avatar
Lennart Poettering committed
221

222 223 224 225
        /* We don't want to force text mode.
         * plymouth may be showing pictures already from initrd. */
        r = reset_terminal_fd(tty_fd, false);
        if (r < 0)
226 227 228
                log_error("Failed to reset /dev/console: %s", strerror(-r));

        close_nointr_nofail(tty_fd);
Lennart Poettering's avatar
Lennart Poettering committed
229 230 231
        return r;
}

232 233 234 235 236
static int set_default_unit(const char *u) {
        char *c;

        assert(u);

237 238
        c = strdup(u);
        if (!c)
239 240
                return -ENOMEM;

241 242
        free(arg_default_unit);
        arg_default_unit = c;
243

244 245 246 247 248 249
        return 0;
}

static int parse_proc_cmdline_word(const char *word) {

        static const char * const rlmap[] = {
250
                "emergency", SPECIAL_EMERGENCY_TARGET,
251
                "-b",        SPECIAL_EMERGENCY_TARGET,
252 253 254 255 256 257 258 259 260
                "single",    SPECIAL_RESCUE_TARGET,
                "-s",        SPECIAL_RESCUE_TARGET,
                "s",         SPECIAL_RESCUE_TARGET,
                "S",         SPECIAL_RESCUE_TARGET,
                "1",         SPECIAL_RESCUE_TARGET,
                "2",         SPECIAL_RUNLEVEL2_TARGET,
                "3",         SPECIAL_RUNLEVEL3_TARGET,
                "4",         SPECIAL_RUNLEVEL4_TARGET,
                "5",         SPECIAL_RUNLEVEL5_TARGET,
261 262
        };

263 264
        assert(word);

265 266 267 268 269 270 271 272 273
        if (startswith(word, "systemd.unit=")) {

                if (!in_initrd())
                        return set_default_unit(word + 13);

        } else if (startswith(word, "rd.systemd.unit=")) {

                if (in_initrd())
                        return set_default_unit(word + 16);
274

275
        } else if (startswith(word, "systemd.log_target=")) {
276 277 278 279 280 281 282 283 284

                if (log_set_target_from_string(word + 19) < 0)
                        log_warning("Failed to parse log target %s. Ignoring.", word + 19);

        } else if (startswith(word, "systemd.log_level=")) {

                if (log_set_max_level_from_string(word + 18) < 0)
                        log_warning("Failed to parse log level %s. Ignoring.", word + 18);

285 286 287 288 289 290 291 292 293 294
        } else if (startswith(word, "systemd.log_color=")) {

                if (log_show_color_from_string(word + 18) < 0)
                        log_warning("Failed to parse log color setting %s. Ignoring.", word + 18);

        } else if (startswith(word, "systemd.log_location=")) {

                if (log_show_location_from_string(word + 21) < 0)
                        log_warning("Failed to parse log location setting %s. Ignoring.", word + 21);

295 296 297 298
        } else if (startswith(word, "systemd.dump_core=")) {
                int r;

                if ((r = parse_boolean(word + 18)) < 0)
Lennart Poettering's avatar
Lennart Poettering committed
299
                        log_warning("Failed to parse dump core switch %s. Ignoring.", word + 18);
300
                else
301
                        arg_dump_core = r;
302 303 304 305 306

        } else if (startswith(word, "systemd.crash_shell=")) {
                int r;

                if ((r = parse_boolean(word + 20)) < 0)
Lennart Poettering's avatar
Lennart Poettering committed
307
                        log_warning("Failed to parse crash shell switch %s. Ignoring.", word + 20);
308
                else
309
                        arg_crash_shell = r;
310 311 312 313 314

        } else if (startswith(word, "systemd.confirm_spawn=")) {
                int r;

                if ((r = parse_boolean(word + 22)) < 0)
Lennart Poettering's avatar
Lennart Poettering committed
315
                        log_warning("Failed to parse confirm spawn switch %s. Ignoring.", word + 22);
316
                else
317
                        arg_confirm_spawn = r;
318

319 320 321 322
        } else if (startswith(word, "systemd.crash_chvt=")) {
                int k;

                if (safe_atoi(word + 19, &k) < 0)
Lennart Poettering's avatar
Lennart Poettering committed
323
                        log_warning("Failed to parse crash chvt switch %s. Ignoring.", word + 19);
324
                else
325
                        arg_crash_chvt = k;
326

327 328 329 330
        } else if (startswith(word, "systemd.show_status=")) {
                int r;

                if ((r = parse_boolean(word + 20)) < 0)
Lennart Poettering's avatar
Lennart Poettering committed
331
                        log_warning("Failed to parse show status switch %s. Ignoring.", word + 20);
332
                else
333
                        arg_show_status = r;
334 335 336 337
        } else if (startswith(word, "systemd.default_standard_output=")) {
                int r;

                if ((r = exec_output_from_string(word + 32)) < 0)
Lennart Poettering's avatar
Lennart Poettering committed
338
                        log_warning("Failed to parse default standard output switch %s. Ignoring.", word + 32);
339 340 341 342 343 344
                else
                        arg_default_std_output = r;
        } else if (startswith(word, "systemd.default_standard_error=")) {
                int r;

                if ((r = exec_output_from_string(word + 31)) < 0)
Lennart Poettering's avatar
Lennart Poettering committed
345
                        log_warning("Failed to parse default standard error switch %s. Ignoring.", word + 31);
346 347
                else
                        arg_default_std_error = r;
348
        } else if (startswith(word, "systemd.setenv=")) {
349 350
                _cleanup_free_ char *cenv = NULL;
                char *eq;
351 352 353 354 355 356 357 358
                int r;

                cenv = strdup(word + 15);
                if (!cenv)
                        return -ENOMEM;

                eq = strchr(cenv, '=');
                if (!eq) {
359 360 361 362 363 364 365
                        if (!env_name_is_valid(cenv))
                                log_warning("Environment variable name '%s' is not valid. Ignoring.", cenv);
                        else  {
                                r = unsetenv(cenv);
                                if (r < 0)
                                        log_warning("Unsetting environment variable '%s' failed, ignoring: %m", cenv);
                        }
366
                } else {
367 368 369 370 371 372 373 374
                        if (!env_assignment_is_valid(cenv))
                                log_warning("Environment variable assignment '%s' is not valid. Ignoring.", cenv);
                        else {
                                *eq = 0;
                                r = setenv(cenv, eq + 1, 1);
                                if (r < 0)
                                        log_warning("Setting environment variable '%s=%s' failed, ignoring: %m", cenv, eq + 1);
                        }
375
                }
376

377 378
        } else if (startswith(word, "systemd.") ||
                   (in_initrd() && startswith(word, "rd.systemd."))) {
379

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
                const char *c;

                /* Ignore systemd.journald.xyz and friends */
                c = word;
                if (startswith(c, "rd."))
                        c += 3;
                if (startswith(c, "systemd."))
                        c += 8;
                if (c[strcspn(c, ".=")] != '.')  {

                        log_warning("Unknown kernel switch %s. Ignoring.", word);

                        log_info("Supported kernel switches:\n"
                                 "systemd.unit=UNIT                        Default unit to start\n"
                                 "rd.systemd.unit=UNIT                     Default unit to start when run in initrd\n"
                                 "systemd.dump_core=0|1                    Dump core on crash\n"
                                 "systemd.crash_shell=0|1                  Run shell on crash\n"
                                 "systemd.crash_chvt=N                     Change to VT #N on crash\n"
                                 "systemd.confirm_spawn=0|1                Confirm every process spawn\n"
                                 "systemd.show_status=0|1                  Show status updates on the console during bootup\n"
                                 "systemd.log_target=console|kmsg|journal|journal-or-kmsg|syslog|syslog-or-kmsg|null\n"
                                 "                                         Log target\n"
                                 "systemd.log_level=LEVEL                  Log level\n"
                                 "systemd.log_color=0|1                    Highlight important log messages\n"
                                 "systemd.log_location=0|1                 Include code location in log messages\n"
                                 "systemd.default_standard_output=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
                                 "                                         Set default log output for services\n"
                                 "systemd.default_standard_error=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
                                 "                                         Set default log error output for services\n"
                                 "systemd.setenv=ASSIGNMENT                Set an environment variable for all spawned processes\n");
                }
411

412
        } else if (streq(word, "quiet"))
413
                arg_show_status = false;
414
        else if (!in_initrd()) {
415 416 417 418 419 420 421 422 423 424 425
                unsigned i;

                /* SysV compatibility */
                for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
                        if (streq(word, rlmap[i]))
                                return set_default_unit(rlmap[i+1]);
        }

        return 0;
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
#define DEFINE_SETTER(name, func, descr)                              \
        static int name(const char *unit,                             \
                        const char *filename,                         \
                        unsigned line,                                \
                        const char *section,                          \
                        const char *lvalue,                           \
                        int ltype,                                    \
                        const char *rvalue,                           \
                        void *data,                                   \
                        void *userdata) {                             \
                                                                      \
                int r;                                                \
                                                                      \
                assert(filename);                                     \
                assert(lvalue);                                       \
                assert(rvalue);                                       \
                                                                      \
                r = func(rvalue);                                     \
                if (r < 0)                                            \
                        log_syntax(unit, LOG_ERR, filename, line, -r, \
                                   "Invalid " descr "'%s': %s",       \
                                   rvalue, strerror(-r));             \
                                                                      \
                return 0;                                             \
        }
451

452 453 454 455
DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level")
DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target")
DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" )
DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location")
456 457


458 459 460 461 462 463 464 465 466
static int config_parse_cpu_affinity2(const char *unit,
                                      const char *filename,
                                      unsigned line,
                                      const char *section,
                                      const char *lvalue,
                                      int ltype,
                                      const char *rvalue,
                                      void *data,
                                      void *userdata) {
467 468 469 470 471 472 473 474 475 476 477

        char *w;
        size_t l;
        char *state;
        cpu_set_t *c = NULL;
        unsigned ncpus = 0;

        assert(filename);
        assert(lvalue);
        assert(rvalue);

478
        FOREACH_WORD_QUOTED(w, l, rvalue, state) {
479 480 481 482 483
                char *t;
                int r;
                unsigned cpu;

                if (!(t = strndup(w, l)))
484
                        return log_oom();
485 486 487 488 489 490

                r = safe_atou(t, &cpu);
                free(t);

                if (!c)
                        if (!(c = cpu_set_malloc(&ncpus)))
491
                                return log_oom();
492 493

                if (r < 0 || cpu >= ncpus) {
494 495
                        log_syntax(unit, LOG_ERR, filename, line, -r,
                                   "Failed to parse CPU affinity '%s'", rvalue);
496 497 498 499 500 501 502 503 504
                        CPU_FREE(c);
                        return -EBADMSG;
                }

                CPU_SET_S(cpu, CPU_ALLOC_SIZE(ncpus), c);
        }

        if (c) {
                if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
505
                        log_warning_unit(unit, "Failed to set CPU affinity: %m");
506 507 508 509 510 511 512

                CPU_FREE(c);
        }

        return 0;
}

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
static void strv_free_free(char ***l) {
        char ***i;

        if (!l)
                return;

        for (i = l; *i; i++)
                strv_free(*i);

        free(l);
}

static void free_join_controllers(void) {
        strv_free_free(arg_join_controllers);
        arg_join_controllers = NULL;
}

530 531 532 533 534 535 536 537 538
static int config_parse_join_controllers(const char *unit,
                                         const char *filename,
                                         unsigned line,
                                         const char *section,
                                         const char *lvalue,
                                         int ltype,
                                         const char *rvalue,
                                         void *data,
                                         void *userdata) {
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554

        unsigned n = 0;
        char *state, *w;
        size_t length;

        assert(filename);
        assert(lvalue);
        assert(rvalue);

        free_join_controllers();

        FOREACH_WORD_QUOTED(w, length, rvalue, state) {
                char *s, **l;

                s = strndup(w, length);
                if (!s)
555
                        return log_oom();
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

                l = strv_split(s, ",");
                free(s);

                strv_uniq(l);

                if (strv_length(l) <= 1) {
                        strv_free(l);
                        continue;
                }

                if (!arg_join_controllers) {
                        arg_join_controllers = new(char**, 2);
                        if (!arg_join_controllers) {
                                strv_free(l);
571
                                return log_oom();
572 573 574 575 576 577 578 579 580 581 582 583 584
                        }

                        arg_join_controllers[0] = l;
                        arg_join_controllers[1] = NULL;

                        n = 1;
                } else {
                        char ***a;
                        char ***t;

                        t = new0(char**, n+2);
                        if (!t) {
                                strv_free(l);
585
                                return log_oom();
586 587 588 589 590 591 592 593 594 595 596 597 598
                        }

                        n = 0;

                        for (a = arg_join_controllers; *a; a++) {

                                if (strv_overlap(*a, l)) {
                                        char **c;

                                        c = strv_merge(*a, l);
                                        if (!c) {
                                                strv_free(l);
                                                strv_free_free(t);
599
                                                return log_oom();
600 601 602 603 604 605 606 607 608 609 610
                                        }

                                        strv_free(l);
                                        l = c;
                                } else {
                                        char **c;

                                        c = strv_copy(*a);
                                        if (!c) {
                                                strv_free(l);
                                                strv_free_free(t);
611
                                                return log_oom();
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
                                        }

                                        t[n++] = c;
                                }
                        }

                        t[n++] = strv_uniq(l);

                        strv_free_free(arg_join_controllers);
                        arg_join_controllers = t;
                }
        }

        return 0;
}

628 629
static int parse_config_file(void) {

630 631 632 633 634 635 636 637 638 639 640 641 642
        const ConfigTableItem items[] = {
                { "Manager", "LogLevel",              config_parse_level2,       0, NULL                     },
                { "Manager", "LogTarget",             config_parse_target,       0, NULL                     },
                { "Manager", "LogColor",              config_parse_color,        0, NULL                     },
                { "Manager", "LogLocation",           config_parse_location,     0, NULL                     },
                { "Manager", "DumpCore",              config_parse_bool,         0, &arg_dump_core           },
                { "Manager", "CrashShell",            config_parse_bool,         0, &arg_crash_shell         },
                { "Manager", "ShowStatus",            config_parse_bool,         0, &arg_show_status         },
                { "Manager", "CrashChVT",             config_parse_int,          0, &arg_crash_chvt          },
                { "Manager", "CPUAffinity",           config_parse_cpu_affinity2, 0, NULL                    },
                { "Manager", "DefaultControllers",    config_parse_strv,         0, &arg_default_controllers },
                { "Manager", "DefaultStandardOutput", config_parse_output,       0, &arg_default_std_output  },
                { "Manager", "DefaultStandardError",  config_parse_output,       0, &arg_default_std_error   },
643
                { "Manager", "JoinControllers",       config_parse_join_controllers, 0, &arg_join_controllers },
644 645
                { "Manager", "RuntimeWatchdogSec",    config_parse_sec,          0, &arg_runtime_watchdog    },
                { "Manager", "ShutdownWatchdogSec",   config_parse_sec,          0, &arg_shutdown_watchdog   },
646
                { "Manager", "CapabilityBoundingSet", config_parse_bounding_set, 0, &arg_capability_bounding_set_drop },
647
                { "Manager", "TimerSlackNSec",        config_parse_nsec,         0, &arg_timer_slack_nsec    },
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
                { "Manager", "DefaultLimitCPU",       config_parse_limit,        0, &arg_default_rlimit[RLIMIT_CPU]},
                { "Manager", "DefaultLimitFSIZE",     config_parse_limit,        0, &arg_default_rlimit[RLIMIT_FSIZE]},
                { "Manager", "DefaultLimitDATA",      config_parse_limit,        0, &arg_default_rlimit[RLIMIT_DATA]},
                { "Manager", "DefaultLimitSTACK",     config_parse_limit,        0, &arg_default_rlimit[RLIMIT_STACK]},
                { "Manager", "DefaultLimitCORE",      config_parse_limit,        0, &arg_default_rlimit[RLIMIT_CORE]},
                { "Manager", "DefaultLimitRSS",       config_parse_limit,        0, &arg_default_rlimit[RLIMIT_RSS]},
                { "Manager", "DefaultLimitNOFILE",    config_parse_limit,        0, &arg_default_rlimit[RLIMIT_NOFILE]},
                { "Manager", "DefaultLimitAS",        config_parse_limit,        0, &arg_default_rlimit[RLIMIT_AS]},
                { "Manager", "DefaultLimitNPROC",     config_parse_limit,        0, &arg_default_rlimit[RLIMIT_NPROC]},
                { "Manager", "DefaultLimitMEMLOCK",   config_parse_limit,        0, &arg_default_rlimit[RLIMIT_MEMLOCK]},
                { "Manager", "DefaultLimitLOCKS",     config_parse_limit,        0, &arg_default_rlimit[RLIMIT_LOCKS]},
                { "Manager", "DefaultLimitSIGPENDING",config_parse_limit,        0, &arg_default_rlimit[RLIMIT_SIGPENDING]},
                { "Manager", "DefaultLimitMSGQUEUE",  config_parse_limit,        0, &arg_default_rlimit[RLIMIT_MSGQUEUE]},
                { "Manager", "DefaultLimitNICE",      config_parse_limit,        0, &arg_default_rlimit[RLIMIT_NICE]},
                { "Manager", "DefaultLimitRTPRIO",    config_parse_limit,        0, &arg_default_rlimit[RLIMIT_RTPRIO]},
                { "Manager", "DefaultLimitRTTIME",    config_parse_limit,        0, &arg_default_rlimit[RLIMIT_RTTIME]},
664
                { NULL, NULL, NULL, 0, NULL }
665 666
        };

667
        _cleanup_fclose_ FILE *f;
668 669 670
        const char *fn;
        int r;

671
        fn = arg_running_as == SYSTEMD_SYSTEM ? PKGSYSCONFDIR "/system.conf" : PKGSYSCONFDIR "/user.conf";
672 673
        f = fopen(fn, "re");
        if (!f) {
674 675 676 677 678 679 680
                if (errno == ENOENT)
                        return 0;

                log_warning("Failed to open configuration file '%s': %m", fn);
                return 0;
        }

681
        r = config_parse(NULL, fn, f, "Manager\0", config_item_table_lookup, (void*) items, false, false, NULL);
682
        if (r < 0)
683 684 685 686 687
                log_warning("Failed to parse configuration file: %s", strerror(-r));

        return 0;
}

688
static int parse_proc_cmdline(void) {
689
        _cleanup_free_ char *line = NULL;
690
        char *w, *state;
691 692 693
        int r;
        size_t l;

694 695 696 697 698
        /* Don't read /proc/cmdline if we are in a container, since
         * that is only relevant for the host system */
        if (detect_container(NULL) > 0)
                return 0;

699 700
        r = read_one_line_file("/proc/cmdline", &line);
        if (r < 0) {
701
                log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
702 703 704 705
                return 0;
        }

        FOREACH_WORD_QUOTED(w, l, line, state) {
706
                _cleanup_free_ char *word;
707

708 709 710
                word = strndup(w, l);
                if (!word)
                        return log_oom();
711 712

                r = parse_proc_cmdline_word(word);
713 714
                if (r < 0) {
                        log_error("Failed on cmdline argument %s: %s", word, strerror(-r));
715
                        return r;
716
                }
717 718
        }

719
        return 0;
720 721 722 723 724 725 726
}

static int parse_argv(int argc, char *argv[]) {

        enum {
                ARG_LOG_LEVEL = 0x100,
                ARG_LOG_TARGET,
727 728
                ARG_LOG_COLOR,
                ARG_LOG_LOCATION,
729
                ARG_UNIT,
730
                ARG_SYSTEM,
731
                ARG_USER,
732
                ARG_TEST,
733
                ARG_VERSION,
Lennart Poettering's avatar
Lennart Poettering committed
734
                ARG_DUMP_CONFIGURATION_ITEMS,
735 736
                ARG_DUMP_CORE,
                ARG_CRASH_SHELL,
737
                ARG_CONFIRM_SPAWN,
738
                ARG_SHOW_STATUS,
739
                ARG_DESERIALIZE,
740
                ARG_SWITCHED_ROOT,
741 742 743
                ARG_INTROSPECT,
                ARG_DEFAULT_STD_OUTPUT,
                ARG_DEFAULT_STD_ERROR
744 745 746
        };

        static const struct option options[] = {
747 748
                { "log-level",                required_argument, NULL, ARG_LOG_LEVEL                },
                { "log-target",               required_argument, NULL, ARG_LOG_TARGET               },
749 750
                { "log-color",                optional_argument, NULL, ARG_LOG_COLOR                },
                { "log-location",             optional_argument, NULL, ARG_LOG_LOCATION             },
751
                { "unit",                     required_argument, NULL, ARG_UNIT                     },
752
                { "system",                   no_argument,       NULL, ARG_SYSTEM                   },
753
                { "user",                     no_argument,       NULL, ARG_USER                     },
754 755
                { "test",                     no_argument,       NULL, ARG_TEST                     },
                { "help",                     no_argument,       NULL, 'h'                          },
756
                { "version",                  no_argument,       NULL, ARG_VERSION                  },
757
                { "dump-configuration-items", no_argument,       NULL, ARG_DUMP_CONFIGURATION_ITEMS },
758 759 760
                { "dump-core",                optional_argument, NULL, ARG_DUMP_CORE                },
                { "crash-shell",              optional_argument, NULL, ARG_CRASH_SHELL              },
                { "confirm-spawn",            optional_argument, NULL, ARG_CONFIRM_SPAWN            },
761
                { "show-status",              optional_argument, NULL, ARG_SHOW_STATUS              },
762
                { "deserialize",              required_argument, NULL, ARG_DESERIALIZE              },
763
                { "switched-root",            no_argument,       NULL, ARG_SWITCHED_ROOT            },
764
                { "introspect",               optional_argument, NULL, ARG_INTROSPECT               },
765 766
                { "default-standard-output",  required_argument, NULL, ARG_DEFAULT_STD_OUTPUT,      },
                { "default-standard-error",   required_argument, NULL, ARG_DEFAULT_STD_ERROR,       },
767
                { NULL,                       0,                 NULL, 0                            }
768 769 770 771 772 773 774
        };

        int c, r;

        assert(argc >= 1);
        assert(argv);

775 776 777
        if (getpid() == 1)
                opterr = 0;

778
        while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798

                switch (c) {

                case ARG_LOG_LEVEL:
                        if ((r = log_set_max_level_from_string(optarg)) < 0) {
                                log_error("Failed to parse log level %s.", optarg);
                                return r;
                        }

                        break;

                case ARG_LOG_TARGET:

                        if ((r = log_set_target_from_string(optarg)) < 0) {
                                log_error("Failed to parse log target %s.", optarg);
                                return r;
                        }

                        break;

799 800
                case ARG_LOG_COLOR:

801 802 803 804 805 806 807
                        if (optarg) {
                                if ((r = log_show_color_from_string(optarg)) < 0) {
                                        log_error("Failed to parse log color setting %s.", optarg);
                                        return r;
                                }
                        } else
                                log_show_color(true);
808 809 810 811 812

                        break;

                case ARG_LOG_LOCATION:

813 814 815 816 817 818 819
                        if (optarg) {
                                if ((r = log_show_location_from_string(optarg)) < 0) {
                                        log_error("Failed to parse log location setting %s.", optarg);
                                        return r;
                                }
                        } else
                                log_show_location(true);
820 821 822

                        break;

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
                case ARG_DEFAULT_STD_OUTPUT:

                        if ((r = exec_output_from_string(optarg)) < 0) {
                                log_error("Failed to parse default standard output setting %s.", optarg);
                                return r;
                        } else
                                arg_default_std_output = r;
                        break;

                case ARG_DEFAULT_STD_ERROR:

                        if ((r = exec_output_from_string(optarg)) < 0) {
                                log_error("Failed to parse default standard error output setting %s.", optarg);
                                return r;
                        } else
                                arg_default_std_error = r;
                        break;

841
                case ARG_UNIT:
842 843 844 845 846 847 848 849

                        if ((r = set_default_unit(optarg)) < 0) {
                                log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
                                return r;
                        }

                        break;

850
                case ARG_SYSTEM:
851
                        arg_running_as = SYSTEMD_SYSTEM;
852
                        break;
853

854
                case ARG_USER:
855
                        arg_running_as = SYSTEMD_USER;
856 857
                        break;

Lennart Poettering's avatar
Lennart Poettering committed
858
                case ARG_TEST:
859
                        arg_action = ACTION_TEST;
Lennart Poettering's avatar
Lennart Poettering committed
860 861
                        break;

862 863 864 865
                case ARG_VERSION:
                        arg_action = ACTION_VERSION;
                        break;

866
                case ARG_DUMP_CONFIGURATION_ITEMS:
867
                        arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
868 869
                        break;

870
                case ARG_DUMP_CORE:
871 872 873 874 875 876
                        r = optarg ? parse_boolean(optarg) : 1;
                        if (r < 0) {
                                log_error("Failed to parse dump core boolean %s.", optarg);
                                return r;
                        }
                        arg_dump_core = r;
877 878 879
                        break;

                case ARG_CRASH_SHELL:
880 881 882 883 884 885
                        r = optarg ? parse_boolean(optarg) : 1;
                        if (r < 0) {
                                log_error("Failed to parse crash shell boolean %s.", optarg);
                                return r;
                        }
                        arg_crash_shell = r;
886 887
                        break;

Lennart Poettering's avatar
Lennart Poettering committed
888
                case ARG_CONFIRM_SPAWN:
889 890 891 892 893 894
                        r = optarg ? parse_boolean(optarg) : 1;
                        if (r < 0) {
                                log_error("Failed to parse confirm spawn boolean %s.", optarg);
                                return r;
                        }
                        arg_confirm_spawn = r;
Lennart Poettering's avatar
Lennart Poettering committed
895 896
                        break;

897
                case ARG_SHOW_STATUS:
898 899 900 901 902 903
                        r = optarg ? parse_boolean(optarg) : 1;
                        if (r < 0) {
                                log_error("Failed to parse show status boolean %s.", optarg);
                                return r;
                        }
                        arg_show_status = r;
904
                        break;
905

906 907 908 909
                case ARG_DESERIALIZE: {
                        int fd;
                        FILE *f;

910 911
                        r = safe_atoi(optarg, &fd);
                        if (r < 0 || fd < 0) {
912
                                log_error("Failed to parse deserialize option %s.", optarg);
913
                                return r < 0 ? r : -EINVAL;
914 915
                        }

916 917 918 919
                        fd_cloexec(fd, true);

                        f = fdopen(fd, "r");
                        if (!f) {
920
                                log_error("Failed to open serialization fd: %m");
921
                                return -errno;
922 923 924 925 926 927 928 929 930 931
                        }

                        if (serialization)
                                fclose(serialization);

                        serialization = f;

                        break;
                }

932
                case ARG_SWITCHED_ROOT:
933
                        arg_switched_root = true;
934 935
                        break;

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
                case ARG_INTROSPECT: {
                        const char * const * i = NULL;

                        for (i = bus_interface_table; *i; i += 2)
                                if (!optarg || streq(i[0], optarg)) {
                                        fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
                                              "<node>\n", stdout);
                                        fputs(i[1], stdout);
                                        fputs("</node>\n", stdout);

                                        if (optarg)
                                                break;
                                }

                        if (!i[0] && optarg)
                                log_error("Unknown interface %s.", optarg);

953
                        arg_action = ACTION_DONE;
954 955 956
                        break;
                }

957
                case 'h':
958
                        arg_action = ACTION_HELP;
959 960
                        break;

961 962 963 964
                case 'D':
                        log_set_max_level(LOG_DEBUG);
                        break;

965 966 967 968 969 970 971
                case 'b':
                case 's':
                case 'z':
                        /* Just to eat away the sysvinit kernel
                         * cmdline args without getopt() error
                         * messages that we'll parse in
                         * parse_proc_cmdline_word() or ignore. */
972

973
                case '?':
974
                default:
975 976 977 978 979 980
                        if (getpid() != 1) {
                                log_error("Unknown option code %c", c);
                                return -EINVAL;
                        }

                        break;
981 982
                }

983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        if (optind < argc && getpid() != 1) {
                /* Hmm, when we aren't run as init system
                 * let's complain about excess arguments */

                log_error("Excess arguments.");
                return -EINVAL;
        }

        if (detect_container(NULL) > 0) {
                char **a;

                /* All /proc/cmdline arguments the kernel didn't
                 * understand it passed to us. We're not really
                 * interested in that usually since /proc/cmdline is
                 * more interesting and complete. With one exception:
                 * if we are run in a container /proc/cmdline is not
                 * relevant for the container, hence we rely on argv[]
                 * instead. */

                for (a = argv; a < argv + argc; a++)
1003 1004
                        if ((r = parse_proc_cmdline_word(*a)) < 0) {
                                log_error("Failed on cmdline argument %s: %s", *a, strerror(-r));
1005
                                return r;
1006
                        }
1007 1008
        }

1009 1010 1011 1012 1013
        return 0;
}

static int help(void) {

Lennart Poettering's avatar
Lennart Poettering committed
1014
        printf("%s [OPTIONS...]\n\n"
1015
               "Starts up and maintains the system or user services.\n\n"
1016 1017
               "  -h --help                      Show this help\n"
               "     --test                      Determine startup sequence, dump it and exit\n"
Lennart Poettering's avatar
Lennart Poettering committed
1018
               "     --dump-configuration-items  Dump understood unit configuration items\n"
1019
               "     --introspect[=INTERFACE]    Extract D-Bus interface data\n"
1020
               "     --unit=UNIT                 Set default unit\n"
1021
               "     --system                    Run a system instance, even if PID != 1\n"
1022
               "     --user                      Run a user instance\n"
1023 1024 1025
               "     --dump-core[=0|1]           Dump core on crash\n"
               "     --crash-shell[=0|1]         Run shell on crash\n"
               "     --confirm-spawn[=0|1]       Ask for confirmation when spawning processes\n"
1026
               "     --show-status[=0|1]         Show status updates on the console during bootup\n"
1027
               "     --log-target=TARGET         Set log target (console, journal, syslog, kmsg, journal-or-kmsg, syslog-or-kmsg, null)\n"
1028
               "     --log-level=LEVEL           Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1029
               "     --log-color[=0|1]           Highlight important log messages\n"
1030 1031 1032
               "     --log-location[=0|1]        Include code location in log messages\n"
               "     --default-standard-output=  Set default standard output for services\n"
               "     --default-standard-error=   Set default standard error output for services\n",
1033
               program_invocation_short_name);
1034 1035 1036 1037

        return 0;
}

1038 1039 1040 1041 1042 1043 1044
static int version(void) {
        puts(PACKAGE_STRING);
        puts(SYSTEMD_FEATURES);

        return 0;
}

1045
static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds, bool switching_root) {
1046 1047 1048 1049 1050 1051 1052 1053
        FILE *f = NULL;
        FDSet *fds = NULL;
        int r;

        assert(m);
        assert(_f);
        assert(_fds);

1054 1055 1056
        /* Make sure nothing is really destructed when we shut down */
        m->n_reloading ++;

1057 1058
        r = manager_open_serialization(m, &f);
        if (r < 0) {
Harald Hoyer's avatar
Harald Hoyer committed
1059
                log_error("Failed to create serialization file: %s", strerror(-r));
1060 1061 1062
                goto fail;
        }

1063 1064
        fds = fdset_new();
        if (!fds) {
1065 1066 1067 1068 1069
                r = -ENOMEM;
                log_error("Failed to allocate fd set: %s", strerror(-r));
                goto fail;
        }

1070
        r = manager_serialize(m, f, fds, switching_root);
1071
        if (r < 0) {
1072 1073 1074 1075 1076 1077 1078 1079 1080
                log_error("Failed to serialize state: %s", strerror(-r));
                goto fail;
        }

        if (fseeko(f, 0, SEEK_SET) < 0) {
                log_error("Failed to rewind serialization fd: %m");
                goto fail;
        }

1081 1082
        r = fd_cloexec(fileno(f), false);
        if (r < 0) {
1083 1084 1085 1086
                log_error("Failed to disable O_CLOEXEC for serialization: %s", strerror(-r));
                goto fail;
        }

1087 1088
        r = fdset_cloexec(fds, false);
        if (r < 0) {
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
                log_error("Failed to disable O_CLOEXEC for serialization fds: %s", strerror(-r));
                goto fail;
        }

        *_f = f;
        *_fds = fds;

        return 0;

fail:
        fdset_free(fds);

        if (f)
                fclose(f);

        return r;
}

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
        struct rlimit nl;
        int r;

        assert(saved_rlimit);

        /* Save the original RLIMIT_NOFILE so that we can reset it
         * later when transitioning from the initrd to the main
         * systemd or suchlike. */
        if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0) {
                log_error("Reading RLIMIT_NOFILE failed: %m");
                return -errno;
        }

        /* Make sure forked processes get the default kernel setting */
        if (!arg_default_rlimit[RLIMIT_NOFILE]) {
                struct rlimit *rl;

                rl = newdup(struct rlimit, saved_rlimit, 1);
                if (!rl)
                        return log_oom();

                arg_default_rlimit[RLIMIT_NOFILE] = rl;
        }

        /* Bump up the resource limit for ourselves substantially */
        nl.rlim_cur = nl.rlim_max = 64*1024;
        r = setrlimit_closest(RLIMIT_NOFILE, &nl);
        if (r < 0) {
                log_error("Setting RLIMIT_NOFILE failed: %s", strerror(-r));
                return r;
        }

        return 0;
}

1143 1144 1145 1146 1147 1148
static struct dual_timestamp* parse_initrd_timestamp(struct dual_timestamp *t) {
        const char *e;
        unsigned long long a, b;

        assert(t);

1149 1150
        e = getenv("RD_TIMESTAMP");
        if (!e)
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
                return NULL;

        if (sscanf(e, "%llu %llu", &a, &b) != 2)
                return NULL;

        t->realtime = (usec_t) a;
        t->monotonic = (usec_t) b;

        return t;
}

1162 1163 1164
static void test_mtab(void) {
        char *p;

1165 1166
        /* Check that /etc/mtab is a symlink */

1167 1168 1169
        if (readlink_malloc("/etc/mtab", &p) >= 0) {
                bool b;

1170
                b = streq(p, "/proc/self/mounts") || streq(p, "/proc/mounts");
1171 1172 1173 1174 1175 1176
                free(p);

                if (b)
                        return;
        }

1177 1178 1179 1180 1181 1182 1183
        log_warning("/etc/mtab is not a symlink or not pointing to /proc/self/mounts. "
                    "This is not supported anymore. "
                    "Please make sure to replace this file by a symlink to avoid incorrect or misleading mount(8) output.");
}

static void test_usr(void) {

Lennart Poettering's avatar
Lennart Poettering committed
1184
        /* Check that /usr is not a separate fs */
1185

1186 1187 1188
        if (dir_is_empty("/usr") <= 0)
                return;

Kay Sievers's avatar
Kay Sievers committed
1189
        log_warning("/usr appears to be on its own filesytem and is not already mounted. This is not a supported setup. "
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
                    "Some things will probably break (sometimes even silently) in mysterious ways. "
                    "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
}

static void test_cgroups(void) {

        if (access("/proc/cgroups", F_OK) >= 0)
                return;

        log_warning("CONFIG_CGROUPS was not set when your kernel was compiled. "
                    "Systems without control groups are not supported. "
                    "We will now sleep for 10s, and then continue boot-up. "
                    "Expect breakage and please do not file bugs. "
1203 1204
                    "Instead fix your kernel and enable CONFIG_CGROUPS. "
                    "Consult http://0pointer.de/blog/projects/cgroups-vs-cgroups.html for more information.");
1205 1206

        sleep(10);
1207 1208
}

1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
static int initialize_join_controllers(void) {
        /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
         * + "net_prio". We'd like to add "cpuset" to the mix, but
         * "cpuset" does't really work for groups with no initialized
         * attributes. */

        arg_join_controllers = new(char**, 3);
        if (!arg_join_controllers)
                return -ENOMEM;

        arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
        arg_join_controllers[1] = strv_new("net_cls", "net_prio", NULL);
Zbigniew Jędrzejewski-Szmek's avatar
Zbigniew Jędrzejewski-Szmek committed
1221 1222 1223 1224
        arg_join_controllers[2] = NULL;

        if (!arg_join_controllers[0] || !arg_join_controllers[1]) {
                free_join_controllers();
1225
                return -ENOMEM;
Zbigniew Jędrzejewski-Szmek's avatar
Zbigniew Jędrzejewski-Szmek committed
1226
        }
1227 1228 1229 1230

        return 0;
}

Lennart Poettering's avatar
Lennart Poettering committed
1231 1232
int main(int argc, char *argv[]) {
        Manager *m = NULL;
1233
        int r, retval = EXIT_FAILURE;
1234 1235
        usec_t before_startup, after_startup;
        char timespan[FORMAT_TIMESPAN_MAX];
1236 1237
        FDSet *fds = NULL;
        bool reexecute = false;
1238
        const char *shutdown_verb = NULL;
1239
        dual_timestamp initrd_timestamp = { 0ULL, 0ULL };
1240 1241 1242 1243
        dual_timestamp userspace_timestamp = { 0ULL, 0ULL };
        dual_timestamp kernel_timestamp = { 0ULL, 0ULL };
        dual_timestamp firmware_timestamp = { 0ULL, 0ULL };
        dual_timestamp loader_timestamp = { 0ULL, 0ULL };
1244
        static char systemd[] = "systemd";
Lennart Poettering's avatar