Home | History | Annotate | Download | only in init
      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 <stdio.h>
     18 #include <stdlib.h>
     19 #include <string.h>
     20 #include <unistd.h>
     21 #include <fcntl.h>
     22 #include <ctype.h>
     23 #include <signal.h>
     24 #include <sys/wait.h>
     25 #include <sys/mount.h>
     26 #include <sys/stat.h>
     27 #include <sys/poll.h>
     28 #include <errno.h>
     29 #include <stdarg.h>
     30 #include <mtd/mtd-user.h>
     31 #include <sys/types.h>
     32 #include <sys/socket.h>
     33 #include <sys/un.h>
     34 
     35 #include <selinux/selinux.h>
     36 #include <selinux/label.h>
     37 #include <selinux/android.h>
     38 
     39 #include <libgen.h>
     40 
     41 #include <cutils/list.h>
     42 #include <cutils/android_reboot.h>
     43 #include <cutils/sockets.h>
     44 #include <cutils/iosched_policy.h>
     45 #include <cutils/fs.h>
     46 #include <private/android_filesystem_config.h>
     47 #include <termios.h>
     48 
     49 #include "devices.h"
     50 #include "init.h"
     51 #include "log.h"
     52 #include "property_service.h"
     53 #include "bootchart.h"
     54 #include "signal_handler.h"
     55 #include "keychords.h"
     56 #include "init_parser.h"
     57 #include "util.h"
     58 #include "ueventd.h"
     59 #include "watchdogd.h"
     60 
     61 struct selabel_handle *sehandle;
     62 struct selabel_handle *sehandle_prop;
     63 
     64 static int property_triggers_enabled = 0;
     65 
     66 #if BOOTCHART
     67 static int   bootchart_count;
     68 #endif
     69 
     70 static char console[32];
     71 static char bootmode[32];
     72 static char hardware[32];
     73 static unsigned revision = 0;
     74 static char qemu[32];
     75 
     76 static struct action *cur_action = NULL;
     77 static struct command *cur_command = NULL;
     78 static struct listnode *command_queue = NULL;
     79 
     80 void notify_service_state(const char *name, const char *state)
     81 {
     82     char pname[PROP_NAME_MAX];
     83     int len = strlen(name);
     84     if ((len + 10) > PROP_NAME_MAX)
     85         return;
     86     snprintf(pname, sizeof(pname), "init.svc.%s", name);
     87     property_set(pname, state);
     88 }
     89 
     90 static int have_console;
     91 static char console_name[PROP_VALUE_MAX] = "/dev/console";
     92 static time_t process_needs_restart;
     93 
     94 static const char *ENV[32];
     95 
     96 /* add_environment - add "key=value" to the current environment */
     97 int 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             size_t len = key_len + strlen(val) + 2;
    117             char *entry = malloc(len);
    118             snprintf(entry, len, "%s=%s", key, val);
    119             ENV[n] = entry;
    120             return 0;
    121         }
    122     }
    123 
    124     ERROR("No env. room to store: '%s':'%s'\n", key, val);
    125 
    126     return -1;
    127 }
    128 
    129 static void zap_stdio(void)
    130 {
    131     int fd;
    132     fd = open("/dev/null", O_RDWR);
    133     dup2(fd, 0);
    134     dup2(fd, 1);
    135     dup2(fd, 2);
    136     close(fd);
    137 }
    138 
    139 static void open_console()
    140 {
    141     int fd;
    142     if ((fd = open(console_name, O_RDWR)) < 0) {
    143         fd = open("/dev/null", O_RDWR);
    144     }
    145     ioctl(fd, TIOCSCTTY, 0);
    146     dup2(fd, 0);
    147     dup2(fd, 1);
    148     dup2(fd, 2);
    149     close(fd);
    150 }
    151 
    152 static void publish_socket(const char *name, int fd)
    153 {
    154     char key[64] = ANDROID_SOCKET_ENV_PREFIX;
    155     char val[64];
    156 
    157     strlcpy(key + sizeof(ANDROID_SOCKET_ENV_PREFIX) - 1,
    158             name,
    159             sizeof(key) - sizeof(ANDROID_SOCKET_ENV_PREFIX));
    160     snprintf(val, sizeof(val), "%d", fd);
    161     add_environment(key, val);
    162 
    163     /* make sure we don't close-on-exec */
    164     fcntl(fd, F_SETFD, 0);
    165 }
    166 
    167 void service_start(struct service *svc, const char *dynamic_args)
    168 {
    169     struct stat s;
    170     pid_t pid;
    171     int needs_console;
    172     int n;
    173     char *scon = NULL;
    174     int rc;
    175 
    176         /* starting a service removes it from the disabled or reset
    177          * state and immediately takes it out of the restarting
    178          * state if it was in there
    179          */
    180     svc->flags &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
    181     svc->time_started = 0;
    182 
    183         /* running processes require no additional work -- if
    184          * they're in the process of exiting, we've ensured
    185          * that they will immediately restart on exit, unless
    186          * they are ONESHOT
    187          */
    188     if (svc->flags & SVC_RUNNING) {
    189         return;
    190     }
    191 
    192     needs_console = (svc->flags & SVC_CONSOLE) ? 1 : 0;
    193     if (needs_console && (!have_console)) {
    194         ERROR("service '%s' requires console\n", svc->name);
    195         svc->flags |= SVC_DISABLED;
    196         return;
    197     }
    198 
    199     if (stat(svc->args[0], &s) != 0) {
    200         ERROR("cannot find '%s', disabling '%s'\n", svc->args[0], svc->name);
    201         svc->flags |= SVC_DISABLED;
    202         return;
    203     }
    204 
    205     if ((!(svc->flags & SVC_ONESHOT)) && dynamic_args) {
    206         ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
    207                svc->args[0]);
    208         svc->flags |= SVC_DISABLED;
    209         return;
    210     }
    211 
    212     if (is_selinux_enabled() > 0) {
    213         if (svc->seclabel) {
    214             scon = strdup(svc->seclabel);
    215             if (!scon) {
    216                 ERROR("Out of memory while starting '%s'\n", svc->name);
    217                 return;
    218             }
    219         } else {
    220             char *mycon = NULL, *fcon = NULL;
    221 
    222             INFO("computing context for service '%s'\n", svc->args[0]);
    223             rc = getcon(&mycon);
    224             if (rc < 0) {
    225                 ERROR("could not get context while starting '%s'\n", svc->name);
    226                 return;
    227             }
    228 
    229             rc = getfilecon(svc->args[0], &fcon);
    230             if (rc < 0) {
    231                 ERROR("could not get context while starting '%s'\n", svc->name);
    232                 freecon(mycon);
    233                 return;
    234             }
    235 
    236             rc = security_compute_create(mycon, fcon, string_to_security_class("process"), &scon);
    237             if (rc == 0 && !strcmp(scon, mycon)) {
    238                 ERROR("Warning!  Service %s needs a SELinux domain defined; please fix!\n", svc->name);
    239             }
    240             freecon(mycon);
    241             freecon(fcon);
    242             if (rc < 0) {
    243                 ERROR("could not get context while starting '%s'\n", svc->name);
    244                 return;
    245             }
    246         }
    247     }
    248 
    249     NOTICE("starting '%s'\n", svc->name);
    250 
    251     pid = fork();
    252 
    253     if (pid == 0) {
    254         struct socketinfo *si;
    255         struct svcenvinfo *ei;
    256         char tmp[32];
    257         int fd, sz;
    258 
    259         umask(077);
    260         if (properties_inited()) {
    261             get_property_workspace(&fd, &sz);
    262             sprintf(tmp, "%d,%d", dup(fd), sz);
    263             add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);
    264         }
    265 
    266         for (ei = svc->envvars; ei; ei = ei->next)
    267             add_environment(ei->name, ei->value);
    268 
    269         for (si = svc->sockets; si; si = si->next) {
    270             int socket_type = (
    271                     !strcmp(si->type, "stream") ? SOCK_STREAM :
    272                         (!strcmp(si->type, "dgram") ? SOCK_DGRAM : SOCK_SEQPACKET));
    273             int s = create_socket(si->name, socket_type,
    274                                   si->perm, si->uid, si->gid, si->socketcon ?: scon);
    275             if (s >= 0) {
    276                 publish_socket(si->name, s);
    277             }
    278         }
    279 
    280         freecon(scon);
    281         scon = NULL;
    282 
    283         if (svc->ioprio_class != IoSchedClass_NONE) {
    284             if (android_set_ioprio(getpid(), svc->ioprio_class, svc->ioprio_pri)) {
    285                 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
    286                       getpid(), svc->ioprio_class, svc->ioprio_pri, strerror(errno));
    287             }
    288         }
    289 
    290         if (needs_console) {
    291             setsid();
    292             open_console();
    293         } else {
    294             zap_stdio();
    295         }
    296 
    297 #if 0
    298         for (n = 0; svc->args[n]; n++) {
    299             INFO("args[%d] = '%s'\n", n, svc->args[n]);
    300         }
    301         for (n = 0; ENV[n]; n++) {
    302             INFO("env[%d] = '%s'\n", n, ENV[n]);
    303         }
    304 #endif
    305 
    306         setpgid(0, getpid());
    307 
    308     /* as requested, set our gid, supplemental gids, and uid */
    309         if (svc->gid) {
    310             if (setgid(svc->gid) != 0) {
    311                 ERROR("setgid failed: %s\n", strerror(errno));
    312                 _exit(127);
    313             }
    314         }
    315         if (svc->nr_supp_gids) {
    316             if (setgroups(svc->nr_supp_gids, svc->supp_gids) != 0) {
    317                 ERROR("setgroups failed: %s\n", strerror(errno));
    318                 _exit(127);
    319             }
    320         }
    321         if (svc->uid) {
    322             if (setuid(svc->uid) != 0) {
    323                 ERROR("setuid failed: %s\n", strerror(errno));
    324                 _exit(127);
    325             }
    326         }
    327         if (svc->seclabel) {
    328             if (is_selinux_enabled() > 0 && setexeccon(svc->seclabel) < 0) {
    329                 ERROR("cannot setexeccon('%s'): %s\n", svc->seclabel, strerror(errno));
    330                 _exit(127);
    331             }
    332         }
    333 
    334         if (!dynamic_args) {
    335             if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
    336                 ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
    337             }
    338         } else {
    339             char *arg_ptrs[INIT_PARSER_MAXARGS+1];
    340             int arg_idx = svc->nargs;
    341             char *tmp = strdup(dynamic_args);
    342             char *next = tmp;
    343             char *bword;
    344 
    345             /* Copy the static arguments */
    346             memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));
    347 
    348             while((bword = strsep(&next, " "))) {
    349                 arg_ptrs[arg_idx++] = bword;
    350                 if (arg_idx == INIT_PARSER_MAXARGS)
    351                     break;
    352             }
    353             arg_ptrs[arg_idx] = '\0';
    354             execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
    355         }
    356         _exit(127);
    357     }
    358 
    359     freecon(scon);
    360 
    361     if (pid < 0) {
    362         ERROR("failed to start '%s'\n", svc->name);
    363         svc->pid = 0;
    364         return;
    365     }
    366 
    367     svc->time_started = gettime();
    368     svc->pid = pid;
    369     svc->flags |= SVC_RUNNING;
    370 
    371     if (properties_inited())
    372         notify_service_state(svc->name, "running");
    373 }
    374 
    375 /* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
    376 static void service_stop_or_reset(struct service *svc, int how)
    377 {
    378     /* The service is still SVC_RUNNING until its process exits, but if it has
    379      * already exited it shoudn't attempt a restart yet. */
    380     svc->flags &= ~(SVC_RESTARTING | SVC_DISABLED_START);
    381 
    382     if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
    383         /* Hrm, an illegal flag.  Default to SVC_DISABLED */
    384         how = SVC_DISABLED;
    385     }
    386         /* if the service has not yet started, prevent
    387          * it from auto-starting with its class
    388          */
    389     if (how == SVC_RESET) {
    390         svc->flags |= (svc->flags & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
    391     } else {
    392         svc->flags |= how;
    393     }
    394 
    395     if (svc->pid) {
    396         NOTICE("service '%s' is being killed\n", svc->name);
    397         kill(-svc->pid, SIGKILL);
    398         notify_service_state(svc->name, "stopping");
    399     } else {
    400         notify_service_state(svc->name, "stopped");
    401     }
    402 }
    403 
    404 void service_reset(struct service *svc)
    405 {
    406     service_stop_or_reset(svc, SVC_RESET);
    407 }
    408 
    409 void service_stop(struct service *svc)
    410 {
    411     service_stop_or_reset(svc, SVC_DISABLED);
    412 }
    413 
    414 void service_restart(struct service *svc)
    415 {
    416     if (svc->flags & SVC_RUNNING) {
    417         /* Stop, wait, then start the service. */
    418         service_stop_or_reset(svc, SVC_RESTART);
    419     } else if (!(svc->flags & SVC_RESTARTING)) {
    420         /* Just start the service since it's not running. */
    421         service_start(svc, NULL);
    422     } /* else: Service is restarting anyways. */
    423 }
    424 
    425 void property_changed(const char *name, const char *value)
    426 {
    427     if (property_triggers_enabled)
    428         queue_property_triggers(name, value);
    429 }
    430 
    431 static void restart_service_if_needed(struct service *svc)
    432 {
    433     time_t next_start_time = svc->time_started + 5;
    434 
    435     if (next_start_time <= gettime()) {
    436         svc->flags &= (~SVC_RESTARTING);
    437         service_start(svc, NULL);
    438         return;
    439     }
    440 
    441     if ((next_start_time < process_needs_restart) ||
    442         (process_needs_restart == 0)) {
    443         process_needs_restart = next_start_time;
    444     }
    445 }
    446 
    447 static void restart_processes()
    448 {
    449     process_needs_restart = 0;
    450     service_for_each_flags(SVC_RESTARTING,
    451                            restart_service_if_needed);
    452 }
    453 
    454 static void msg_start(const char *name)
    455 {
    456     struct service *svc = NULL;
    457     char *tmp = NULL;
    458     char *args = NULL;
    459 
    460     if (!strchr(name, ':'))
    461         svc = service_find_by_name(name);
    462     else {
    463         tmp = strdup(name);
    464         if (tmp) {
    465             args = strchr(tmp, ':');
    466             *args = '\0';
    467             args++;
    468 
    469             svc = service_find_by_name(tmp);
    470         }
    471     }
    472 
    473     if (svc) {
    474         service_start(svc, args);
    475     } else {
    476         ERROR("no such service '%s'\n", name);
    477     }
    478     if (tmp)
    479         free(tmp);
    480 }
    481 
    482 static void msg_stop(const char *name)
    483 {
    484     struct service *svc = service_find_by_name(name);
    485 
    486     if (svc) {
    487         service_stop(svc);
    488     } else {
    489         ERROR("no such service '%s'\n", name);
    490     }
    491 }
    492 
    493 static void msg_restart(const char *name)
    494 {
    495     struct service *svc = service_find_by_name(name);
    496 
    497     if (svc) {
    498         service_restart(svc);
    499     } else {
    500         ERROR("no such service '%s'\n", name);
    501     }
    502 }
    503 
    504 void handle_control_message(const char *msg, const char *arg)
    505 {
    506     if (!strcmp(msg,"start")) {
    507         msg_start(arg);
    508     } else if (!strcmp(msg,"stop")) {
    509         msg_stop(arg);
    510     } else if (!strcmp(msg,"restart")) {
    511         msg_restart(arg);
    512     } else {
    513         ERROR("unknown control msg '%s'\n", msg);
    514     }
    515 }
    516 
    517 static struct command *get_first_command(struct action *act)
    518 {
    519     struct listnode *node;
    520     node = list_head(&act->commands);
    521     if (!node || list_empty(&act->commands))
    522         return NULL;
    523 
    524     return node_to_item(node, struct command, clist);
    525 }
    526 
    527 static struct command *get_next_command(struct action *act, struct command *cmd)
    528 {
    529     struct listnode *node;
    530     node = cmd->clist.next;
    531     if (!node)
    532         return NULL;
    533     if (node == &act->commands)
    534         return NULL;
    535 
    536     return node_to_item(node, struct command, clist);
    537 }
    538 
    539 static int is_last_command(struct action *act, struct command *cmd)
    540 {
    541     return (list_tail(&act->commands) == &cmd->clist);
    542 }
    543 
    544 void execute_one_command(void)
    545 {
    546     int ret, i;
    547     char cmd_str[256] = "";
    548 
    549     if (!cur_action || !cur_command || is_last_command(cur_action, cur_command)) {
    550         cur_action = action_remove_queue_head();
    551         cur_command = NULL;
    552         if (!cur_action)
    553             return;
    554         INFO("processing action %p (%s)\n", cur_action, cur_action->name);
    555         cur_command = get_first_command(cur_action);
    556     } else {
    557         cur_command = get_next_command(cur_action, cur_command);
    558     }
    559 
    560     if (!cur_command)
    561         return;
    562 
    563     ret = cur_command->func(cur_command->nargs, cur_command->args);
    564     if (klog_get_level() >= KLOG_INFO_LEVEL) {
    565         for (i = 0; i < cur_command->nargs; i++) {
    566             strlcat(cmd_str, cur_command->args[i], sizeof(cmd_str));
    567             if (i < cur_command->nargs - 1) {
    568                 strlcat(cmd_str, " ", sizeof(cmd_str));
    569             }
    570         }
    571         INFO("command '%s' action=%s status=%d (%s:%d)\n",
    572              cmd_str, cur_action ? cur_action->name : "", ret, cur_command->filename,
    573              cur_command->line);
    574     }
    575 }
    576 
    577 static int wait_for_coldboot_done_action(int nargs, char **args)
    578 {
    579     int ret;
    580     INFO("wait for %s\n", coldboot_done);
    581     ret = wait_for_file(coldboot_done, COMMAND_RETRY_TIMEOUT);
    582     if (ret)
    583         ERROR("Timed out waiting for %s\n", coldboot_done);
    584     return ret;
    585 }
    586 
    587 /*
    588  * Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
    589  * by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
    590  * Does nothing if Hardware RNG is not present.
    591  *
    592  * Since we don't yet trust the quality of Hardware RNG, these bytes are not
    593  * mixed into the primary pool of Linux RNG and the entropy estimate is left
    594  * unmodified.
    595  *
    596  * If the HW RNG device /dev/hw_random is present, we require that at least
    597  * 512 bytes read from it are written into Linux RNG. QA is expected to catch
    598  * devices/configurations where these I/O operations are blocking for a long
    599  * time. We do not reboot or halt on failures, as this is a best-effort
    600  * attempt.
    601  */
    602 static int mix_hwrng_into_linux_rng_action(int nargs, char **args)
    603 {
    604     int result = -1;
    605     int hwrandom_fd = -1;
    606     int urandom_fd = -1;
    607     char buf[512];
    608     ssize_t chunk_size;
    609     size_t total_bytes_written = 0;
    610 
    611     hwrandom_fd = TEMP_FAILURE_RETRY(
    612             open("/dev/hw_random", O_RDONLY | O_NOFOLLOW));
    613     if (hwrandom_fd == -1) {
    614         if (errno == ENOENT) {
    615           ERROR("/dev/hw_random not found\n");
    616           /* It's not an error to not have a Hardware RNG. */
    617           result = 0;
    618         } else {
    619           ERROR("Failed to open /dev/hw_random: %s\n", strerror(errno));
    620         }
    621         goto ret;
    622     }
    623 
    624     urandom_fd = TEMP_FAILURE_RETRY(
    625             open("/dev/urandom", O_WRONLY | O_NOFOLLOW));
    626     if (urandom_fd == -1) {
    627         ERROR("Failed to open /dev/urandom: %s\n", strerror(errno));
    628         goto ret;
    629     }
    630 
    631     while (total_bytes_written < sizeof(buf)) {
    632         chunk_size = TEMP_FAILURE_RETRY(
    633                 read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
    634         if (chunk_size == -1) {
    635             ERROR("Failed to read from /dev/hw_random: %s\n", strerror(errno));
    636             goto ret;
    637         } else if (chunk_size == 0) {
    638             ERROR("Failed to read from /dev/hw_random: EOF\n");
    639             goto ret;
    640         }
    641 
    642         chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
    643         if (chunk_size == -1) {
    644             ERROR("Failed to write to /dev/urandom: %s\n", strerror(errno));
    645             goto ret;
    646         }
    647         total_bytes_written += chunk_size;
    648     }
    649 
    650     INFO("Mixed %zu bytes from /dev/hw_random into /dev/urandom",
    651                 total_bytes_written);
    652     result = 0;
    653 
    654 ret:
    655     if (hwrandom_fd != -1) {
    656         close(hwrandom_fd);
    657     }
    658     if (urandom_fd != -1) {
    659         close(urandom_fd);
    660     }
    661     memset(buf, 0, sizeof(buf));
    662     return result;
    663 }
    664 
    665 static int keychord_init_action(int nargs, char **args)
    666 {
    667     keychord_init();
    668     return 0;
    669 }
    670 
    671 static int console_init_action(int nargs, char **args)
    672 {
    673     int fd;
    674 
    675     if (console[0]) {
    676         snprintf(console_name, sizeof(console_name), "/dev/%s", console);
    677     }
    678 
    679     fd = open(console_name, O_RDWR);
    680     if (fd >= 0)
    681         have_console = 1;
    682     close(fd);
    683 
    684     fd = open("/dev/tty0", O_WRONLY);
    685     if (fd >= 0) {
    686         const char *msg;
    687             msg = "\n"
    688         "\n"
    689         "\n"
    690         "\n"
    691         "\n"
    692         "\n"
    693         "\n"  // console is 40 cols x 30 lines
    694         "\n"
    695         "\n"
    696         "\n"
    697         "\n"
    698         "\n"
    699         "\n"
    700         "\n"
    701         "             A N D R O I D ";
    702         write(fd, msg, strlen(msg));
    703         close(fd);
    704     }
    705 
    706     return 0;
    707 }
    708 
    709 static void import_kernel_nv(char *name, int for_emulator)
    710 {
    711     char *value = strchr(name, '=');
    712     int name_len = strlen(name);
    713 
    714     if (value == 0) return;
    715     *value++ = 0;
    716     if (name_len == 0) return;
    717 
    718     if (for_emulator) {
    719         /* in the emulator, export any kernel option with the
    720          * ro.kernel. prefix */
    721         char buff[PROP_NAME_MAX];
    722         int len = snprintf( buff, sizeof(buff), "ro.kernel.%s", name );
    723 
    724         if (len < (int)sizeof(buff))
    725             property_set( buff, value );
    726         return;
    727     }
    728 
    729     if (!strcmp(name,"qemu")) {
    730         strlcpy(qemu, value, sizeof(qemu));
    731     } else if (!strncmp(name, "androidboot.", 12) && name_len > 12) {
    732         const char *boot_prop_name = name + 12;
    733         char prop[PROP_NAME_MAX];
    734         int cnt;
    735 
    736         cnt = snprintf(prop, sizeof(prop), "ro.boot.%s", boot_prop_name);
    737         if (cnt < PROP_NAME_MAX)
    738             property_set(prop, value);
    739     }
    740 }
    741 
    742 static void export_kernel_boot_props(void)
    743 {
    744     char tmp[PROP_VALUE_MAX];
    745     int ret;
    746     unsigned i;
    747     struct {
    748         const char *src_prop;
    749         const char *dest_prop;
    750         const char *def_val;
    751     } prop_map[] = {
    752         { "ro.boot.serialno", "ro.serialno", "", },
    753         { "ro.boot.mode", "ro.bootmode", "unknown", },
    754         { "ro.boot.baseband", "ro.baseband", "unknown", },
    755         { "ro.boot.bootloader", "ro.bootloader", "unknown", },
    756     };
    757 
    758     for (i = 0; i < ARRAY_SIZE(prop_map); i++) {
    759         ret = property_get(prop_map[i].src_prop, tmp);
    760         if (ret > 0)
    761             property_set(prop_map[i].dest_prop, tmp);
    762         else
    763             property_set(prop_map[i].dest_prop, prop_map[i].def_val);
    764     }
    765 
    766     ret = property_get("ro.boot.console", tmp);
    767     if (ret)
    768         strlcpy(console, tmp, sizeof(console));
    769 
    770     /* save a copy for init's usage during boot */
    771     property_get("ro.bootmode", tmp);
    772     strlcpy(bootmode, tmp, sizeof(bootmode));
    773 
    774     /* if this was given on kernel command line, override what we read
    775      * before (e.g. from /proc/cpuinfo), if anything */
    776     ret = property_get("ro.boot.hardware", tmp);
    777     if (ret)
    778         strlcpy(hardware, tmp, sizeof(hardware));
    779     property_set("ro.hardware", hardware);
    780 
    781     snprintf(tmp, PROP_VALUE_MAX, "%d", revision);
    782     property_set("ro.revision", tmp);
    783 
    784     /* TODO: these are obsolete. We should delete them */
    785     if (!strcmp(bootmode,"factory"))
    786         property_set("ro.factorytest", "1");
    787     else if (!strcmp(bootmode,"factory2"))
    788         property_set("ro.factorytest", "2");
    789     else
    790         property_set("ro.factorytest", "0");
    791 }
    792 
    793 static void process_kernel_cmdline(void)
    794 {
    795     /* don't expose the raw commandline to nonpriv processes */
    796     chmod("/proc/cmdline", 0440);
    797 
    798     /* first pass does the common stuff, and finds if we are in qemu.
    799      * second pass is only necessary for qemu to export all kernel params
    800      * as props.
    801      */
    802     import_kernel_cmdline(0, import_kernel_nv);
    803     if (qemu[0])
    804         import_kernel_cmdline(1, import_kernel_nv);
    805 
    806     /* now propogate the info given on command line to internal variables
    807      * used by init as well as the current required properties
    808      */
    809     export_kernel_boot_props();
    810 }
    811 
    812 static int property_service_init_action(int nargs, char **args)
    813 {
    814     /* read any property files on system or data and
    815      * fire up the property service.  This must happen
    816      * after the ro.foo properties are set above so
    817      * that /data/local.prop cannot interfere with them.
    818      */
    819     start_property_service();
    820     if (get_property_set_fd() < 0) {
    821         ERROR("start_property_service() failed\n");
    822         exit(1);
    823     }
    824 
    825     return 0;
    826 }
    827 
    828 static int signal_init_action(int nargs, char **args)
    829 {
    830     signal_init();
    831     if (get_signal_fd() < 0) {
    832         ERROR("signal_init() failed\n");
    833         exit(1);
    834     }
    835     return 0;
    836 }
    837 
    838 static int queue_property_triggers_action(int nargs, char **args)
    839 {
    840     queue_all_property_triggers();
    841     /* enable property triggers */
    842     property_triggers_enabled = 1;
    843     return 0;
    844 }
    845 
    846 #if BOOTCHART
    847 static int bootchart_init_action(int nargs, char **args)
    848 {
    849     bootchart_count = bootchart_init();
    850     if (bootchart_count < 0) {
    851         ERROR("bootcharting init failure\n");
    852     } else if (bootchart_count > 0) {
    853         NOTICE("bootcharting started (period=%d ms)\n", bootchart_count*BOOTCHART_POLLING_MS);
    854     } else {
    855         NOTICE("bootcharting ignored\n");
    856     }
    857 
    858     return 0;
    859 }
    860 #endif
    861 
    862 static const struct selinux_opt seopts_prop[] = {
    863         { SELABEL_OPT_PATH, "/property_contexts" },
    864         { SELABEL_OPT_PATH, "/data/security/current/property_contexts" },
    865         { 0, NULL }
    866 };
    867 
    868 struct selabel_handle* selinux_android_prop_context_handle(void)
    869 {
    870     int policy_index = selinux_android_use_data_policy() ? 1 : 0;
    871     struct selabel_handle* sehandle = selabel_open(SELABEL_CTX_ANDROID_PROP,
    872                                                    &seopts_prop[policy_index], 1);
    873     if (!sehandle) {
    874         ERROR("SELinux:  Could not load property_contexts:  %s\n",
    875               strerror(errno));
    876         return NULL;
    877     }
    878     INFO("SELinux: Loaded property contexts from %s\n", seopts_prop[policy_index].value);
    879     return sehandle;
    880 }
    881 
    882 void selinux_init_all_handles(void)
    883 {
    884     sehandle = selinux_android_file_context_handle();
    885     selinux_android_set_sehandle(sehandle);
    886     sehandle_prop = selinux_android_prop_context_handle();
    887 }
    888 
    889 static bool selinux_is_disabled(void)
    890 {
    891 #ifdef ALLOW_DISABLE_SELINUX
    892     char tmp[PROP_VALUE_MAX];
    893 
    894     if (access("/sys/fs/selinux", F_OK) != 0) {
    895         /* SELinux is not compiled into the kernel, or has been disabled
    896          * via the kernel command line "selinux=0".
    897          */
    898         return true;
    899     }
    900 
    901     if ((property_get("ro.boot.selinux", tmp) != 0) && (strcmp(tmp, "disabled") == 0)) {
    902         /* SELinux is compiled into the kernel, but we've been told to disable it. */
    903         return true;
    904     }
    905 #endif
    906 
    907     return false;
    908 }
    909 
    910 static bool selinux_is_enforcing(void)
    911 {
    912 #ifdef ALLOW_DISABLE_SELINUX
    913     char tmp[PROP_VALUE_MAX];
    914 
    915     if (property_get("ro.boot.selinux", tmp) == 0) {
    916         /* Property is not set.  Assume enforcing */
    917         return true;
    918     }
    919 
    920     if (strcmp(tmp, "permissive") == 0) {
    921         /* SELinux is in the kernel, but we've been told to go into permissive mode */
    922         return false;
    923     }
    924 
    925     if (strcmp(tmp, "enforcing") != 0) {
    926         ERROR("SELinux: Unknown value of ro.boot.selinux. Got: \"%s\". Assuming enforcing.\n", tmp);
    927     }
    928 
    929 #endif
    930     return true;
    931 }
    932 
    933 int selinux_reload_policy(void)
    934 {
    935     if (selinux_is_disabled()) {
    936         return -1;
    937     }
    938 
    939     INFO("SELinux: Attempting to reload policy files\n");
    940 
    941     if (selinux_android_reload_policy() == -1) {
    942         return -1;
    943     }
    944 
    945     if (sehandle)
    946         selabel_close(sehandle);
    947 
    948     if (sehandle_prop)
    949         selabel_close(sehandle_prop);
    950 
    951     selinux_init_all_handles();
    952     return 0;
    953 }
    954 
    955 static int audit_callback(void *data, security_class_t cls __attribute__((unused)), char *buf, size_t len)
    956 {
    957     snprintf(buf, len, "property=%s", !data ? "NULL" : (char *)data);
    958     return 0;
    959 }
    960 
    961 int log_callback(int type, const char *fmt, ...)
    962 {
    963     int level;
    964     va_list ap;
    965     switch (type) {
    966     case SELINUX_WARNING:
    967         level = KLOG_WARNING_LEVEL;
    968         break;
    969     case SELINUX_INFO:
    970         level = KLOG_INFO_LEVEL;
    971         break;
    972     default:
    973         level = KLOG_ERROR_LEVEL;
    974         break;
    975     }
    976     va_start(ap, fmt);
    977     klog_vwrite(level, fmt, ap);
    978     va_end(ap);
    979     return 0;
    980 }
    981 
    982 static void selinux_initialize(void)
    983 {
    984     if (selinux_is_disabled()) {
    985         return;
    986     }
    987 
    988     INFO("loading selinux policy\n");
    989     if (selinux_android_load_policy() < 0) {
    990         ERROR("SELinux: Failed to load policy; rebooting into recovery mode\n");
    991         android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
    992         while (1) { pause(); }  // never reached
    993     }
    994 
    995     selinux_init_all_handles();
    996     bool is_enforcing = selinux_is_enforcing();
    997     INFO("SELinux: security_setenforce(%d)\n", is_enforcing);
    998     security_setenforce(is_enforcing);
    999 }
   1000 
   1001 int main(int argc, char **argv)
   1002 {
   1003     int fd_count = 0;
   1004     struct pollfd ufds[4];
   1005     char *tmpdev;
   1006     char* debuggable;
   1007     char tmp[32];
   1008     int property_set_fd_init = 0;
   1009     int signal_fd_init = 0;
   1010     int keychord_fd_init = 0;
   1011     bool is_charger = false;
   1012 
   1013     if (!strcmp(basename(argv[0]), "ueventd"))
   1014         return ueventd_main(argc, argv);
   1015 
   1016     if (!strcmp(basename(argv[0]), "watchdogd"))
   1017         return watchdogd_main(argc, argv);
   1018 
   1019     /* clear the umask */
   1020     umask(0);
   1021 
   1022         /* Get the basic filesystem setup we need put
   1023          * together in the initramdisk on / and then we'll
   1024          * let the rc file figure out the rest.
   1025          */
   1026     mkdir("/dev", 0755);
   1027     mkdir("/proc", 0755);
   1028     mkdir("/sys", 0755);
   1029 
   1030     mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
   1031     mkdir("/dev/pts", 0755);
   1032     mkdir("/dev/socket", 0755);
   1033     mount("devpts", "/dev/pts", "devpts", 0, NULL);
   1034     mount("proc", "/proc", "proc", 0, NULL);
   1035     mount("sysfs", "/sys", "sysfs", 0, NULL);
   1036 
   1037         /* indicate that booting is in progress to background fw loaders, etc */
   1038     close(open("/dev/.booting", O_WRONLY | O_CREAT, 0000));
   1039 
   1040         /* We must have some place other than / to create the
   1041          * device nodes for kmsg and null, otherwise we won't
   1042          * be able to remount / read-only later on.
   1043          * Now that tmpfs is mounted on /dev, we can actually
   1044          * talk to the outside world.
   1045          */
   1046     open_devnull_stdio();
   1047     klog_init();
   1048     property_init();
   1049 
   1050     get_hardware_name(hardware, &revision);
   1051 
   1052     process_kernel_cmdline();
   1053 
   1054     union selinux_callback cb;
   1055     cb.func_log = log_callback;
   1056     selinux_set_callback(SELINUX_CB_LOG, cb);
   1057 
   1058     cb.func_audit = audit_callback;
   1059     selinux_set_callback(SELINUX_CB_AUDIT, cb);
   1060 
   1061     selinux_initialize();
   1062     /* These directories were necessarily created before initial policy load
   1063      * and therefore need their security context restored to the proper value.
   1064      * This must happen before /dev is populated by ueventd.
   1065      */
   1066     restorecon("/dev");
   1067     restorecon("/dev/socket");
   1068     restorecon("/dev/__properties__");
   1069     restorecon_recursive("/sys");
   1070 
   1071     is_charger = !strcmp(bootmode, "charger");
   1072 
   1073     INFO("property init\n");
   1074     property_load_boot_defaults();
   1075 
   1076     INFO("reading config file\n");
   1077     init_parse_config_file("/init.rc");
   1078 
   1079     action_for_each_trigger("early-init", action_add_queue_tail);
   1080 
   1081     queue_builtin_action(wait_for_coldboot_done_action, "wait_for_coldboot_done");
   1082     queue_builtin_action(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
   1083     queue_builtin_action(keychord_init_action, "keychord_init");
   1084     queue_builtin_action(console_init_action, "console_init");
   1085 
   1086     /* execute all the boot actions to get us started */
   1087     action_for_each_trigger("init", action_add_queue_tail);
   1088 
   1089     /* Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
   1090      * wasn't ready immediately after wait_for_coldboot_done
   1091      */
   1092     queue_builtin_action(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
   1093     queue_builtin_action(property_service_init_action, "property_service_init");
   1094     queue_builtin_action(signal_init_action, "signal_init");
   1095 
   1096     /* Don't mount filesystems or start core system services if in charger mode. */
   1097     if (is_charger) {
   1098         action_for_each_trigger("charger", action_add_queue_tail);
   1099     } else {
   1100         action_for_each_trigger("late-init", action_add_queue_tail);
   1101     }
   1102 
   1103     /* run all property triggers based on current state of the properties */
   1104     queue_builtin_action(queue_property_triggers_action, "queue_property_triggers");
   1105 
   1106 
   1107 #if BOOTCHART
   1108     queue_builtin_action(bootchart_init_action, "bootchart_init");
   1109 #endif
   1110 
   1111     for(;;) {
   1112         int nr, i, timeout = -1;
   1113 
   1114         execute_one_command();
   1115         restart_processes();
   1116 
   1117         if (!property_set_fd_init && get_property_set_fd() > 0) {
   1118             ufds[fd_count].fd = get_property_set_fd();
   1119             ufds[fd_count].events = POLLIN;
   1120             ufds[fd_count].revents = 0;
   1121             fd_count++;
   1122             property_set_fd_init = 1;
   1123         }
   1124         if (!signal_fd_init && get_signal_fd() > 0) {
   1125             ufds[fd_count].fd = get_signal_fd();
   1126             ufds[fd_count].events = POLLIN;
   1127             ufds[fd_count].revents = 0;
   1128             fd_count++;
   1129             signal_fd_init = 1;
   1130         }
   1131         if (!keychord_fd_init && get_keychord_fd() > 0) {
   1132             ufds[fd_count].fd = get_keychord_fd();
   1133             ufds[fd_count].events = POLLIN;
   1134             ufds[fd_count].revents = 0;
   1135             fd_count++;
   1136             keychord_fd_init = 1;
   1137         }
   1138 
   1139         if (process_needs_restart) {
   1140             timeout = (process_needs_restart - gettime()) * 1000;
   1141             if (timeout < 0)
   1142                 timeout = 0;
   1143         }
   1144 
   1145         if (!action_queue_empty() || cur_action)
   1146             timeout = 0;
   1147 
   1148 #if BOOTCHART
   1149         if (bootchart_count > 0) {
   1150             if (timeout < 0 || timeout > BOOTCHART_POLLING_MS)
   1151                 timeout = BOOTCHART_POLLING_MS;
   1152             if (bootchart_step() < 0 || --bootchart_count == 0) {
   1153                 bootchart_finish();
   1154                 bootchart_count = 0;
   1155             }
   1156         }
   1157 #endif
   1158 
   1159         nr = poll(ufds, fd_count, timeout);
   1160         if (nr <= 0)
   1161             continue;
   1162 
   1163         for (i = 0; i < fd_count; i++) {
   1164             if (ufds[i].revents & POLLIN) {
   1165                 if (ufds[i].fd == get_property_set_fd())
   1166                     handle_property_set_fd();
   1167                 else if (ufds[i].fd == get_keychord_fd())
   1168                     handle_keychord();
   1169                 else if (ufds[i].fd == get_signal_fd())
   1170                     handle_signal();
   1171             }
   1172         }
   1173     }
   1174 
   1175     return 0;
   1176 }
   1177