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 "builtins.h"
18 
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <mntent.h>
23 #include <net/if.h>
24 #include <signal.h>
25 #include <sched.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/socket.h>
30 #include <sys/mount.h>
31 #include <sys/resource.h>
32 #include <sys/syscall.h>
33 #include <sys/time.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <unistd.h>
38 #include <linux/loop.h>
39 #include <ext4_crypt.h>
40 #include <ext4_crypt_init_extensions.h>
41 
42 #include <selinux/selinux.h>
43 #include <selinux/label.h>
44 
45 #include <fs_mgr.h>
46 #include <android-base/file.h>
47 #include <android-base/parseint.h>
48 #include <android-base/stringprintf.h>
49 #include <bootloader_message_writer.h>
50 #include <cutils/partition_utils.h>
51 #include <cutils/android_reboot.h>
52 #include <logwrap/logwrap.h>
53 #include <private/android_filesystem_config.h>
54 
55 #include "action.h"
56 #include "bootchart.h"
57 #include "devices.h"
58 #include "init.h"
59 #include "init_parser.h"
60 #include "log.h"
61 #include "property_service.h"
62 #include "service.h"
63 #include "signal_handler.h"
64 #include "util.h"
65 
66 #define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
67 #define UNMOUNT_CHECK_MS 5000
68 #define UNMOUNT_CHECK_TIMES 10
69 
70 static const int kTerminateServiceDelayMicroSeconds = 50000;
71 
insmod(const char * filename,const char * options)72 static int insmod(const char *filename, const char *options) {
73     int fd = open(filename, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
74     if (fd == -1) {
75         ERROR("insmod: open(\"%s\") failed: %s", filename, strerror(errno));
76         return -1;
77     }
78     int rc = syscall(__NR_finit_module, fd, options, 0);
79     if (rc == -1) {
80         ERROR("finit_module for \"%s\" failed: %s", filename, strerror(errno));
81     }
82     close(fd);
83     return rc;
84 }
85 
__ifupdown(const char * interface,int up)86 static int __ifupdown(const char *interface, int up) {
87     struct ifreq ifr;
88     int s, ret;
89 
90     strlcpy(ifr.ifr_name, interface, IFNAMSIZ);
91 
92     s = socket(AF_INET, SOCK_DGRAM, 0);
93     if (s < 0)
94         return -1;
95 
96     ret = ioctl(s, SIOCGIFFLAGS, &ifr);
97     if (ret < 0) {
98         goto done;
99     }
100 
101     if (up)
102         ifr.ifr_flags |= IFF_UP;
103     else
104         ifr.ifr_flags &= ~IFF_UP;
105 
106     ret = ioctl(s, SIOCSIFFLAGS, &ifr);
107 
108 done:
109     close(s);
110     return ret;
111 }
112 
113 // Turn off backlight while we are performing power down cleanup activities.
turnOffBacklight()114 static void turnOffBacklight() {
115     static const char off[] = "0";
116 
117     android::base::WriteStringToFile(off, "/sys/class/leds/lcd-backlight/brightness");
118 
119     static const char backlightDir[] = "/sys/class/backlight";
120     std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(backlightDir), closedir);
121     if (!dir) {
122         return;
123     }
124 
125     struct dirent *dp;
126     while ((dp = readdir(dir.get())) != NULL) {
127         if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) ||
128                 (dp->d_name[0] == '.')) {
129             continue;
130         }
131 
132         std::string fileName = android::base::StringPrintf("%s/%s/brightness",
133                                                            backlightDir,
134                                                            dp->d_name);
135         android::base::WriteStringToFile(off, fileName);
136     }
137 }
138 
wipe_data_via_recovery(const std::string & reason)139 static int wipe_data_via_recovery(const std::string& reason) {
140     const std::vector<std::string> options = {"--wipe_data", std::string() + "--reason=" + reason};
141     std::string err;
142     if (!write_bootloader_message(options, &err)) {
143         ERROR("failed to set bootloader message: %s", err.c_str());
144         return -1;
145     }
146     android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
147     while (1) { pause(); }  // never reached
148 }
149 
unmount_and_fsck(const struct mntent * entry)150 static void unmount_and_fsck(const struct mntent *entry) {
151     if (strcmp(entry->mnt_type, "f2fs") && strcmp(entry->mnt_type, "ext4"))
152         return;
153 
154     /* First, lazily unmount the directory. This unmount request finishes when
155      * all processes that open a file or directory in |entry->mnt_dir| exit.
156      */
157     TEMP_FAILURE_RETRY(umount2(entry->mnt_dir, MNT_DETACH));
158 
159     /* Next, kill all processes except init, kthreadd, and kthreadd's
160      * children to finish the lazy unmount. Killing all processes here is okay
161      * because this callback function is only called right before reboot().
162      * It might be cleaner to selectively kill processes that actually use
163      * |entry->mnt_dir| rather than killing all, probably by reusing a function
164      * like killProcessesWithOpenFiles() in vold/, but the selinux policy does
165      * not allow init to scan /proc/<pid> files which the utility function
166      * heavily relies on. The policy does not allow the process to execute
167      * killall/pkill binaries either. Note that some processes might
168      * automatically restart after kill(), but that is not really a problem
169      * because |entry->mnt_dir| is no longer visible to such new processes.
170      */
171     ServiceManager::GetInstance().ForEachService([] (Service* s) { s->Stop(); });
172     TEMP_FAILURE_RETRY(kill(-1, SIGKILL));
173 
174     // Restart Watchdogd to allow us to complete umounting and fsck
175     Service *svc = ServiceManager::GetInstance().FindServiceByName("watchdogd");
176     if (svc) {
177         do {
178             sched_yield(); // do not be so eager, let cleanup have priority
179             ServiceManager::GetInstance().ReapAnyOutstandingChildren();
180         } while (svc->flags() & SVC_RUNNING); // Paranoid Cargo
181         svc->Start();
182     }
183 
184     turnOffBacklight();
185 
186     int count = 0;
187     while (count++ < UNMOUNT_CHECK_TIMES) {
188         int fd = TEMP_FAILURE_RETRY(open(entry->mnt_fsname, O_RDONLY | O_EXCL));
189         if (fd >= 0) {
190             /* |entry->mnt_dir| has sucessfully been unmounted. */
191             close(fd);
192             break;
193         } else if (errno == EBUSY) {
194             /* Some processes using |entry->mnt_dir| are still alive. Wait for a
195              * while then retry.
196              */
197             TEMP_FAILURE_RETRY(
198                 usleep(UNMOUNT_CHECK_MS * 1000 / UNMOUNT_CHECK_TIMES));
199             continue;
200         } else {
201             /* Cannot open the device. Give up. */
202             return;
203         }
204     }
205 
206     // NB: With watchdog still running, there is no cap on the time it takes
207     // to complete the fsck, from the users perspective the device graphics
208     // and responses are locked-up and they may choose to hold the power
209     // button in frustration if it drags out.
210 
211     int st;
212     if (!strcmp(entry->mnt_type, "f2fs")) {
213         const char *f2fs_argv[] = {
214             "/system/bin/fsck.f2fs", "-f", entry->mnt_fsname,
215         };
216         android_fork_execvp_ext(ARRAY_SIZE(f2fs_argv), (char **)f2fs_argv,
217                                 &st, true, LOG_KLOG, true, NULL, NULL, 0);
218     } else if (!strcmp(entry->mnt_type, "ext4")) {
219         const char *ext4_argv[] = {
220             "/system/bin/e2fsck", "-f", "-y", entry->mnt_fsname,
221         };
222         android_fork_execvp_ext(ARRAY_SIZE(ext4_argv), (char **)ext4_argv,
223                                 &st, true, LOG_KLOG, true, NULL, NULL, 0);
224     }
225 }
226 
do_class_start(const std::vector<std::string> & args)227 static int do_class_start(const std::vector<std::string>& args) {
228         /* Starting a class does not start services
229          * which are explicitly disabled.  They must
230          * be started individually.
231          */
232     ServiceManager::GetInstance().
233         ForEachServiceInClass(args[1], [] (Service* s) { s->StartIfNotDisabled(); });
234     return 0;
235 }
236 
do_class_stop(const std::vector<std::string> & args)237 static int do_class_stop(const std::vector<std::string>& args) {
238     ServiceManager::GetInstance().
239         ForEachServiceInClass(args[1], [] (Service* s) { s->Stop(); });
240     return 0;
241 }
242 
do_class_reset(const std::vector<std::string> & args)243 static int do_class_reset(const std::vector<std::string>& args) {
244     ServiceManager::GetInstance().
245         ForEachServiceInClass(args[1], [] (Service* s) { s->Reset(); });
246     return 0;
247 }
248 
do_domainname(const std::vector<std::string> & args)249 static int do_domainname(const std::vector<std::string>& args) {
250     return write_file("/proc/sys/kernel/domainname", args[1].c_str());
251 }
252 
do_enable(const std::vector<std::string> & args)253 static int do_enable(const std::vector<std::string>& args) {
254     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
255     if (!svc) {
256         return -1;
257     }
258     return svc->Enable();
259 }
260 
do_exec(const std::vector<std::string> & args)261 static int do_exec(const std::vector<std::string>& args) {
262     Service* svc = ServiceManager::GetInstance().MakeExecOneshotService(args);
263     if (!svc) {
264         return -1;
265     }
266     if (!svc->Start()) {
267         return -1;
268     }
269     waiting_for_exec = true;
270     return 0;
271 }
272 
do_export(const std::vector<std::string> & args)273 static int do_export(const std::vector<std::string>& args) {
274     return add_environment(args[1].c_str(), args[2].c_str());
275 }
276 
do_hostname(const std::vector<std::string> & args)277 static int do_hostname(const std::vector<std::string>& args) {
278     return write_file("/proc/sys/kernel/hostname", args[1].c_str());
279 }
280 
do_ifup(const std::vector<std::string> & args)281 static int do_ifup(const std::vector<std::string>& args) {
282     return __ifupdown(args[1].c_str(), 1);
283 }
284 
do_insmod(const std::vector<std::string> & args)285 static int do_insmod(const std::vector<std::string>& args) {
286     std::string options;
287 
288     if (args.size() > 2) {
289         options += args[2];
290         for (std::size_t i = 3; i < args.size(); ++i) {
291             options += ' ';
292             options += args[i];
293         }
294     }
295 
296     return insmod(args[1].c_str(), options.c_str());
297 }
298 
do_mkdir(const std::vector<std::string> & args)299 static int do_mkdir(const std::vector<std::string>& args) {
300     mode_t mode = 0755;
301     int ret;
302 
303     /* mkdir <path> [mode] [owner] [group] */
304 
305     if (args.size() >= 3) {
306         mode = std::stoul(args[2], 0, 8);
307     }
308 
309     ret = make_dir(args[1].c_str(), mode);
310     /* chmod in case the directory already exists */
311     if (ret == -1 && errno == EEXIST) {
312         ret = fchmodat(AT_FDCWD, args[1].c_str(), mode, AT_SYMLINK_NOFOLLOW);
313     }
314     if (ret == -1) {
315         return -errno;
316     }
317 
318     if (args.size() >= 4) {
319         uid_t uid = decode_uid(args[3].c_str());
320         gid_t gid = -1;
321 
322         if (args.size() == 5) {
323             gid = decode_uid(args[4].c_str());
324         }
325 
326         if (lchown(args[1].c_str(), uid, gid) == -1) {
327             return -errno;
328         }
329 
330         /* chown may have cleared S_ISUID and S_ISGID, chmod again */
331         if (mode & (S_ISUID | S_ISGID)) {
332             ret = fchmodat(AT_FDCWD, args[1].c_str(), mode, AT_SYMLINK_NOFOLLOW);
333             if (ret == -1) {
334                 return -errno;
335             }
336         }
337     }
338 
339     if (e4crypt_is_native()) {
340         if (e4crypt_set_directory_policy(args[1].c_str())) {
341             wipe_data_via_recovery(std::string() + "set_policy_failed:" + args[1]);
342             return -1;
343         }
344     }
345     return 0;
346 }
347 
348 static struct {
349     const char *name;
350     unsigned flag;
351 } mount_flags[] = {
352     { "noatime",    MS_NOATIME },
353     { "noexec",     MS_NOEXEC },
354     { "nosuid",     MS_NOSUID },
355     { "nodev",      MS_NODEV },
356     { "nodiratime", MS_NODIRATIME },
357     { "ro",         MS_RDONLY },
358     { "rw",         0 },
359     { "remount",    MS_REMOUNT },
360     { "bind",       MS_BIND },
361     { "rec",        MS_REC },
362     { "unbindable", MS_UNBINDABLE },
363     { "private",    MS_PRIVATE },
364     { "slave",      MS_SLAVE },
365     { "shared",     MS_SHARED },
366     { "defaults",   0 },
367     { 0,            0 },
368 };
369 
370 #define DATA_MNT_POINT "/data"
371 
372 /* mount <type> <device> <path> <flags ...> <options> */
do_mount(const std::vector<std::string> & args)373 static int do_mount(const std::vector<std::string>& args) {
374     char tmp[64];
375     const char *source, *target, *system;
376     const char *options = NULL;
377     unsigned flags = 0;
378     std::size_t na = 0;
379     int n, i;
380     int wait = 0;
381 
382     for (na = 4; na < args.size(); na++) {
383         for (i = 0; mount_flags[i].name; i++) {
384             if (!args[na].compare(mount_flags[i].name)) {
385                 flags |= mount_flags[i].flag;
386                 break;
387             }
388         }
389 
390         if (!mount_flags[i].name) {
391             if (!args[na].compare("wait"))
392                 wait = 1;
393             /* if our last argument isn't a flag, wolf it up as an option string */
394             else if (na + 1 == args.size())
395                 options = args[na].c_str();
396         }
397     }
398 
399     system = args[1].c_str();
400     source = args[2].c_str();
401     target = args[3].c_str();
402 
403     if (!strncmp(source, "mtd@", 4)) {
404         n = mtd_name_to_number(source + 4);
405         if (n < 0) {
406             return -1;
407         }
408 
409         snprintf(tmp, sizeof(tmp), "/dev/block/mtdblock%d", n);
410 
411         if (wait)
412             wait_for_file(tmp, COMMAND_RETRY_TIMEOUT);
413         if (mount(tmp, target, system, flags, options) < 0) {
414             return -1;
415         }
416 
417         goto exit_success;
418     } else if (!strncmp(source, "loop@", 5)) {
419         int mode, loop, fd;
420         struct loop_info info;
421 
422         mode = (flags & MS_RDONLY) ? O_RDONLY : O_RDWR;
423         fd = open(source + 5, mode | O_CLOEXEC);
424         if (fd < 0) {
425             return -1;
426         }
427 
428         for (n = 0; ; n++) {
429             snprintf(tmp, sizeof(tmp), "/dev/block/loop%d", n);
430             loop = open(tmp, mode | O_CLOEXEC);
431             if (loop < 0) {
432                 close(fd);
433                 return -1;
434             }
435 
436             /* if it is a blank loop device */
437             if (ioctl(loop, LOOP_GET_STATUS, &info) < 0 && errno == ENXIO) {
438                 /* if it becomes our loop device */
439                 if (ioctl(loop, LOOP_SET_FD, fd) >= 0) {
440                     close(fd);
441 
442                     if (mount(tmp, target, system, flags, options) < 0) {
443                         ioctl(loop, LOOP_CLR_FD, 0);
444                         close(loop);
445                         return -1;
446                     }
447 
448                     close(loop);
449                     goto exit_success;
450                 }
451             }
452 
453             close(loop);
454         }
455 
456         close(fd);
457         ERROR("out of loopback devices");
458         return -1;
459     } else {
460         if (wait)
461             wait_for_file(source, COMMAND_RETRY_TIMEOUT);
462         if (mount(source, target, system, flags, options) < 0) {
463             return -1;
464         }
465 
466     }
467 
468 exit_success:
469     return 0;
470 
471 }
472 
473 /* Imports .rc files from the specified paths. Default ones are applied if none is given.
474  *
475  * start_index: index of the first path in the args list
476  */
import_late(const std::vector<std::string> & args,size_t start_index)477 static void import_late(const std::vector<std::string>& args, size_t start_index) {
478     Parser& parser = Parser::GetInstance();
479     if (args.size() <= start_index) {
480         // Use the default set if no path is given
481         static const std::vector<std::string> init_directories = {
482             "/system/etc/init",
483             "/vendor/etc/init",
484             "/odm/etc/init"
485         };
486 
487         for (const auto& dir : init_directories) {
488             parser.ParseConfig(dir);
489         }
490     } else {
491         for (size_t i = start_index; i < args.size(); ++i) {
492             parser.ParseConfig(args[i]);
493         }
494     }
495 }
496 
497 /* mount_all <fstab> [ <path> ]*
498  *
499  * This function might request a reboot, in which case it will
500  * not return.
501  */
do_mount_all(const std::vector<std::string> & args)502 static int do_mount_all(const std::vector<std::string>& args) {
503     pid_t pid;
504     int ret = -1;
505     int child_ret = -1;
506     int status;
507     struct fstab *fstab;
508 
509     const char* fstabfile = args[1].c_str();
510     /*
511      * Call fs_mgr_mount_all() to mount all filesystems.  We fork(2) and
512      * do the call in the child to provide protection to the main init
513      * process if anything goes wrong (crash or memory leak), and wait for
514      * the child to finish in the parent.
515      */
516     pid = fork();
517     if (pid > 0) {
518         /* Parent.  Wait for the child to return */
519         int wp_ret = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
520         if (wp_ret < 0) {
521             /* Unexpected error code. We will continue anyway. */
522             NOTICE("waitpid failed rc=%d: %s\n", wp_ret, strerror(errno));
523         }
524 
525         if (WIFEXITED(status)) {
526             ret = WEXITSTATUS(status);
527         } else {
528             ret = -1;
529         }
530     } else if (pid == 0) {
531         /* child, call fs_mgr_mount_all() */
532         klog_set_level(6);  /* So we can see what fs_mgr_mount_all() does */
533         fstab = fs_mgr_read_fstab(fstabfile);
534         child_ret = fs_mgr_mount_all(fstab);
535         fs_mgr_free_fstab(fstab);
536         if (child_ret == -1) {
537             ERROR("fs_mgr_mount_all returned an error\n");
538         }
539         _exit(child_ret);
540     } else {
541         /* fork failed, return an error */
542         return -1;
543     }
544 
545     /* Paths of .rc files are specified at the 2nd argument and beyond */
546     import_late(args, 2);
547 
548     if (ret == FS_MGR_MNTALL_DEV_NEEDS_ENCRYPTION) {
549         ActionManager::GetInstance().QueueEventTrigger("encrypt");
550     } else if (ret == FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED) {
551         property_set("ro.crypto.state", "encrypted");
552         property_set("ro.crypto.type", "block");
553         ActionManager::GetInstance().QueueEventTrigger("defaultcrypto");
554     } else if (ret == FS_MGR_MNTALL_DEV_NOT_ENCRYPTED) {
555         property_set("ro.crypto.state", "unencrypted");
556         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
557     } else if (ret == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
558         property_set("ro.crypto.state", "unsupported");
559         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
560     } else if (ret == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
561         /* Setup a wipe via recovery, and reboot into recovery */
562         ERROR("fs_mgr_mount_all suggested recovery, so wiping data via recovery.\n");
563         ret = wipe_data_via_recovery("wipe_data_via_recovery");
564         /* If reboot worked, there is no return. */
565     } else if (ret == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED) {
566         if (e4crypt_install_keyring()) {
567             return -1;
568         }
569         property_set("ro.crypto.state", "encrypted");
570         property_set("ro.crypto.type", "file");
571 
572         // Although encrypted, we have device key, so we do not need to
573         // do anything different from the nonencrypted case.
574         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
575     } else if (ret > 0) {
576         ERROR("fs_mgr_mount_all returned unexpected error %d\n", ret);
577     }
578     /* else ... < 0: error */
579 
580     return ret;
581 }
582 
do_swapon_all(const std::vector<std::string> & args)583 static int do_swapon_all(const std::vector<std::string>& args) {
584     struct fstab *fstab;
585     int ret;
586 
587     fstab = fs_mgr_read_fstab(args[1].c_str());
588     ret = fs_mgr_swapon_all(fstab);
589     fs_mgr_free_fstab(fstab);
590 
591     return ret;
592 }
593 
do_setprop(const std::vector<std::string> & args)594 static int do_setprop(const std::vector<std::string>& args) {
595     const char* name = args[1].c_str();
596     const char* value = args[2].c_str();
597     property_set(name, value);
598     return 0;
599 }
600 
do_setrlimit(const std::vector<std::string> & args)601 static int do_setrlimit(const std::vector<std::string>& args) {
602     struct rlimit limit;
603     int resource;
604     resource = std::stoi(args[1]);
605     limit.rlim_cur = std::stoi(args[2]);
606     limit.rlim_max = std::stoi(args[3]);
607     return setrlimit(resource, &limit);
608 }
609 
do_start(const std::vector<std::string> & args)610 static int do_start(const std::vector<std::string>& args) {
611     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
612     if (!svc) {
613         ERROR("do_start: Service %s not found\n", args[1].c_str());
614         return -1;
615     }
616     if (!svc->Start())
617         return -1;
618     return 0;
619 }
620 
do_stop(const std::vector<std::string> & args)621 static int do_stop(const std::vector<std::string>& args) {
622     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
623     if (!svc) {
624         ERROR("do_stop: Service %s not found\n", args[1].c_str());
625         return -1;
626     }
627     svc->Stop();
628     return 0;
629 }
630 
do_restart(const std::vector<std::string> & args)631 static int do_restart(const std::vector<std::string>& args) {
632     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
633     if (!svc) {
634         ERROR("do_restart: Service %s not found\n", args[1].c_str());
635         return -1;
636     }
637     svc->Restart();
638     return 0;
639 }
640 
do_powerctl(const std::vector<std::string> & args)641 static int do_powerctl(const std::vector<std::string>& args) {
642     const char* command = args[1].c_str();
643     int len = 0;
644     unsigned int cmd = 0;
645     const char *reboot_target = "";
646     void (*callback_on_ro_remount)(const struct mntent*) = NULL;
647 
648     if (strncmp(command, "shutdown", 8) == 0) {
649         cmd = ANDROID_RB_POWEROFF;
650         len = 8;
651     } else if (strncmp(command, "reboot", 6) == 0) {
652         cmd = ANDROID_RB_RESTART2;
653         len = 6;
654     } else {
655         ERROR("powerctl: unrecognized command '%s'\n", command);
656         return -EINVAL;
657     }
658 
659     if (command[len] == ',') {
660         if (cmd == ANDROID_RB_POWEROFF &&
661             !strcmp(&command[len + 1], "userrequested")) {
662             // The shutdown reason is PowerManager.SHUTDOWN_USER_REQUESTED.
663             // Run fsck once the file system is remounted in read-only mode.
664             callback_on_ro_remount = unmount_and_fsck;
665         } else if (cmd == ANDROID_RB_RESTART2) {
666             reboot_target = &command[len + 1];
667         }
668     } else if (command[len] != '\0') {
669         ERROR("powerctl: unrecognized reboot target '%s'\n", &command[len]);
670         return -EINVAL;
671     }
672 
673     std::string timeout = property_get("ro.build.shutdown_timeout");
674     unsigned int delay = 0;
675 
676     if (android::base::ParseUint(timeout.c_str(), &delay) && delay > 0) {
677         Timer t;
678         // Ask all services to terminate.
679         ServiceManager::GetInstance().ForEachService(
680             [] (Service* s) { s->Terminate(); });
681 
682         while (t.duration() < delay) {
683             ServiceManager::GetInstance().ReapAnyOutstandingChildren();
684 
685             int service_count = 0;
686             ServiceManager::GetInstance().ForEachService(
687                 [&service_count] (Service* s) {
688                     // Count the number of services running.
689                     // Exclude the console as it will ignore the SIGTERM signal
690                     // and not exit.
691                     // Note: SVC_CONSOLE actually means "requires console" but
692                     // it is only used by the shell.
693                     if (s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
694                         service_count++;
695                     }
696                 });
697 
698             if (service_count == 0) {
699                 // All terminable services terminated. We can exit early.
700                 break;
701             }
702 
703             // Wait a bit before recounting the number or running services.
704             usleep(kTerminateServiceDelayMicroSeconds);
705         }
706         NOTICE("Terminating running services took %.02f seconds", t.duration());
707     }
708 
709     return android_reboot_with_callback(cmd, 0, reboot_target,
710                                         callback_on_ro_remount);
711 }
712 
do_trigger(const std::vector<std::string> & args)713 static int do_trigger(const std::vector<std::string>& args) {
714     ActionManager::GetInstance().QueueEventTrigger(args[1]);
715     return 0;
716 }
717 
do_symlink(const std::vector<std::string> & args)718 static int do_symlink(const std::vector<std::string>& args) {
719     return symlink(args[1].c_str(), args[2].c_str());
720 }
721 
do_rm(const std::vector<std::string> & args)722 static int do_rm(const std::vector<std::string>& args) {
723     return unlink(args[1].c_str());
724 }
725 
do_rmdir(const std::vector<std::string> & args)726 static int do_rmdir(const std::vector<std::string>& args) {
727     return rmdir(args[1].c_str());
728 }
729 
do_sysclktz(const std::vector<std::string> & args)730 static int do_sysclktz(const std::vector<std::string>& args) {
731     struct timezone tz;
732 
733     memset(&tz, 0, sizeof(tz));
734     tz.tz_minuteswest = std::stoi(args[1]);
735     if (settimeofday(NULL, &tz))
736         return -1;
737     return 0;
738 }
739 
do_verity_load_state(const std::vector<std::string> & args)740 static int do_verity_load_state(const std::vector<std::string>& args) {
741     int mode = -1;
742     int rc = fs_mgr_load_verity_state(&mode);
743     if (rc == 0 && mode != VERITY_MODE_DEFAULT) {
744         ActionManager::GetInstance().QueueEventTrigger("verity-logging");
745     }
746     return rc;
747 }
748 
verity_update_property(fstab_rec * fstab,const char * mount_point,int mode,int status)749 static void verity_update_property(fstab_rec *fstab, const char *mount_point,
750                                    int mode, int status) {
751     property_set(android::base::StringPrintf("partition.%s.verified", mount_point).c_str(),
752                  android::base::StringPrintf("%d", mode).c_str());
753 }
754 
do_verity_update_state(const std::vector<std::string> & args)755 static int do_verity_update_state(const std::vector<std::string>& args) {
756     return fs_mgr_update_verity_state(verity_update_property);
757 }
758 
do_write(const std::vector<std::string> & args)759 static int do_write(const std::vector<std::string>& args) {
760     const char* path = args[1].c_str();
761     const char* value = args[2].c_str();
762     return write_file(path, value);
763 }
764 
do_copy(const std::vector<std::string> & args)765 static int do_copy(const std::vector<std::string>& args) {
766     char *buffer = NULL;
767     int rc = 0;
768     int fd1 = -1, fd2 = -1;
769     struct stat info;
770     int brtw, brtr;
771     char *p;
772 
773     if (stat(args[1].c_str(), &info) < 0)
774         return -1;
775 
776     if ((fd1 = open(args[1].c_str(), O_RDONLY|O_CLOEXEC)) < 0)
777         goto out_err;
778 
779     if ((fd2 = open(args[2].c_str(), O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0660)) < 0)
780         goto out_err;
781 
782     if (!(buffer = (char*) malloc(info.st_size)))
783         goto out_err;
784 
785     p = buffer;
786     brtr = info.st_size;
787     while(brtr) {
788         rc = read(fd1, p, brtr);
789         if (rc < 0)
790             goto out_err;
791         if (rc == 0)
792             break;
793         p += rc;
794         brtr -= rc;
795     }
796 
797     p = buffer;
798     brtw = info.st_size;
799     while(brtw) {
800         rc = write(fd2, p, brtw);
801         if (rc < 0)
802             goto out_err;
803         if (rc == 0)
804             break;
805         p += rc;
806         brtw -= rc;
807     }
808 
809     rc = 0;
810     goto out;
811 out_err:
812     rc = -1;
813 out:
814     if (buffer)
815         free(buffer);
816     if (fd1 >= 0)
817         close(fd1);
818     if (fd2 >= 0)
819         close(fd2);
820     return rc;
821 }
822 
do_chown(const std::vector<std::string> & args)823 static int do_chown(const std::vector<std::string>& args) {
824     /* GID is optional. */
825     if (args.size() == 3) {
826         if (lchown(args[2].c_str(), decode_uid(args[1].c_str()), -1) == -1)
827             return -errno;
828     } else if (args.size() == 4) {
829         if (lchown(args[3].c_str(), decode_uid(args[1].c_str()),
830                    decode_uid(args[2].c_str())) == -1)
831             return -errno;
832     } else {
833         return -1;
834     }
835     return 0;
836 }
837 
get_mode(const char * s)838 static mode_t get_mode(const char *s) {
839     mode_t mode = 0;
840     while (*s) {
841         if (*s >= '0' && *s <= '7') {
842             mode = (mode<<3) | (*s-'0');
843         } else {
844             return -1;
845         }
846         s++;
847     }
848     return mode;
849 }
850 
do_chmod(const std::vector<std::string> & args)851 static int do_chmod(const std::vector<std::string>& args) {
852     mode_t mode = get_mode(args[1].c_str());
853     if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) {
854         return -errno;
855     }
856     return 0;
857 }
858 
do_restorecon(const std::vector<std::string> & args)859 static int do_restorecon(const std::vector<std::string>& args) {
860     int ret = 0;
861 
862     for (auto it = std::next(args.begin()); it != args.end(); ++it) {
863         if (restorecon(it->c_str()) < 0)
864             ret = -errno;
865     }
866     return ret;
867 }
868 
do_restorecon_recursive(const std::vector<std::string> & args)869 static int do_restorecon_recursive(const std::vector<std::string>& args) {
870     int ret = 0;
871 
872     for (auto it = std::next(args.begin()); it != args.end(); ++it) {
873         if (restorecon_recursive(it->c_str()) < 0)
874             ret = -errno;
875     }
876     return ret;
877 }
878 
do_loglevel(const std::vector<std::string> & args)879 static int do_loglevel(const std::vector<std::string>& args) {
880     int log_level = std::stoi(args[1]);
881     if (log_level < KLOG_ERROR_LEVEL || log_level > KLOG_DEBUG_LEVEL) {
882         ERROR("loglevel: invalid log level'%d'\n", log_level);
883         return -EINVAL;
884     }
885     klog_set_level(log_level);
886     return 0;
887 }
888 
do_load_persist_props(const std::vector<std::string> & args)889 static int do_load_persist_props(const std::vector<std::string>& args) {
890     load_persist_props();
891     return 0;
892 }
893 
do_load_system_props(const std::vector<std::string> & args)894 static int do_load_system_props(const std::vector<std::string>& args) {
895     load_system_props();
896     return 0;
897 }
898 
do_wait(const std::vector<std::string> & args)899 static int do_wait(const std::vector<std::string>& args) {
900     if (args.size() == 2) {
901         return wait_for_file(args[1].c_str(), COMMAND_RETRY_TIMEOUT);
902     } else if (args.size() == 3) {
903         return wait_for_file(args[1].c_str(), std::stoi(args[2]));
904     } else
905         return -1;
906 }
907 
908 /*
909  * Callback to make a directory from the ext4 code
910  */
do_installkeys_ensure_dir_exists(const char * dir)911 static int do_installkeys_ensure_dir_exists(const char* dir) {
912     if (make_dir(dir, 0700) && errno != EEXIST) {
913         return -1;
914     }
915 
916     return 0;
917 }
918 
is_file_crypto()919 static bool is_file_crypto() {
920     std::string value = property_get("ro.crypto.type");
921     return value == "file";
922 }
923 
do_installkey(const std::vector<std::string> & args)924 static int do_installkey(const std::vector<std::string>& args) {
925     if (!is_file_crypto()) {
926         return 0;
927     }
928     return e4crypt_create_device_key(args[1].c_str(),
929                                      do_installkeys_ensure_dir_exists);
930 }
931 
do_init_user0(const std::vector<std::string> & args)932 static int do_init_user0(const std::vector<std::string>& args) {
933     return e4crypt_do_init_user0();
934 }
935 
map() const936 BuiltinFunctionMap::Map& BuiltinFunctionMap::map() const {
937     constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
938     static const Map builtin_functions = {
939         {"bootchart_init",          {0,     0,    do_bootchart_init}},
940         {"chmod",                   {2,     2,    do_chmod}},
941         {"chown",                   {2,     3,    do_chown}},
942         {"class_reset",             {1,     1,    do_class_reset}},
943         {"class_start",             {1,     1,    do_class_start}},
944         {"class_stop",              {1,     1,    do_class_stop}},
945         {"copy",                    {2,     2,    do_copy}},
946         {"domainname",              {1,     1,    do_domainname}},
947         {"enable",                  {1,     1,    do_enable}},
948         {"exec",                    {1,     kMax, do_exec}},
949         {"export",                  {2,     2,    do_export}},
950         {"hostname",                {1,     1,    do_hostname}},
951         {"ifup",                    {1,     1,    do_ifup}},
952         {"init_user0",              {0,     0,    do_init_user0}},
953         {"insmod",                  {1,     kMax, do_insmod}},
954         {"installkey",              {1,     1,    do_installkey}},
955         {"load_persist_props",      {0,     0,    do_load_persist_props}},
956         {"load_system_props",       {0,     0,    do_load_system_props}},
957         {"loglevel",                {1,     1,    do_loglevel}},
958         {"mkdir",                   {1,     4,    do_mkdir}},
959         {"mount_all",               {1,     kMax, do_mount_all}},
960         {"mount",                   {3,     kMax, do_mount}},
961         {"powerctl",                {1,     1,    do_powerctl}},
962         {"restart",                 {1,     1,    do_restart}},
963         {"restorecon",              {1,     kMax, do_restorecon}},
964         {"restorecon_recursive",    {1,     kMax, do_restorecon_recursive}},
965         {"rm",                      {1,     1,    do_rm}},
966         {"rmdir",                   {1,     1,    do_rmdir}},
967         {"setprop",                 {2,     2,    do_setprop}},
968         {"setrlimit",               {3,     3,    do_setrlimit}},
969         {"start",                   {1,     1,    do_start}},
970         {"stop",                    {1,     1,    do_stop}},
971         {"swapon_all",              {1,     1,    do_swapon_all}},
972         {"symlink",                 {2,     2,    do_symlink}},
973         {"sysclktz",                {1,     1,    do_sysclktz}},
974         {"trigger",                 {1,     1,    do_trigger}},
975         {"verity_load_state",       {0,     0,    do_verity_load_state}},
976         {"verity_update_state",     {0,     0,    do_verity_update_state}},
977         {"wait",                    {1,     2,    do_wait}},
978         {"write",                   {2,     2,    do_write}},
979     };
980     return builtin_functions;
981 }
982