init.c revision cfa0d8439384a1aaa53d31fb720c234cabf796ee
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#include <libgen.h>
35
36#include <cutils/sockets.h>
37#include <cutils/iosched_policy.h>
38#include <private/android_filesystem_config.h>
39#include <termios.h>
40
41#include <sys/system_properties.h>
42
43#include "devices.h"
44#include "init.h"
45#include "list.h"
46#include "log.h"
47#include "property_service.h"
48#include "bootchart.h"
49#include "signal_handler.h"
50#include "keychords.h"
51#include "init_parser.h"
52#include "util.h"
53#include "ueventd.h"
54
55static int property_triggers_enabled = 0;
56
57#if BOOTCHART
58static int   bootchart_count;
59#endif
60
61static char console[32];
62static char serialno[32];
63static char bootmode[32];
64static char baseband[32];
65static char carrier[32];
66static char bootloader[32];
67static char hardware[32];
68static unsigned revision = 0;
69static char qemu[32];
70
71static struct action *cur_action = NULL;
72static struct command *cur_command = NULL;
73static struct listnode *command_queue = NULL;
74
75void notify_service_state(const char *name, const char *state)
76{
77    char pname[PROP_NAME_MAX];
78    int len = strlen(name);
79    if ((len + 10) > PROP_NAME_MAX)
80        return;
81    snprintf(pname, sizeof(pname), "init.svc.%s", name);
82    property_set(pname, state);
83}
84
85static int have_console;
86static char *console_name = "/dev/console";
87static time_t process_needs_restart;
88
89static const char *ENV[32];
90
91/* add_environment - add "key=value" to the current environment */
92int add_environment(const char *key, const char *val)
93{
94    int n;
95
96    for (n = 0; n < 31; n++) {
97        if (!ENV[n]) {
98            size_t len = strlen(key) + strlen(val) + 2;
99            char *entry = malloc(len);
100            snprintf(entry, len, "%s=%s", key, val);
101            ENV[n] = entry;
102            return 0;
103        }
104    }
105
106    return 1;
107}
108
109static void zap_stdio(void)
110{
111    int fd;
112    fd = open("/dev/null", O_RDWR);
113    dup2(fd, 0);
114    dup2(fd, 1);
115    dup2(fd, 2);
116    close(fd);
117}
118
119static void open_console()
120{
121    int fd;
122    if ((fd = open(console_name, O_RDWR)) < 0) {
123        fd = open("/dev/null", O_RDWR);
124    }
125    dup2(fd, 0);
126    dup2(fd, 1);
127    dup2(fd, 2);
128    close(fd);
129}
130
131static void publish_socket(const char *name, int fd)
132{
133    char key[64] = ANDROID_SOCKET_ENV_PREFIX;
134    char val[64];
135
136    strlcpy(key + sizeof(ANDROID_SOCKET_ENV_PREFIX) - 1,
137            name,
138            sizeof(key) - sizeof(ANDROID_SOCKET_ENV_PREFIX));
139    snprintf(val, sizeof(val), "%d", fd);
140    add_environment(key, val);
141
142    /* make sure we don't close-on-exec */
143    fcntl(fd, F_SETFD, 0);
144}
145
146void service_start(struct service *svc, const char *dynamic_args)
147{
148    struct stat s;
149    pid_t pid;
150    int needs_console;
151    int n;
152
153        /* starting a service removes it from the disabled
154         * state and immediately takes it out of the restarting
155         * state if it was in there
156         */
157    svc->flags &= (~(SVC_DISABLED|SVC_RESTARTING));
158    svc->time_started = 0;
159
160        /* running processes require no additional work -- if
161         * they're in the process of exiting, we've ensured
162         * that they will immediately restart on exit, unless
163         * they are ONESHOT
164         */
165    if (svc->flags & SVC_RUNNING) {
166        return;
167    }
168
169    needs_console = (svc->flags & SVC_CONSOLE) ? 1 : 0;
170    if (needs_console && (!have_console)) {
171        ERROR("service '%s' requires console\n", svc->name);
172        svc->flags |= SVC_DISABLED;
173        return;
174    }
175
176    if (stat(svc->args[0], &s) != 0) {
177        ERROR("cannot find '%s', disabling '%s'\n", svc->args[0], svc->name);
178        svc->flags |= SVC_DISABLED;
179        return;
180    }
181
182    if ((!(svc->flags & SVC_ONESHOT)) && dynamic_args) {
183        ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
184               svc->args[0]);
185        svc->flags |= SVC_DISABLED;
186        return;
187    }
188
189    NOTICE("starting '%s'\n", svc->name);
190
191    pid = fork();
192
193    if (pid == 0) {
194        struct socketinfo *si;
195        struct svcenvinfo *ei;
196        char tmp[32];
197        int fd, sz;
198
199        if (properties_inited()) {
200            get_property_workspace(&fd, &sz);
201            sprintf(tmp, "%d,%d", dup(fd), sz);
202            add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);
203        }
204
205        for (ei = svc->envvars; ei; ei = ei->next)
206            add_environment(ei->name, ei->value);
207
208        for (si = svc->sockets; si; si = si->next) {
209            int socket_type = (
210                    !strcmp(si->type, "stream") ? SOCK_STREAM :
211                        (!strcmp(si->type, "dgram") ? SOCK_DGRAM : SOCK_SEQPACKET));
212            int s = create_socket(si->name, socket_type,
213                                  si->perm, si->uid, si->gid);
214            if (s >= 0) {
215                publish_socket(si->name, s);
216            }
217        }
218
219        if (svc->ioprio_class != IoSchedClass_NONE) {
220            if (android_set_ioprio(getpid(), svc->ioprio_class, svc->ioprio_pri)) {
221                ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
222                      getpid(), svc->ioprio_class, svc->ioprio_pri, strerror(errno));
223            }
224        }
225
226        if (needs_console) {
227            setsid();
228            open_console();
229        } else {
230            zap_stdio();
231        }
232
233#if 0
234        for (n = 0; svc->args[n]; n++) {
235            INFO("args[%d] = '%s'\n", n, svc->args[n]);
236        }
237        for (n = 0; ENV[n]; n++) {
238            INFO("env[%d] = '%s'\n", n, ENV[n]);
239        }
240#endif
241
242        setpgid(0, getpid());
243
244    /* as requested, set our gid, supplemental gids, and uid */
245        if (svc->gid) {
246            setgid(svc->gid);
247        }
248        if (svc->nr_supp_gids) {
249            setgroups(svc->nr_supp_gids, svc->supp_gids);
250        }
251        if (svc->uid) {
252            setuid(svc->uid);
253        }
254
255        if (!dynamic_args) {
256            if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
257                ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
258            }
259        } else {
260            char *arg_ptrs[INIT_PARSER_MAXARGS+1];
261            int arg_idx = svc->nargs;
262            char *tmp = strdup(dynamic_args);
263            char *next = tmp;
264            char *bword;
265
266            /* Copy the static arguments */
267            memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));
268
269            while((bword = strsep(&next, " "))) {
270                arg_ptrs[arg_idx++] = bword;
271                if (arg_idx == INIT_PARSER_MAXARGS)
272                    break;
273            }
274            arg_ptrs[arg_idx] = '\0';
275            execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
276        }
277        _exit(127);
278    }
279
280    if (pid < 0) {
281        ERROR("failed to start '%s'\n", svc->name);
282        svc->pid = 0;
283        return;
284    }
285
286    svc->time_started = gettime();
287    svc->pid = pid;
288    svc->flags |= SVC_RUNNING;
289
290    if (properties_inited())
291        notify_service_state(svc->name, "running");
292}
293
294void service_stop(struct service *svc)
295{
296        /* we are no longer running, nor should we
297         * attempt to restart
298         */
299    svc->flags &= (~(SVC_RUNNING|SVC_RESTARTING));
300
301        /* if the service has not yet started, prevent
302         * it from auto-starting with its class
303         */
304    svc->flags |= SVC_DISABLED;
305
306    if (svc->pid) {
307        NOTICE("service '%s' is being killed\n", svc->name);
308        kill(-svc->pid, SIGTERM);
309        notify_service_state(svc->name, "stopping");
310    } else {
311        notify_service_state(svc->name, "stopped");
312    }
313}
314
315void property_changed(const char *name, const char *value)
316{
317    if (property_triggers_enabled)
318        queue_property_triggers(name, value);
319}
320
321static void restart_service_if_needed(struct service *svc)
322{
323    time_t next_start_time = svc->time_started + 5;
324
325    if (next_start_time <= gettime()) {
326        svc->flags &= (~SVC_RESTARTING);
327        service_start(svc, NULL);
328        return;
329    }
330
331    if ((next_start_time < process_needs_restart) ||
332        (process_needs_restart == 0)) {
333        process_needs_restart = next_start_time;
334    }
335}
336
337static void restart_processes()
338{
339    process_needs_restart = 0;
340    service_for_each_flags(SVC_RESTARTING,
341                           restart_service_if_needed);
342}
343
344static void msg_start(const char *name)
345{
346    struct service *svc;
347    char *tmp = NULL;
348    char *args = NULL;
349
350    if (!strchr(name, ':'))
351        svc = service_find_by_name(name);
352    else {
353        tmp = strdup(name);
354        args = strchr(tmp, ':');
355        *args = '\0';
356        args++;
357
358        svc = service_find_by_name(tmp);
359    }
360
361    if (svc) {
362        service_start(svc, args);
363    } else {
364        ERROR("no such service '%s'\n", name);
365    }
366    if (tmp)
367        free(tmp);
368}
369
370static void msg_stop(const char *name)
371{
372    struct service *svc = service_find_by_name(name);
373
374    if (svc) {
375        service_stop(svc);
376    } else {
377        ERROR("no such service '%s'\n", name);
378    }
379}
380
381void handle_control_message(const char *msg, const char *arg)
382{
383    if (!strcmp(msg,"start")) {
384        msg_start(arg);
385    } else if (!strcmp(msg,"stop")) {
386        msg_stop(arg);
387    } else if (!strcmp(msg,"restart")) {
388        msg_stop(arg);
389        msg_start(arg);
390    } else {
391        ERROR("unknown control msg '%s'\n", msg);
392    }
393}
394
395static void import_kernel_nv(char *name, int in_qemu)
396{
397    char *value = strchr(name, '=');
398
399    if (value == 0) return;
400    *value++ = 0;
401    if (*name == 0) return;
402
403    if (!in_qemu)
404    {
405        /* on a real device, white-list the kernel options */
406        if (!strcmp(name,"qemu")) {
407            strlcpy(qemu, value, sizeof(qemu));
408        } else if (!strcmp(name,"androidboot.console")) {
409            strlcpy(console, value, sizeof(console));
410        } else if (!strcmp(name,"androidboot.mode")) {
411            strlcpy(bootmode, value, sizeof(bootmode));
412        } else if (!strcmp(name,"androidboot.serialno")) {
413            strlcpy(serialno, value, sizeof(serialno));
414        } else if (!strcmp(name,"androidboot.baseband")) {
415            strlcpy(baseband, value, sizeof(baseband));
416        } else if (!strcmp(name,"androidboot.carrier")) {
417            strlcpy(carrier, value, sizeof(carrier));
418        } else if (!strcmp(name,"androidboot.bootloader")) {
419            strlcpy(bootloader, value, sizeof(bootloader));
420        } else if (!strcmp(name,"androidboot.hardware")) {
421            strlcpy(hardware, value, sizeof(hardware));
422        }
423    } else {
424        /* in the emulator, export any kernel option with the
425         * ro.kernel. prefix */
426        char  buff[32];
427        int   len = snprintf( buff, sizeof(buff), "ro.kernel.%s", name );
428        if (len < (int)sizeof(buff)) {
429            property_set( buff, value );
430        }
431    }
432}
433
434static void import_kernel_cmdline(int in_qemu)
435{
436    char cmdline[1024];
437    char *ptr;
438    int fd;
439
440    fd = open("/proc/cmdline", O_RDONLY);
441    if (fd >= 0) {
442        int n = read(fd, cmdline, 1023);
443        if (n < 0) n = 0;
444
445        /* get rid of trailing newline, it happens */
446        if (n > 0 && cmdline[n-1] == '\n') n--;
447
448        cmdline[n] = 0;
449        close(fd);
450    } else {
451        cmdline[0] = 0;
452    }
453
454    ptr = cmdline;
455    while (ptr && *ptr) {
456        char *x = strchr(ptr, ' ');
457        if (x != 0) *x++ = 0;
458        import_kernel_nv(ptr, in_qemu);
459        ptr = x;
460    }
461
462        /* don't expose the raw commandline to nonpriv processes */
463    chmod("/proc/cmdline", 0440);
464}
465
466static struct command *get_first_command(struct action *act)
467{
468    struct listnode *node;
469    node = list_head(&act->commands);
470    if (!node)
471        return NULL;
472
473    return node_to_item(node, struct command, clist);
474}
475
476static struct command *get_next_command(struct action *act, struct command *cmd)
477{
478    struct listnode *node;
479    node = cmd->clist.next;
480    if (!node)
481        return NULL;
482    if (node == &act->commands)
483        return NULL;
484
485    return node_to_item(node, struct command, clist);
486}
487
488static int is_last_command(struct action *act, struct command *cmd)
489{
490    return (list_tail(&act->commands) == &cmd->clist);
491}
492
493void execute_one_command(void)
494{
495    int ret;
496
497    if (!cur_action || !cur_command || is_last_command(cur_action, cur_command)) {
498        cur_action = action_remove_queue_head();
499        cur_command = NULL;
500        if (!cur_action)
501            return;
502        INFO("processing action %p (%s)\n", cur_action, cur_action->name);
503        cur_command = get_first_command(cur_action);
504    } else {
505        cur_command = get_next_command(cur_action, cur_command);
506    }
507
508    if (!cur_command)
509        return;
510
511    ret = cur_command->func(cur_command->nargs, cur_command->args);
512    INFO("command '%s' r=%d\n", cur_command->args[0], ret);
513}
514
515static int wait_for_coldboot_done_action(int nargs, char **args)
516{
517    int ret;
518    INFO("wait for %s\n", coldboot_done);
519    ret = wait_for_file(coldboot_done, COMMAND_RETRY_TIMEOUT);
520    if (ret)
521        ERROR("Timed out waiting for %s\n", coldboot_done);
522    return ret;
523}
524
525static int property_init_action(int nargs, char **args)
526{
527    INFO("property init\n");
528    property_init();
529    return 0;
530}
531
532static int keychord_init_action(int nargs, char **args)
533{
534    keychord_init();
535    return 0;
536}
537
538static int console_init_action(int nargs, char **args)
539{
540    int fd;
541    char tmp[PROP_VALUE_MAX];
542
543    if (console[0]) {
544        snprintf(tmp, sizeof(tmp), "/dev/%s", console);
545        console_name = strdup(tmp);
546    }
547
548    fd = open(console_name, O_RDWR);
549    if (fd >= 0)
550        have_console = 1;
551    close(fd);
552
553    if( load_565rle_image(INIT_IMAGE_FILE) ) {
554        fd = open("/dev/tty0", O_WRONLY);
555        if (fd >= 0) {
556            const char *msg;
557                msg = "\n"
558            "\n"
559            "\n"
560            "\n"
561            "\n"
562            "\n"
563            "\n"  // console is 40 cols x 30 lines
564            "\n"
565            "\n"
566            "\n"
567            "\n"
568            "\n"
569            "\n"
570            "\n"
571            "             A N D R O I D ";
572            write(fd, msg, strlen(msg));
573            close(fd);
574        }
575    }
576    return 0;
577}
578
579static int set_init_properties_action(int nargs, char **args)
580{
581    char tmp[PROP_VALUE_MAX];
582
583    if (qemu[0])
584        import_kernel_cmdline(1);
585
586    if (!strcmp(bootmode,"factory"))
587        property_set("ro.factorytest", "1");
588    else if (!strcmp(bootmode,"factory2"))
589        property_set("ro.factorytest", "2");
590    else
591        property_set("ro.factorytest", "0");
592
593    property_set("ro.serialno", serialno[0] ? serialno : "");
594    property_set("ro.bootmode", bootmode[0] ? bootmode : "unknown");
595    property_set("ro.baseband", baseband[0] ? baseband : "unknown");
596    property_set("ro.carrier", carrier[0] ? carrier : "unknown");
597    property_set("ro.bootloader", bootloader[0] ? bootloader : "unknown");
598
599    property_set("ro.hardware", hardware);
600    snprintf(tmp, PROP_VALUE_MAX, "%d", revision);
601    property_set("ro.revision", tmp);
602    return 0;
603}
604
605static int property_service_init_action(int nargs, char **args)
606{
607    /* read any property files on system or data and
608     * fire up the property service.  This must happen
609     * after the ro.foo properties are set above so
610     * that /data/local.prop cannot interfere with them.
611     */
612    start_property_service();
613    return 0;
614}
615
616static int signal_init_action(int nargs, char **args)
617{
618    signal_init();
619    return 0;
620}
621
622static int check_startup_action(int nargs, char **args)
623{
624    /* make sure we actually have all the pieces we need */
625    if ((get_property_set_fd() < 0) ||
626        (get_signal_fd() < 0)) {
627        ERROR("init startup failure\n");
628        exit(1);
629    }
630    return 0;
631}
632
633static int queue_property_triggers_action(int nargs, char **args)
634{
635    queue_all_property_triggers();
636    /* enable property triggers */
637    property_triggers_enabled = 1;
638    return 0;
639}
640
641#if BOOTCHART
642static int bootchart_init_action(int nargs, char **args)
643{
644    bootchart_count = bootchart_init();
645    if (bootchart_count < 0) {
646        ERROR("bootcharting init failure\n");
647    } else if (bootchart_count > 0) {
648        NOTICE("bootcharting started (period=%d ms)\n", bootchart_count*BOOTCHART_POLLING_MS);
649    } else {
650        NOTICE("bootcharting ignored\n");
651    }
652}
653#endif
654
655int main(int argc, char **argv)
656{
657    int fd_count = 0;
658    struct pollfd ufds[4];
659    char *tmpdev;
660    char* debuggable;
661    char tmp[32];
662    int property_set_fd_init = 0;
663    int signal_fd_init = 0;
664    int keychord_fd_init = 0;
665
666    if (!strcmp(basename(argv[0]), "ueventd"))
667        return ueventd_main(argc, argv);
668
669    /* clear the umask */
670    umask(0);
671
672        /* Get the basic filesystem setup we need put
673         * together in the initramdisk on / and then we'll
674         * let the rc file figure out the rest.
675         */
676    mkdir("/dev", 0755);
677    mkdir("/proc", 0755);
678    mkdir("/sys", 0755);
679
680    mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
681    mkdir("/dev/pts", 0755);
682    mkdir("/dev/socket", 0755);
683    mount("devpts", "/dev/pts", "devpts", 0, NULL);
684    mount("proc", "/proc", "proc", 0, NULL);
685    mount("sysfs", "/sys", "sysfs", 0, NULL);
686
687        /* We must have some place other than / to create the
688         * device nodes for kmsg and null, otherwise we won't
689         * be able to remount / read-only later on.
690         * Now that tmpfs is mounted on /dev, we can actually
691         * talk to the outside world.
692         */
693    open_devnull_stdio();
694    log_init();
695
696    INFO("reading config file\n");
697    init_parse_config_file("/init.rc");
698
699    /* pull the kernel commandline and ramdisk properties file in */
700    import_kernel_cmdline(0);
701
702    get_hardware_name(hardware, &revision);
703    snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);
704    init_parse_config_file(tmp);
705
706    action_for_each_trigger("early-init", action_add_queue_tail);
707
708    queue_builtin_action(wait_for_coldboot_done_action, "wait_for_coldboot_done");
709    queue_builtin_action(property_init_action, "property_init");
710    queue_builtin_action(keychord_init_action, "keychord_init");
711    queue_builtin_action(console_init_action, "console_init");
712    queue_builtin_action(set_init_properties_action, "set_init_properties");
713
714        /* execute all the boot actions to get us started */
715    action_for_each_trigger("init", action_add_queue_tail);
716    action_for_each_trigger("early-fs", action_add_queue_tail);
717    action_for_each_trigger("fs", action_add_queue_tail);
718    action_for_each_trigger("post-fs", action_add_queue_tail);
719
720    queue_builtin_action(property_service_init_action, "property_service_init");
721    queue_builtin_action(signal_init_action, "signal_init");
722    queue_builtin_action(check_startup_action, "check_startup");
723
724    /* execute all the boot actions to get us started */
725    action_for_each_trigger("early-boot", action_add_queue_tail);
726    action_for_each_trigger("boot", action_add_queue_tail);
727
728        /* run all property triggers based on current state of the properties */
729    queue_builtin_action(queue_property_triggers_action, "queue_propety_triggers");
730
731
732#if BOOTCHART
733    queue_builtin_action(bootchart_init_action, "bootchart_init");
734#endif
735
736    for(;;) {
737        int nr, i, timeout = -1;
738
739        execute_one_command();
740        restart_processes();
741
742        if (!property_set_fd_init && get_property_set_fd() > 0) {
743            ufds[fd_count].fd = get_property_set_fd();
744            ufds[fd_count].events = POLLIN;
745            ufds[fd_count].revents = 0;
746            fd_count++;
747            property_set_fd_init = 1;
748        }
749        if (!signal_fd_init && get_signal_fd() > 0) {
750            ufds[fd_count].fd = get_signal_fd();
751            ufds[fd_count].events = POLLIN;
752            ufds[fd_count].revents = 0;
753            fd_count++;
754            signal_fd_init = 1;
755        }
756        if (!keychord_fd_init && get_keychord_fd() > 0) {
757            ufds[fd_count].fd = get_keychord_fd();
758            ufds[fd_count].events = POLLIN;
759            ufds[fd_count].revents = 0;
760            fd_count++;
761            keychord_fd_init = 1;
762        }
763
764        if (process_needs_restart) {
765            timeout = (process_needs_restart - gettime()) * 1000;
766            if (timeout < 0)
767                timeout = 0;
768        }
769
770        if (!action_queue_empty() || cur_action)
771            timeout = 0;
772
773#if BOOTCHART
774        if (bootchart_count > 0) {
775            if (timeout < 0 || timeout > BOOTCHART_POLLING_MS)
776                timeout = BOOTCHART_POLLING_MS;
777            if (bootchart_step() < 0 || --bootchart_count == 0) {
778                bootchart_finish();
779                bootchart_count = 0;
780            }
781        }
782#endif
783
784        nr = poll(ufds, fd_count, timeout);
785        if (nr <= 0)
786            continue;
787
788        for (i = 0; i < fd_count; i++) {
789            if (ufds[i].revents == POLLIN) {
790                if (ufds[i].fd == get_property_set_fd())
791                    handle_property_set_fd();
792                else if (ufds[i].fd == get_keychord_fd())
793                    handle_keychord();
794                else if (ufds[i].fd == get_signal_fd())
795                    handle_signal();
796            }
797        }
798    }
799
800    return 0;
801}
802