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