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