main.c 49.8 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 9 10 11 12 13 14 15 16 17 18 19 20 21
/***
  This file is part of systemd.

  Copyright 2010 Lennart Poettering

  systemd is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (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
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  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>
Lennart Poettering's avatar
Lennart Poettering committed
35 36

#include "manager.h"
37
#include "log.h"
38
#include "mount-setup.h"
39
#include "hostname-setup.h"
40
#include "loopback-setup.h"
41
#include "kmod-setup.h"
42
#include "locale-setup.h"
43
#include "selinux-setup.h"
44
#include "machine-id-setup.h"
45
#include "load-fragment.h"
46
#include "fdset.h"
47
#include "special.h"
48
#include "conf-parser.h"
49
#include "bus-errors.h"
50
#include "missing.h"
51
#include "label.h"
52
#include "build.h"
53
#include "strv.h"
54
#include "def.h"
Lennart Poettering's avatar
Lennart Poettering committed
55

56 57
static enum {
        ACTION_RUN,
Lennart Poettering's avatar
Lennart Poettering committed
58
        ACTION_HELP,
59
        ACTION_TEST,
60 61
        ACTION_DUMP_CONFIGURATION_ITEMS,
        ACTION_DONE
62
} arg_action = ACTION_RUN;
63

64 65 66 67 68 69 70
static char *arg_default_unit = NULL;
static ManagerRunningAs arg_running_as = _MANAGER_RUNNING_AS_INVALID;

static bool arg_dump_core = true;
static bool arg_crash_shell = false;
static int arg_crash_chvt = -1;
static bool arg_confirm_spawn = false;
71
static bool arg_show_status = true;
72
#ifdef HAVE_SYSV_COMPAT
73
static bool arg_sysv_console = true;
74
#endif
75
static bool arg_mount_auto = true;
76
static bool arg_swap_auto = true;
77
static char **arg_default_controllers = NULL;
78
static ExecOutput arg_default_std_output = EXEC_OUTPUT_INHERIT;
79
static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
80

81
static FILE* serialization = NULL;
Lennart Poettering's avatar
Lennart Poettering committed
82

83 84 85
static void nop_handler(int sig) {
}

86
_noreturn_ static void crash(int sig) {
87

88
        if (!arg_dump_core)
89
                log_error("Caught <%s>, not dumping core.", signal_to_string(sig));
90
        else {
91
                struct sigaction sa;
92 93
                pid_t pid;

94 95 96 97 98 99
                /* We want to wait for the core process, hence let's enable SIGCHLD */
                zero(sa);
                sa.sa_handler = nop_handler;
                sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
                assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);

100
                if ((pid = fork()) < 0)
101
                        log_error("Caught <%s>, cannot fork for core dump: %s", signal_to_string(sig), strerror(errno));
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

                else if (pid == 0) {
                        struct rlimit rl;

                        /* 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 */
                        zero(rl);
                        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);
125 126

                } else {
127 128
                        siginfo_t status;
                        int r;
129 130

                        /* Order things nicely. */
131 132 133
                        if ((r = wait_for_terminate(pid, &status)) < 0)
                                log_error("Caught <%s>, waitpid() failed: %s", signal_to_string(sig), strerror(-r));
                        else if (status.si_code != CLD_DUMPED)
134
                                log_error("Caught <%s>, core dump failed.", signal_to_string(sig));
135
                        else
136
                                log_error("Caught <%s>, dumped core as pid %lu.", signal_to_string(sig), (unsigned long) pid);
137 138 139
                }
        }

140 141
        if (arg_crash_chvt)
                chvt(arg_crash_chvt);
142

143
        if (arg_crash_shell) {
144 145
                struct sigaction sa;
                pid_t pid;
146

147 148 149
                log_info("Executing crash shell in 10s...");
                sleep(10);

150 151 152 153 154
                /* Let the kernel reap children for us */
                zero(sa);
                sa.sa_handler = SIG_IGN;
                sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART;
                assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
155

156 157 158
                if ((pid = fork()) < 0)
                        log_error("Failed to fork off crash shell: %s", strerror(errno));
                else if (pid == 0) {
159
                        int fd, r;
160

161
                        if ((fd = acquire_terminal("/dev/console", false, true, true)) < 0)
162
                                log_error("Failed to acquire terminal: %s", strerror(-fd));
163
                        else if ((r = make_stdio(fd)) < 0)
164
                                log_error("Failed to duplicate terminal fd: %s", strerror(-r));
165

166 167 168 169 170
                        execl("/bin/sh", "/bin/sh", NULL);

                        log_error("execl() failed: %s", strerror(errno));
                        _exit(1);
                }
171

172
                log_info("Successfully spawned crash shall as pid %lu.", (unsigned long) pid);
173 174 175
        }

        log_info("Freezing execution.");
176 177 178 179 180 181 182 183 184 185 186
        freeze();
}

static void install_crash_handler(void) {
        struct sigaction sa;

        zero(sa);

        sa.sa_handler = crash;
        sa.sa_flags = SA_NODEFER;

Lennart Poettering's avatar
Lennart Poettering committed
187
        sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
188
}
189

190 191
static int console_setup(bool do_reset) {
        int tty_fd, r;
Lennart Poettering's avatar
Lennart Poettering committed
192

193 194
        /* 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
195

196 197 198 199
        release_terminal();

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

201 202 203 204
        if ((tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0) {
                log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
                return -tty_fd;
        }
Lennart Poettering's avatar
Lennart Poettering committed
205

206 207 208 209
        if ((r = reset_terminal(tty_fd)) < 0)
                log_error("Failed to reset /dev/console: %s", strerror(-r));

        close_nointr_nofail(tty_fd);
Lennart Poettering's avatar
Lennart Poettering committed
210 211 212
        return r;
}

213 214 215 216 217 218 219 220
static int set_default_unit(const char *u) {
        char *c;

        assert(u);

        if (!(c = strdup(u)))
                return -ENOMEM;

221 222
        free(arg_default_unit);
        arg_default_unit = c;
223 224 225 226 227 228
        return 0;
}

static int parse_proc_cmdline_word(const char *word) {

        static const char * const rlmap[] = {
229
                "emergency", SPECIAL_EMERGENCY_TARGET,
230
                "-b",        SPECIAL_EMERGENCY_TARGET,
231 232 233 234 235 236 237 238 239
                "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,
240 241
        };

242 243
        assert(word);

244 245
        if (startswith(word, "systemd.unit="))
                return set_default_unit(word + 13);
246 247 248 249 250 251 252 253 254 255 256

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

                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);

257 258 259 260 261 262 263 264 265 266
        } 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);

267 268 269 270
        } else if (startswith(word, "systemd.dump_core=")) {
                int r;

                if ((r = parse_boolean(word + 18)) < 0)
271
                        log_warning("Failed to parse dump core switch %s, Ignoring.", word + 18);
272
                else
273
                        arg_dump_core = r;
274 275 276 277 278

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

                if ((r = parse_boolean(word + 20)) < 0)
279
                        log_warning("Failed to parse crash shell switch %s, Ignoring.", word + 20);
280
                else
281
                        arg_crash_shell = r;
282 283 284 285 286 287 288

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

                if ((r = parse_boolean(word + 22)) < 0)
                        log_warning("Failed to parse confirm spawn switch %s, Ignoring.", word + 22);
                else
289
                        arg_confirm_spawn = r;
290

291 292 293 294 295 296
        } else if (startswith(word, "systemd.crash_chvt=")) {
                int k;

                if (safe_atoi(word + 19, &k) < 0)
                        log_warning("Failed to parse crash chvt switch %s, Ignoring.", word + 19);
                else
297
                        arg_crash_chvt = k;
298

299 300 301 302 303
        } else if (startswith(word, "systemd.show_status=")) {
                int r;

                if ((r = parse_boolean(word + 20)) < 0)
                        log_warning("Failed to parse show status switch %s, Ignoring.", word + 20);
304
                else
305
                        arg_show_status = r;
306 307 308 309 310 311 312 313 314 315 316 317 318 319
        } else if (startswith(word, "systemd.default_standard_output=")) {
                int r;

                if ((r = exec_output_from_string(word + 32)) < 0)
                        log_warning("Failed to parse default standard output switch %s, Ignoring.", word + 32);
                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)
                        log_warning("Failed to parse default standard error switch %s, Ignoring.", word + 31);
                else
                        arg_default_std_error = r;
320
#ifdef HAVE_SYSV_COMPAT
321 322 323 324 325 326 327
        } else if (startswith(word, "systemd.sysv_console=")) {
                int r;

                if ((r = parse_boolean(word + 21)) < 0)
                        log_warning("Failed to parse SysV console switch %s, Ignoring.", word + 20);
                else
                        arg_sysv_console = r;
328
#endif
329

330 331 332 333
        } else if (startswith(word, "systemd.")) {

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

334 335 336
                log_info("Supported kernel switches:\n"
                         "systemd.unit=UNIT                        Default unit to start\n"
                         "systemd.dump_core=0|1                    Dump core on crash\n"
337
                         "systemd.crash_shell=0|1                  Run shell on crash\n"
338
                         "systemd.crash_chvt=N                     Change to VT #N on crash\n"
339
                         "systemd.confirm_spawn=0|1                Confirm every process spawn\n"
340
                         "systemd.show_status=0|1                  Show status updates on the console during bootup\n"
341
#ifdef HAVE_SYSV_COMPAT
342
                         "systemd.sysv_console=0|1                 Connect output of SysV scripts to console\n"
343
#endif
344
                         "systemd.log_target=console|kmsg|syslog|syslog-or-kmsg|null\n"
345 346 347
                         "                                         Log target\n"
                         "systemd.log_level=LEVEL                  Log level\n"
                         "systemd.log_color=0|1                    Highlight important log messages\n"
348 349 350 351 352
                         "systemd.log_location=0|1                 Include code location in log messages\n"
                         "systemd.default_standard_output=null|tty|syslog|syslog+console|kmsg|kmsg+console\n"
                         "                                         Set default log output for services\n"
                         "systemd.default_standard_error=null|tty|syslog|syslog+console|kmsg|kmsg+console\n"
                         "                                         Set default log error output for services\n");
353

354
        } else if (streq(word, "quiet")) {
355
                arg_show_status = false;
356
#ifdef HAVE_SYSV_COMPAT
357
                arg_sysv_console = false;
358
#endif
359
        } else {
360 361 362 363 364 365 366 367 368 369 370
                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;
}

371 372 373 374 375
static int config_parse_level(
                const char *filename,
                unsigned line,
                const char *section,
                const char *lvalue,
376
                int ltype,
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
                const char *rvalue,
                void *data,
                void *userdata) {

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

        log_set_max_level_from_string(rvalue);
        return 0;
}

static int config_parse_target(
                const char *filename,
                unsigned line,
                const char *section,
                const char *lvalue,
394
                int ltype,
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
                const char *rvalue,
                void *data,
                void *userdata) {

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

        log_set_target_from_string(rvalue);
        return 0;
}

static int config_parse_color(
                const char *filename,
                unsigned line,
                const char *section,
                const char *lvalue,
412
                int ltype,
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
                const char *rvalue,
                void *data,
                void *userdata) {

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

        log_show_color_from_string(rvalue);
        return 0;
}

static int config_parse_location(
                const char *filename,
                unsigned line,
                const char *section,
                const char *lvalue,
430
                int ltype,
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
                const char *rvalue,
                void *data,
                void *userdata) {

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

        log_show_location_from_string(rvalue);
        return 0;
}

static int config_parse_cpu_affinity(
                const char *filename,
                unsigned line,
                const char *section,
                const char *lvalue,
448
                int ltype,
449 450 451 452 453 454 455 456 457 458 459 460 461 462
                const char *rvalue,
                void *data,
                void *userdata) {

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

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

463
        FOREACH_WORD_QUOTED(w, l, rvalue, state) {
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
                char *t;
                int r;
                unsigned cpu;

                if (!(t = strndup(w, l)))
                        return -ENOMEM;

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

                if (!c)
                        if (!(c = cpu_set_malloc(&ncpus)))
                                return -ENOMEM;

                if (r < 0 || cpu >= ncpus) {
                        log_error("[%s:%u] Failed to parse CPU affinity: %s", filename, line, rvalue);
                        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)
                        log_warning("Failed to set CPU affinity: %m");

                CPU_FREE(c);
        }

        return 0;
}

497 498
static DEFINE_CONFIG_PARSE_ENUM(config_parse_output, exec_output, ExecOutput, "Failed to parse output specifier");

499 500 501
static int parse_config_file(void) {

        const ConfigItem items[] = {
Kay Sievers's avatar
Kay Sievers committed
502 503 504 505 506 507 508
                { "LogLevel",              config_parse_level,        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" },
509
#ifdef HAVE_SYSV_COMPAT
Kay Sievers's avatar
Kay Sievers committed
510
                { "SysVConsole",           config_parse_bool,         0, &arg_sysv_console,        "Manager" },
511
#endif
Kay Sievers's avatar
Kay Sievers committed
512 513 514 515 516 517 518 519
                { "CrashChVT",             config_parse_int,          0, &arg_crash_chvt,          "Manager" },
                { "CPUAffinity",           config_parse_cpu_affinity, 0, NULL,                     "Manager" },
                { "MountAuto",             config_parse_bool,         0, &arg_mount_auto,          "Manager" },
                { "SwapAuto",              config_parse_bool,         0, &arg_swap_auto,           "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,   "Manager" },
                { NULL, NULL, 0, NULL, NULL }
520 521 522 523 524 525 526 527 528 529 530
        };

        static const char * const sections[] = {
                "Manager",
                NULL
        };

        FILE *f;
        const char *fn;
        int r;

531
        fn = arg_running_as == MANAGER_SYSTEM ? SYSTEM_CONFIG_FILE : USER_CONFIG_FILE;
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

        if (!(f = fopen(fn, "re"))) {
                if (errno == ENOENT)
                        return 0;

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

        if ((r = config_parse(fn, f, sections, items, false, NULL)) < 0)
                log_warning("Failed to parse configuration file: %s", strerror(-r));

        fclose(f);

        return 0;
}

549
static int parse_proc_cmdline(void) {
550
        char *line, *w, *state;
551 552 553
        int r;
        size_t l;

554 555 556 557 558
        /* 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;

559
        if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
560
                log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
                return 0;
        }

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

                if (!(word = strndup(w, l))) {
                        r = -ENOMEM;
                        goto finish;
                }

                r = parse_proc_cmdline_word(word);
                free(word);

                if (r < 0)
                        goto finish;
        }

        r = 0;

finish:
        free(line);
        return r;
}

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

        enum {
                ARG_LOG_LEVEL = 0x100,
                ARG_LOG_TARGET,
591 592
                ARG_LOG_COLOR,
                ARG_LOG_LOCATION,
593
                ARG_UNIT,
594
                ARG_SYSTEM,
595
                ARG_USER,
596
                ARG_TEST,
Lennart Poettering's avatar
Lennart Poettering committed
597
                ARG_DUMP_CONFIGURATION_ITEMS,
598 599
                ARG_DUMP_CORE,
                ARG_CRASH_SHELL,
600
                ARG_CONFIRM_SPAWN,
601
                ARG_SHOW_STATUS,
602
                ARG_SYSV_CONSOLE,
603
                ARG_DESERIALIZE,
604 605 606
                ARG_INTROSPECT,
                ARG_DEFAULT_STD_OUTPUT,
                ARG_DEFAULT_STD_ERROR
607 608 609
        };

        static const struct option options[] = {
610 611
                { "log-level",                required_argument, NULL, ARG_LOG_LEVEL                },
                { "log-target",               required_argument, NULL, ARG_LOG_TARGET               },
612 613
                { "log-color",                optional_argument, NULL, ARG_LOG_COLOR                },
                { "log-location",             optional_argument, NULL, ARG_LOG_LOCATION             },
614
                { "unit",                     required_argument, NULL, ARG_UNIT                     },
615
                { "system",                   no_argument,       NULL, ARG_SYSTEM                   },
616
                { "user",                     no_argument,       NULL, ARG_USER                     },
617 618 619
                { "test",                     no_argument,       NULL, ARG_TEST                     },
                { "help",                     no_argument,       NULL, 'h'                          },
                { "dump-configuration-items", no_argument,       NULL, ARG_DUMP_CONFIGURATION_ITEMS },
620 621
                { "dump-core",                no_argument,       NULL, ARG_DUMP_CORE                },
                { "crash-shell",              no_argument,       NULL, ARG_CRASH_SHELL              },
622
                { "confirm-spawn",            no_argument,       NULL, ARG_CONFIRM_SPAWN            },
623
                { "show-status",              optional_argument, NULL, ARG_SHOW_STATUS              },
624
#ifdef HAVE_SYSV_COMPAT
625
                { "sysv-console",             optional_argument, NULL, ARG_SYSV_CONSOLE             },
626
#endif
627
                { "deserialize",              required_argument, NULL, ARG_DESERIALIZE              },
628
                { "introspect",               optional_argument, NULL, ARG_INTROSPECT               },
629 630
                { "default-standard-output",  required_argument, NULL, ARG_DEFAULT_STD_OUTPUT,      },
                { "default-standard-error",   required_argument, NULL, ARG_DEFAULT_STD_ERROR,       },
631
                { NULL,                       0,                 NULL, 0                            }
632 633 634 635 636 637 638
        };

        int c, r;

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

639 640 641
        if (getpid() == 1)
                opterr = 0;

642
        while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662

                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;

663 664
                case ARG_LOG_COLOR:

665 666 667 668 669 670 671
                        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);
672 673 674 675 676

                        break;

                case ARG_LOG_LOCATION:

677 678 679 680 681 682 683
                        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);
684 685 686

                        break;

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
                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;

705
                case ARG_UNIT:
706 707 708 709 710 711 712 713

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

                        break;

714 715 716
                case ARG_SYSTEM:
                        arg_running_as = MANAGER_SYSTEM;
                        break;
717

718 719
                case ARG_USER:
                        arg_running_as = MANAGER_USER;
720 721
                        break;

Lennart Poettering's avatar
Lennart Poettering committed
722
                case ARG_TEST:
723
                        arg_action = ACTION_TEST;
Lennart Poettering's avatar
Lennart Poettering committed
724 725
                        break;

726
                case ARG_DUMP_CONFIGURATION_ITEMS:
727
                        arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
728 729
                        break;

730 731 732 733 734 735 736 737
                case ARG_DUMP_CORE:
                        arg_dump_core = true;
                        break;

                case ARG_CRASH_SHELL:
                        arg_crash_shell = true;
                        break;

Lennart Poettering's avatar
Lennart Poettering committed
738
                case ARG_CONFIRM_SPAWN:
739
                        arg_confirm_spawn = true;
Lennart Poettering's avatar
Lennart Poettering committed
740 741
                        break;

742
                case ARG_SHOW_STATUS:
743 744 745 746 747 748 749 750 751 752

                        if (optarg) {
                                if ((r = parse_boolean(optarg)) < 0) {
                                        log_error("Failed to show status boolean %s.", optarg);
                                        return r;
                                }
                                arg_show_status = r;
                        } else
                                arg_show_status = true;
                        break;
753
#ifdef HAVE_SYSV_COMPAT
754 755 756 757 758 759 760 761 762 763
                case ARG_SYSV_CONSOLE:

                        if (optarg) {
                                if ((r = parse_boolean(optarg)) < 0) {
                                        log_error("Failed to SysV console boolean %s.", optarg);
                                        return r;
                                }
                                arg_sysv_console = r;
                        } else
                                arg_sysv_console = true;
764
                        break;
765
#endif
766

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
                case ARG_DESERIALIZE: {
                        int fd;
                        FILE *f;

                        if ((r = safe_atoi(optarg, &fd)) < 0 || fd < 0) {
                                log_error("Failed to parse deserialize option %s.", optarg);
                                return r;
                        }

                        if (!(f = fdopen(fd, "r"))) {
                                log_error("Failed to open serialization fd: %m");
                                return r;
                        }

                        if (serialization)
                                fclose(serialization);

                        serialization = f;

                        break;
                }

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
                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);

806
                        arg_action = ACTION_DONE;
807 808 809
                        break;
                }

810
                case 'h':
811
                        arg_action = ACTION_HELP;
812 813
                        break;

814 815 816 817
                case 'D':
                        log_set_max_level(LOG_DEBUG);
                        break;

818 819 820 821 822 823 824
                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. */
825

826
                case '?':
827
                default:
828 829 830 831 832 833
                        if (getpid() != 1) {
                                log_error("Unknown option code %c", c);
                                return -EINVAL;
                        }

                        break;
834 835
                }

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
        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++)
                        if ((r = parse_proc_cmdline_word(*a)) < 0)
                                return r;
858 859
        }

860 861 862 863 864
        return 0;
}

static int help(void) {

Lennart Poettering's avatar
Lennart Poettering committed
865
        printf("%s [OPTIONS...]\n\n"
866
               "Starts up and maintains the system or user services.\n\n"
867 868
               "  -h --help                      Show this help\n"
               "     --test                      Determine startup sequence, dump it and exit\n"
Lennart Poettering's avatar
Lennart Poettering committed
869
               "     --dump-configuration-items  Dump understood unit configuration items\n"
870
               "     --introspect[=INTERFACE]    Extract D-Bus interface data\n"
871
               "     --unit=UNIT                 Set default unit\n"
872
               "     --system                    Run a system instance, even if PID != 1\n"
873
               "     --user                      Run a user instance\n"
874 875 876
               "     --dump-core                 Dump core on crash\n"
               "     --crash-shell               Run shell on crash\n"
               "     --confirm-spawn             Ask for confirmation when spawning processes\n"
877
               "     --show-status[=0|1]         Show status updates on the console during bootup\n"
878
#ifdef HAVE_SYSV_COMPAT
879
               "     --sysv-console[=0|1]        Connect output of SysV scripts to console\n"
880
#endif
881
               "     --log-target=TARGET         Set log target (console, syslog, kmsg, syslog-or-kmsg, null)\n"
882
               "     --log-level=LEVEL           Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
883
               "     --log-color[=0|1]           Highlight important log messages\n"
884 885 886
               "     --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",
887
               program_invocation_short_name);
888 889 890 891

        return 0;
}

892 893 894 895 896 897 898 899 900
static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds) {
        FILE *f = NULL;
        FDSet *fds = NULL;
        int r;

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

901
        if ((r = manager_open_serialization(m, &f)) < 0) {
Harald Hoyer's avatar
Harald Hoyer committed
902
                log_error("Failed to create serialization file: %s", strerror(-r));
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
                goto fail;
        }

        if (!(fds = fdset_new())) {
                r = -ENOMEM;
                log_error("Failed to allocate fd set: %s", strerror(-r));
                goto fail;
        }

        if ((r = manager_serialize(m, f, fds)) < 0) {
                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;
        }

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

        if ((r = fdset_cloexec(fds, false)) < 0) {
                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;
}

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
static struct dual_timestamp* parse_initrd_timestamp(struct dual_timestamp *t) {
        const char *e;
        unsigned long long a, b;

        assert(t);

        if (!(e = getenv("RD_TIMESTAMP")))
                return NULL;

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

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

        return t;
}

964 965 966
static void test_mtab(void) {
        char *p;

967 968
        /* Check that /etc/mtab is a symlink */

969 970 971
        if (readlink_malloc("/etc/mtab", &p) >= 0) {
                bool b;

972
                b = streq(p, "/proc/self/mounts") || streq(p, "/proc/mounts");
973 974 975 976 977 978
                free(p);

                if (b)
                        return;
        }

979 980 981 982 983 984 985
        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
986
        /* Check that /usr is not a separate fs */
987

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
        if (dir_is_empty("/usr") <= 0)
                return;

        log_warning("/usr appears to be on a different file system than /. This is not supported anymore. "
                    "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. "
                    "Instead fix your kernel and enable CONFIG_CGROUPS." );

        sleep(10);
1008 1009
}

Lennart Poettering's avatar
Lennart Poettering committed
1010 1011
int main(int argc, char *argv[]) {
        Manager *m = NULL;
1012
        int r, retval = EXIT_FAILURE;
1013 1014
        FDSet *fds = NULL;
        bool reexecute = false;
1015
        const char *shutdown_verb = NULL;
1016
        dual_timestamp initrd_timestamp = { 0ULL, 0ULL };
1017
        char systemd[] = "systemd";
1018

1019
        if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
Harald Hoyer's avatar
Harald Hoyer committed
1020
                /* This is compatibility support for SysV, where
1021 1022 1023 1024 1025 1026 1027 1028
                 * calling init as a user is identical to telinit. */

                errno = -ENOENT;
                execv(SYSTEMCTL_BINARY_PATH, argv);
                log_error("Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
                return 1;
        }

1029 1030 1031 1032 1033 1034 1035 1036
        /* If we get started via the /sbin/init symlink then we are
           called 'init'. After a subsequent reexecution we are then
           called 'systemd'. That is confusing, hence let's call us
           systemd right-away. */

        program_invocation_short_name = systemd;
        prctl(PR_SET_NAME, systemd);

1037
        log_show_color(isatty(STDERR_FILENO) > 0);
1038
        log_show_location(false);
1039
        log_set_max_level(LOG_INFO);
1040

1041
        if (getpid() == 1) {
1042
                arg_running_as = MANAGER_SYSTEM;
1043
                log_set_target(detect_container(NULL) > 0 ? LOG_TARGET_CONSOLE : LOG_TARGET_SYSLOG_OR_KMSG);
1044

1045 1046 1047 1048 1049
                /* This might actually not return, but cause a
                 * reexecution */
                if (selinux_setup(argv) < 0)
                        goto finish;

1050 1051
                if (label_init() < 0)
                        goto finish;
1052
        } else {
1053
                arg_running_as = MANAGER_USER;
1054 1055
                log_set_target(LOG_TARGET_CONSOLE);
        }
1056

1057 1058
        if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
                goto finish;
Lennart Poettering's avatar
Lennart Poettering committed
1059

1060 1061
        /* Mount /proc, /sys and friends, so that /proc/cmdline and
         * /proc/$PID/fd is available. */
1062
        if (geteuid() == 0 && !getenv("SYSTEMD_SKIP_API_MOUNTS"))
1063 1064
                if (mount_setup() < 0)
                        goto finish;
1065 1066 1067 1068

        /* Reset all signal handlers. */
        assert_se(reset_all_signal_handlers() == 0);

1069
        /* If we are init, we can block sigkill. Yay. */
1070
        ignore_signals(SIGNALS_IGNORE, -1);
1071

1072 1073 1074
        if (parse_config_file() < 0)
                goto finish;

1075
        if (arg_running_as == MANAGER_SYSTEM)
1076 1077
                if (parse_proc_cmdline() < 0)
                        goto finish;
1078 1079 1080 1081 1082 1083

        log_parse_environment();

        if (parse_argv(argc, argv) < 0)
                goto finish;

1084 1085 1086 1087 1088
        if (arg_action == ACTION_TEST && geteuid() == 0) {
                log_error("Don't run test mode as root.");
                goto finish;
        }

1089 1090 1091 1092 1093 1094 1095
        if (arg_running_as == MANAGER_SYSTEM &&
            arg_action == ACTION_RUN &&
            running_in_chroot() > 0) {
                log_error("Cannot be run in a chroot() environment.");
                goto finish;
        }

1096 1097
        /* If Plymouth is being run make sure we show the status, so
         * that there's something nice to see when people press Esc */
Kay Sievers's avatar
Kay Sievers committed
1098
        if (access("/run/initramfs/plymouth", F_OK) >= 0)
1099 1100
                arg_show_status = true;

1101
        if (arg_action == ACTION_HELP) {
1102 1103
                retval = help();
                goto finish;
1104
        } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
1105
                unit_dump_config_items(stdout);
1106
                retval = EXIT_SUCCESS;
1107
                goto finish;
1108
        } else if (arg_action == ACTION_DONE) {
1109
                retval = EXIT_SUCCESS;
1110
                goto finish;
1111 1112
        }

1113
        assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
1114

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
        /* Remember open file descriptors for later deserialization */
        if (serialization) {
                if ((r = fdset_new_fill(&fds)) < 0) {
                        log_error("Failed to allocate fd set: %s", strerror(-r));
                        goto finish;
                }

                assert_se(fdset_remove(fds, fileno(serialization)) >= 0);
        } else
                close_all_fds(NULL, 0);

1126
        /* Set up PATH unless it is already set */
1127 1128
        setenv("PATH",
               "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
1129
               arg_running_as == MANAGER_SYSTEM);
1130

1131
        if (arg_running_as == MANAGER_SYSTEM) {
1132 1133 1134 1135 1136 1137
                /* Parse the data passed to us by the initrd and unset it */
                parse_initrd_timestamp(&initrd_timestamp);
                filter_environ("RD_");

                /* Unset some environment variables passed in from the
                 * kernel that don't really make sense for us. */
1138 1139
                unsetenv("HOME");
                unsetenv("TERM");