init.cpp revision e36a85cdcc93a84a6869fc8fc3fc82e3639d4398
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <libgen.h>
22#include <paths.h>
23#include <signal.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/epoll.h>
29#include <sys/mount.h>
30#include <sys/socket.h>
31#include <sys/stat.h>
32#include <sys/types.h>
33#include <sys/un.h>
34#include <sys/wait.h>
35#include <unistd.h>
36
37#include <mtd/mtd-user.h>
38
39#include <selinux/selinux.h>
40#include <selinux/label.h>
41#include <selinux/android.h>
42
43#include <base/file.h>
44#include <base/stringprintf.h>
45#include <base/strings.h>
46#include <cutils/android_reboot.h>
47#include <cutils/fs.h>
48#include <cutils/iosched_policy.h>
49#include <cutils/list.h>
50#include <cutils/sockets.h>
51#include <private/android_filesystem_config.h>
52
53#include <memory>
54
55#include "action.h"
56#include "bootchart.h"
57#include "devices.h"
58#include "import_parser.h"
59#include "init.h"
60#include "init_parser.h"
61#include "keychords.h"
62#include "log.h"
63#include "property_service.h"
64#include "service.h"
65#include "signal_handler.h"
66#include "ueventd.h"
67#include "util.h"
68#include "watchdogd.h"
69
70struct selabel_handle *sehandle;
71struct selabel_handle *sehandle_prop;
72
73static int property_triggers_enabled = 0;
74
75static char qemu[32];
76
77int have_console;
78std::string console_name = "/dev/console";
79static time_t process_needs_restart;
80
81const char *ENV[32];
82
83bool waiting_for_exec = false;
84
85static int epoll_fd = -1;
86
87void register_epoll_handler(int fd, void (*fn)()) {
88    epoll_event ev;
89    ev.events = EPOLLIN;
90    ev.data.ptr = reinterpret_cast<void*>(fn);
91    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
92        ERROR("epoll_ctl failed: %s\n", strerror(errno));
93    }
94}
95
96/* add_environment - add "key=value" to the current environment */
97int add_environment(const char *key, const char *val)
98{
99    size_t n;
100    size_t key_len = strlen(key);
101
102    /* The last environment entry is reserved to terminate the list */
103    for (n = 0; n < (ARRAY_SIZE(ENV) - 1); n++) {
104
105        /* Delete any existing entry for this key */
106        if (ENV[n] != NULL) {
107            size_t entry_key_len = strcspn(ENV[n], "=");
108            if ((entry_key_len == key_len) && (strncmp(ENV[n], key, entry_key_len) == 0)) {
109                free((char*)ENV[n]);
110                ENV[n] = NULL;
111            }
112        }
113
114        /* Add entry if a free slot is available */
115        if (ENV[n] == NULL) {
116            char* entry;
117            asprintf(&entry, "%s=%s", key, val);
118            ENV[n] = entry;
119            return 0;
120        }
121    }
122
123    ERROR("No env. room to store: '%s':'%s'\n", key, val);
124
125    return -1;
126}
127
128void property_changed(const char *name, const char *value)
129{
130    if (property_triggers_enabled)
131        ActionManager::GetInstance().QueuePropertyTrigger(name, value);
132}
133
134static void restart_processes()
135{
136    process_needs_restart = 0;
137    ServiceManager::GetInstance().
138        ForEachServiceWithFlags(SVC_RESTARTING, [] (Service* s) {
139                s->RestartIfNeeded(process_needs_restart);
140            });
141}
142
143static void msg_start(const std::string& name)
144{
145    Service* svc = nullptr;
146    std::vector<std::string> vargs;
147
148    size_t colon_pos = name.find(':');
149    if (colon_pos == std::string::npos) {
150        svc = ServiceManager::GetInstance().FindServiceByName(name);
151    } else {
152        std::string service_name(name.substr(0, colon_pos));
153        std::string args(name.substr(colon_pos + 1));
154        vargs = android::base::Split(args, " ");
155
156        svc = ServiceManager::GetInstance().FindServiceByName(service_name);
157    }
158
159    if (svc) {
160        svc->Start(vargs);
161    } else {
162        ERROR("no such service '%s'\n", name.c_str());
163    }
164}
165
166static void msg_stop(const std::string& name)
167{
168    Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
169
170    if (svc) {
171        svc->Stop();
172    } else {
173        ERROR("no such service '%s'\n", name.c_str());
174    }
175}
176
177static void msg_restart(const std::string& name)
178{
179    Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
180
181    if (svc) {
182        svc->Restart();
183    } else {
184        ERROR("no such service '%s'\n", name.c_str());
185    }
186}
187
188void handle_control_message(const std::string& msg, const std::string& arg)
189{
190    if (msg == "start") {
191        msg_start(arg);
192    } else if (msg == "stop") {
193        msg_stop(arg);
194    } else if (msg == "restart") {
195        msg_restart(arg);
196    } else {
197        ERROR("unknown control msg '%s'\n", msg.c_str());
198    }
199}
200
201static int wait_for_coldboot_done_action(const std::vector<std::string>& args) {
202    Timer t;
203
204    NOTICE("Waiting for %s...\n", COLDBOOT_DONE);
205    // Any longer than 1s is an unreasonable length of time to delay booting.
206    // If you're hitting this timeout, check that you didn't make your
207    // sepolicy regular expressions too expensive (http://b/19899875).
208    if (wait_for_file(COLDBOOT_DONE, 1)) {
209        ERROR("Timed out waiting for %s\n", COLDBOOT_DONE);
210    }
211
212    NOTICE("Waiting for %s took %.2fs.\n", COLDBOOT_DONE, t.duration());
213    return 0;
214}
215
216/*
217 * Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
218 * by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
219 * Does nothing if Hardware RNG is not present.
220 *
221 * Since we don't yet trust the quality of Hardware RNG, these bytes are not
222 * mixed into the primary pool of Linux RNG and the entropy estimate is left
223 * unmodified.
224 *
225 * If the HW RNG device /dev/hw_random is present, we require that at least
226 * 512 bytes read from it are written into Linux RNG. QA is expected to catch
227 * devices/configurations where these I/O operations are blocking for a long
228 * time. We do not reboot or halt on failures, as this is a best-effort
229 * attempt.
230 */
231static int mix_hwrng_into_linux_rng_action(const std::vector<std::string>& args)
232{
233    int result = -1;
234    int hwrandom_fd = -1;
235    int urandom_fd = -1;
236    char buf[512];
237    ssize_t chunk_size;
238    size_t total_bytes_written = 0;
239
240    hwrandom_fd = TEMP_FAILURE_RETRY(
241            open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
242    if (hwrandom_fd == -1) {
243        if (errno == ENOENT) {
244          ERROR("/dev/hw_random not found\n");
245          /* It's not an error to not have a Hardware RNG. */
246          result = 0;
247        } else {
248          ERROR("Failed to open /dev/hw_random: %s\n", strerror(errno));
249        }
250        goto ret;
251    }
252
253    urandom_fd = TEMP_FAILURE_RETRY(
254            open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
255    if (urandom_fd == -1) {
256        ERROR("Failed to open /dev/urandom: %s\n", strerror(errno));
257        goto ret;
258    }
259
260    while (total_bytes_written < sizeof(buf)) {
261        chunk_size = TEMP_FAILURE_RETRY(
262                read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
263        if (chunk_size == -1) {
264            ERROR("Failed to read from /dev/hw_random: %s\n", strerror(errno));
265            goto ret;
266        } else if (chunk_size == 0) {
267            ERROR("Failed to read from /dev/hw_random: EOF\n");
268            goto ret;
269        }
270
271        chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
272        if (chunk_size == -1) {
273            ERROR("Failed to write to /dev/urandom: %s\n", strerror(errno));
274            goto ret;
275        }
276        total_bytes_written += chunk_size;
277    }
278
279    INFO("Mixed %zu bytes from /dev/hw_random into /dev/urandom",
280                total_bytes_written);
281    result = 0;
282
283ret:
284    if (hwrandom_fd != -1) {
285        close(hwrandom_fd);
286    }
287    if (urandom_fd != -1) {
288        close(urandom_fd);
289    }
290    return result;
291}
292
293static int keychord_init_action(const std::vector<std::string>& args)
294{
295    keychord_init();
296    return 0;
297}
298
299static int console_init_action(const std::vector<std::string>& args)
300{
301    std::string console = property_get("ro.boot.console");
302    if (!console.empty()) {
303        console_name = "/dev/" + console;
304    }
305
306    int fd = open(console_name.c_str(), O_RDWR | O_CLOEXEC);
307    if (fd >= 0)
308        have_console = 1;
309    close(fd);
310
311    fd = open("/dev/tty0", O_WRONLY | O_CLOEXEC);
312    if (fd >= 0) {
313        const char *msg;
314            msg = "\n"
315        "\n"
316        "\n"
317        "\n"
318        "\n"
319        "\n"
320        "\n"  // console is 40 cols x 30 lines
321        "\n"
322        "\n"
323        "\n"
324        "\n"
325        "\n"
326        "\n"
327        "\n"
328        "             A N D R O I D ";
329        write(fd, msg, strlen(msg));
330        close(fd);
331    }
332
333    return 0;
334}
335
336static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
337    if (key.empty()) return;
338
339    if (for_emulator) {
340        // In the emulator, export any kernel option with the "ro.kernel." prefix.
341        property_set(android::base::StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
342        return;
343    }
344
345    if (key == "qemu") {
346        strlcpy(qemu, value.c_str(), sizeof(qemu));
347    } else if (android::base::StartsWith(key, "androidboot.")) {
348        property_set(android::base::StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(),
349                     value.c_str());
350    }
351}
352
353static void export_kernel_boot_props() {
354    struct {
355        const char *src_prop;
356        const char *dst_prop;
357        const char *default_value;
358    } prop_map[] = {
359        { "ro.boot.serialno",   "ro.serialno",   "", },
360        { "ro.boot.mode",       "ro.bootmode",   "unknown", },
361        { "ro.boot.baseband",   "ro.baseband",   "unknown", },
362        { "ro.boot.bootloader", "ro.bootloader", "unknown", },
363        { "ro.boot.hardware",   "ro.hardware",   "unknown", },
364        { "ro.boot.revision",   "ro.revision",   "0", },
365    };
366    for (size_t i = 0; i < ARRAY_SIZE(prop_map); i++) {
367        std::string value = property_get(prop_map[i].src_prop);
368        property_set(prop_map[i].dst_prop, (!value.empty()) ? value.c_str() : prop_map[i].default_value);
369    }
370}
371
372static void process_kernel_dt() {
373    static const char android_dir[] = "/proc/device-tree/firmware/android";
374
375    std::string file_name = android::base::StringPrintf("%s/compatible", android_dir);
376
377    std::string dt_file;
378    android::base::ReadFileToString(file_name, &dt_file);
379    if (!dt_file.compare("android,firmware")) {
380        ERROR("firmware/android is not compatible with 'android,firmware'\n");
381        return;
382    }
383
384    std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(android_dir), closedir);
385    if (!dir) return;
386
387    struct dirent *dp;
388    while ((dp = readdir(dir.get())) != NULL) {
389        if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
390            continue;
391        }
392
393        file_name = android::base::StringPrintf("%s/%s", android_dir, dp->d_name);
394
395        android::base::ReadFileToString(file_name, &dt_file);
396        std::replace(dt_file.begin(), dt_file.end(), ',', '.');
397
398        std::string property_name = android::base::StringPrintf("ro.boot.%s", dp->d_name);
399        property_set(property_name.c_str(), dt_file.c_str());
400    }
401}
402
403static void process_kernel_cmdline() {
404    // Don't expose the raw commandline to unprivileged processes.
405    chmod("/proc/cmdline", 0440);
406
407    // The first pass does the common stuff, and finds if we are in qemu.
408    // The second pass is only necessary for qemu to export all kernel params
409    // as properties.
410    import_kernel_cmdline(false, import_kernel_nv);
411    if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
412}
413
414static int queue_property_triggers_action(const std::vector<std::string>& args)
415{
416    ActionManager::GetInstance().QueueAllPropertyTriggers();
417    /* enable property triggers */
418    property_triggers_enabled = 1;
419    return 0;
420}
421
422static void selinux_init_all_handles(void)
423{
424    sehandle = selinux_android_file_context_handle();
425    selinux_android_set_sehandle(sehandle);
426    sehandle_prop = selinux_android_prop_context_handle();
427}
428
429enum selinux_enforcing_status { SELINUX_PERMISSIVE, SELINUX_ENFORCING };
430
431static selinux_enforcing_status selinux_status_from_cmdline() {
432    selinux_enforcing_status status = SELINUX_ENFORCING;
433
434    import_kernel_cmdline(false, [&](const std::string& key, const std::string& value, bool in_qemu) {
435        if (key == "androidboot.selinux" && value == "permissive") {
436            status = SELINUX_PERMISSIVE;
437        }
438    });
439
440    return status;
441}
442
443static bool selinux_is_enforcing(void)
444{
445    if (ALLOW_PERMISSIVE_SELINUX) {
446        return selinux_status_from_cmdline() == SELINUX_ENFORCING;
447    }
448    return true;
449}
450
451int selinux_reload_policy(void)
452{
453    INFO("SELinux: Attempting to reload policy files\n");
454
455    if (selinux_android_reload_policy() == -1) {
456        return -1;
457    }
458
459    if (sehandle)
460        selabel_close(sehandle);
461
462    if (sehandle_prop)
463        selabel_close(sehandle_prop);
464
465    selinux_init_all_handles();
466    return 0;
467}
468
469static int audit_callback(void *data, security_class_t /*cls*/, char *buf, size_t len) {
470
471    property_audit_data *d = reinterpret_cast<property_audit_data*>(data);
472
473    if (!d || !d->name || !d->cr) {
474        ERROR("audit_callback invoked with null data arguments!");
475        return 0;
476    }
477
478    snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name,
479            d->cr->pid, d->cr->uid, d->cr->gid);
480    return 0;
481}
482
483static void security_failure() {
484    ERROR("Security failure; rebooting into recovery mode...\n");
485    android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
486    while (true) { pause(); }  // never reached
487}
488
489static void selinux_initialize(bool in_kernel_domain) {
490    Timer t;
491
492    selinux_callback cb;
493    cb.func_log = selinux_klog_callback;
494    selinux_set_callback(SELINUX_CB_LOG, cb);
495    cb.func_audit = audit_callback;
496    selinux_set_callback(SELINUX_CB_AUDIT, cb);
497
498    if (in_kernel_domain) {
499        INFO("Loading SELinux policy...\n");
500        if (selinux_android_load_policy() < 0) {
501            ERROR("failed to load policy: %s\n", strerror(errno));
502            security_failure();
503        }
504
505        bool kernel_enforcing = (security_getenforce() == 1);
506        bool is_enforcing = selinux_is_enforcing();
507        if (kernel_enforcing != is_enforcing) {
508            if (security_setenforce(is_enforcing)) {
509                ERROR("security_setenforce(%s) failed: %s\n",
510                      is_enforcing ? "true" : "false", strerror(errno));
511                security_failure();
512            }
513        }
514
515        if (write_file("/sys/fs/selinux/checkreqprot", "0") == -1) {
516            security_failure();
517        }
518
519        NOTICE("(Initializing SELinux %s took %.2fs.)\n",
520               is_enforcing ? "enforcing" : "non-enforcing", t.duration());
521    } else {
522        selinux_init_all_handles();
523    }
524}
525
526int main(int argc, char** argv) {
527    if (!strcmp(basename(argv[0]), "ueventd")) {
528        return ueventd_main(argc, argv);
529    }
530
531    if (!strcmp(basename(argv[0]), "watchdogd")) {
532        return watchdogd_main(argc, argv);
533    }
534
535    // Clear the umask.
536    umask(0);
537
538    add_environment("PATH", _PATH_DEFPATH);
539
540    bool is_first_stage = (argc == 1) || (strcmp(argv[1], "--second-stage") != 0);
541
542    // Get the basic filesystem setup we need put together in the initramdisk
543    // on / and then we'll let the rc file figure out the rest.
544    if (is_first_stage) {
545        mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
546        mkdir("/dev/pts", 0755);
547        mkdir("/dev/socket", 0755);
548        mount("devpts", "/dev/pts", "devpts", 0, NULL);
549        #define MAKE_STR(x) __STRING(x)
550        mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
551        mount("sysfs", "/sys", "sysfs", 0, NULL);
552    }
553
554    // We must have some place other than / to create the device nodes for
555    // kmsg and null, otherwise we won't be able to remount / read-only
556    // later on. Now that tmpfs is mounted on /dev, we can actually talk
557    // to the outside world.
558    open_devnull_stdio();
559    klog_init();
560    klog_set_level(KLOG_NOTICE_LEVEL);
561
562    NOTICE("init %s started!\n", is_first_stage ? "first stage" : "second stage");
563
564    if (!is_first_stage) {
565        // Indicate that booting is in progress to background fw loaders, etc.
566        close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
567
568        property_init();
569
570        // If arguments are passed both on the command line and in DT,
571        // properties set in DT always have priority over the command-line ones.
572        process_kernel_dt();
573        process_kernel_cmdline();
574
575        // Propagate the kernel variables to internal variables
576        // used by init as well as the current required properties.
577        export_kernel_boot_props();
578    }
579
580    // Set up SELinux, including loading the SELinux policy if we're in the kernel domain.
581    selinux_initialize(is_first_stage);
582
583    // If we're in the kernel domain, re-exec init to transition to the init domain now
584    // that the SELinux policy has been loaded.
585    if (is_first_stage) {
586        if (restorecon("/init") == -1) {
587            ERROR("restorecon failed: %s\n", strerror(errno));
588            security_failure();
589        }
590        char* path = argv[0];
591        char* args[] = { path, const_cast<char*>("--second-stage"), nullptr };
592        if (execv(path, args) == -1) {
593            ERROR("execv(\"%s\") failed: %s\n", path, strerror(errno));
594            security_failure();
595        }
596    }
597
598    // These directories were necessarily created before initial policy load
599    // and therefore need their security context restored to the proper value.
600    // This must happen before /dev is populated by ueventd.
601    NOTICE("Running restorecon...\n");
602    restorecon("/dev");
603    restorecon("/dev/socket");
604    restorecon("/dev/__properties__");
605    restorecon("/property_contexts");
606    restorecon_recursive("/sys");
607
608    epoll_fd = epoll_create1(EPOLL_CLOEXEC);
609    if (epoll_fd == -1) {
610        ERROR("epoll_create1 failed: %s\n", strerror(errno));
611        exit(1);
612    }
613
614    signal_handler_init();
615
616    property_load_boot_defaults();
617    start_property_service();
618
619    const BuiltinFunctionMap function_map;
620    Action::set_function_map(&function_map);
621
622    Parser& parser = Parser::GetInstance();
623    parser.AddSectionParser("service",std::make_unique<ServiceParser>());
624    parser.AddSectionParser("on", std::make_unique<ActionParser>());
625    parser.AddSectionParser("import", std::make_unique<ImportParser>());
626    parser.ParseConfig("/init.rc");
627
628    ActionManager& am = ActionManager::GetInstance();
629
630    am.QueueEventTrigger("early-init");
631
632    // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
633    am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
634    // ... so that we can start queuing up actions that require stuff from /dev.
635    am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
636    am.QueueBuiltinAction(keychord_init_action, "keychord_init");
637    am.QueueBuiltinAction(console_init_action, "console_init");
638
639    // Trigger all the boot actions to get us started.
640    am.QueueEventTrigger("init");
641
642    // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
643    // wasn't ready immediately after wait_for_coldboot_done
644    am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
645
646    // Don't mount filesystems or start core system services in charger mode.
647    std::string bootmode = property_get("ro.bootmode");
648    if (bootmode == "charger") {
649        am.QueueEventTrigger("charger");
650    } else {
651        am.QueueEventTrigger("late-init");
652    }
653
654    // Run all property triggers based on current state of the properties.
655    am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
656
657    while (true) {
658        if (!waiting_for_exec) {
659            am.ExecuteOneCommand();
660            restart_processes();
661        }
662
663        int timeout = -1;
664        if (process_needs_restart) {
665            timeout = (process_needs_restart - gettime()) * 1000;
666            if (timeout < 0)
667                timeout = 0;
668        }
669
670        if (am.HasMoreCommands()) {
671            timeout = 0;
672        }
673
674        bootchart_sample(&timeout);
675
676        epoll_event ev;
677        int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, timeout));
678        if (nr == -1) {
679            ERROR("epoll_wait failed: %s\n", strerror(errno));
680        } else if (nr == 1) {
681            ((void (*)()) ev.data.ptr)();
682        }
683    }
684
685    return 0;
686}
687