• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <linux/loop.h>
23 #include <linux/module.h>
24 #include <mntent.h>
25 #include <net/if.h>
26 #include <sched.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/mount.h>
32 #include <sys/resource.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/syscall.h>
36 #include <sys/system_properties.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <unistd.h>
41 
42 #include <android-base/chrono_utils.h>
43 #include <android-base/file.h>
44 #include <android-base/logging.h>
45 #include <android-base/parseint.h>
46 #include <android-base/properties.h>
47 #include <android-base/strings.h>
48 #include <bootloader_message/bootloader_message.h>
49 #include <cutils/android_reboot.h>
50 #include <ext4_utils/ext4_crypt.h>
51 #include <ext4_utils/ext4_crypt_init_extensions.h>
52 #include <fs_mgr.h>
53 #include <selinux/android.h>
54 #include <selinux/label.h>
55 #include <selinux/selinux.h>
56 
57 #include "action.h"
58 #include "bootchart.h"
59 #include "init.h"
60 #include "init_parser.h"
61 #include "property_service.h"
62 #include "reboot.h"
63 #include "service.h"
64 #include "signal_handler.h"
65 #include "util.h"
66 
67 using namespace std::literals::string_literals;
68 
69 #define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
70 
71 namespace android {
72 namespace init {
73 
74 static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
75 
insmod(const char * filename,const char * options,int flags)76 static int insmod(const char *filename, const char *options, int flags) {
77     int fd = open(filename, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
78     if (fd == -1) {
79         PLOG(ERROR) << "insmod: open(\"" << filename << "\") failed";
80         return -1;
81     }
82     int rc = syscall(__NR_finit_module, fd, options, flags);
83     if (rc == -1) {
84         PLOG(ERROR) << "finit_module for \"" << filename << "\" failed";
85     }
86     close(fd);
87     return rc;
88 }
89 
__ifupdown(const char * interface,int up)90 static int __ifupdown(const char *interface, int up) {
91     struct ifreq ifr;
92     int s, ret;
93 
94     strlcpy(ifr.ifr_name, interface, IFNAMSIZ);
95 
96     s = socket(AF_INET, SOCK_DGRAM, 0);
97     if (s < 0)
98         return -1;
99 
100     ret = ioctl(s, SIOCGIFFLAGS, &ifr);
101     if (ret < 0) {
102         goto done;
103     }
104 
105     if (up)
106         ifr.ifr_flags |= IFF_UP;
107     else
108         ifr.ifr_flags &= ~IFF_UP;
109 
110     ret = ioctl(s, SIOCSIFFLAGS, &ifr);
111 
112 done:
113     close(s);
114     return ret;
115 }
116 
reboot_into_recovery(const std::vector<std::string> & options)117 static int reboot_into_recovery(const std::vector<std::string>& options) {
118     std::string err;
119     if (!write_bootloader_message(options, &err)) {
120         LOG(ERROR) << "failed to set bootloader message: " << err;
121         return -1;
122     }
123     property_set("sys.powerctl", "reboot,recovery");
124     return 0;
125 }
126 
do_class_start(const std::vector<std::string> & args)127 static int do_class_start(const std::vector<std::string>& args) {
128         /* Starting a class does not start services
129          * which are explicitly disabled.  They must
130          * be started individually.
131          */
132     ServiceManager::GetInstance().
133         ForEachServiceInClass(args[1], [] (Service* s) { s->StartIfNotDisabled(); });
134     return 0;
135 }
136 
do_class_stop(const std::vector<std::string> & args)137 static int do_class_stop(const std::vector<std::string>& args) {
138     ServiceManager::GetInstance().
139         ForEachServiceInClass(args[1], [] (Service* s) { s->Stop(); });
140     return 0;
141 }
142 
do_class_reset(const std::vector<std::string> & args)143 static int do_class_reset(const std::vector<std::string>& args) {
144     ServiceManager::GetInstance().
145         ForEachServiceInClass(args[1], [] (Service* s) { s->Reset(); });
146     return 0;
147 }
148 
do_class_restart(const std::vector<std::string> & args)149 static int do_class_restart(const std::vector<std::string>& args) {
150     ServiceManager::GetInstance().
151         ForEachServiceInClass(args[1], [] (Service* s) { s->Restart(); });
152     return 0;
153 }
154 
do_domainname(const std::vector<std::string> & args)155 static int do_domainname(const std::vector<std::string>& args) {
156     std::string err;
157     if (!WriteFile("/proc/sys/kernel/domainname", args[1], &err)) {
158         LOG(ERROR) << err;
159         return -1;
160     }
161     return 0;
162 }
163 
do_enable(const std::vector<std::string> & args)164 static int do_enable(const std::vector<std::string>& args) {
165     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
166     if (!svc) {
167         return -1;
168     }
169     return svc->Enable();
170 }
171 
do_exec(const std::vector<std::string> & args)172 static int do_exec(const std::vector<std::string>& args) {
173     return ServiceManager::GetInstance().Exec(args) ? 0 : -1;
174 }
175 
do_exec_start(const std::vector<std::string> & args)176 static int do_exec_start(const std::vector<std::string>& args) {
177     return ServiceManager::GetInstance().ExecStart(args[1]) ? 0 : -1;
178 }
179 
do_export(const std::vector<std::string> & args)180 static int do_export(const std::vector<std::string>& args) {
181     return add_environment(args[1].c_str(), args[2].c_str());
182 }
183 
do_hostname(const std::vector<std::string> & args)184 static int do_hostname(const std::vector<std::string>& args) {
185     std::string err;
186     if (!WriteFile("/proc/sys/kernel/hostname", args[1], &err)) {
187         LOG(ERROR) << err;
188         return -1;
189     }
190     return 0;
191 }
192 
do_ifup(const std::vector<std::string> & args)193 static int do_ifup(const std::vector<std::string>& args) {
194     return __ifupdown(args[1].c_str(), 1);
195 }
196 
do_insmod(const std::vector<std::string> & args)197 static int do_insmod(const std::vector<std::string>& args) {
198     int flags = 0;
199     auto it = args.begin() + 1;
200 
201     if (!(*it).compare("-f")) {
202         flags = MODULE_INIT_IGNORE_VERMAGIC | MODULE_INIT_IGNORE_MODVERSIONS;
203         it++;
204     }
205 
206     std::string filename = *it++;
207     std::string options = android::base::Join(std::vector<std::string>(it, args.end()), ' ');
208     return insmod(filename.c_str(), options.c_str(), flags);
209 }
210 
do_mkdir(const std::vector<std::string> & args)211 static int do_mkdir(const std::vector<std::string>& args) {
212     mode_t mode = 0755;
213     int ret;
214 
215     /* mkdir <path> [mode] [owner] [group] */
216 
217     if (args.size() >= 3) {
218         mode = std::strtoul(args[2].c_str(), 0, 8);
219     }
220 
221     ret = make_dir(args[1].c_str(), mode, sehandle);
222     /* chmod in case the directory already exists */
223     if (ret == -1 && errno == EEXIST) {
224         ret = fchmodat(AT_FDCWD, args[1].c_str(), mode, AT_SYMLINK_NOFOLLOW);
225     }
226     if (ret == -1) {
227         return -errno;
228     }
229 
230     if (args.size() >= 4) {
231         uid_t uid;
232         std::string decode_uid_err;
233         if (!DecodeUid(args[3], &uid, &decode_uid_err)) {
234             LOG(ERROR) << "Unable to find UID for '" << args[3] << "': " << decode_uid_err;
235             return -1;
236         }
237         gid_t gid = -1;
238 
239         if (args.size() == 5) {
240             if (!DecodeUid(args[4], &gid, &decode_uid_err)) {
241                 LOG(ERROR) << "Unable to find GID for '" << args[3] << "': " << decode_uid_err;
242                 return -1;
243             }
244         }
245 
246         if (lchown(args[1].c_str(), uid, gid) == -1) {
247             return -errno;
248         }
249 
250         /* chown may have cleared S_ISUID and S_ISGID, chmod again */
251         if (mode & (S_ISUID | S_ISGID)) {
252             ret = fchmodat(AT_FDCWD, args[1].c_str(), mode, AT_SYMLINK_NOFOLLOW);
253             if (ret == -1) {
254                 return -errno;
255             }
256         }
257     }
258 
259     if (e4crypt_is_native()) {
260         if (e4crypt_set_directory_policy(args[1].c_str())) {
261             const std::vector<std::string> options = {
262                 "--prompt_and_wipe_data",
263                 "--reason=set_policy_failed:"s + args[1]};
264             reboot_into_recovery(options);
265             return 0;
266         }
267     }
268     return 0;
269 }
270 
271 /* umount <path> */
do_umount(const std::vector<std::string> & args)272 static int do_umount(const std::vector<std::string>& args) {
273   return umount(args[1].c_str());
274 }
275 
276 static struct {
277     const char *name;
278     unsigned flag;
279 } mount_flags[] = {
280     { "noatime",    MS_NOATIME },
281     { "noexec",     MS_NOEXEC },
282     { "nosuid",     MS_NOSUID },
283     { "nodev",      MS_NODEV },
284     { "nodiratime", MS_NODIRATIME },
285     { "ro",         MS_RDONLY },
286     { "rw",         0 },
287     { "remount",    MS_REMOUNT },
288     { "bind",       MS_BIND },
289     { "rec",        MS_REC },
290     { "unbindable", MS_UNBINDABLE },
291     { "private",    MS_PRIVATE },
292     { "slave",      MS_SLAVE },
293     { "shared",     MS_SHARED },
294     { "defaults",   0 },
295     { 0,            0 },
296 };
297 
298 #define DATA_MNT_POINT "/data"
299 
300 /* mount <type> <device> <path> <flags ...> <options> */
do_mount(const std::vector<std::string> & args)301 static int do_mount(const std::vector<std::string>& args) {
302     char tmp[64];
303     const char *source, *target, *system;
304     const char *options = NULL;
305     unsigned flags = 0;
306     std::size_t na = 0;
307     int n, i;
308     int wait = 0;
309 
310     for (na = 4; na < args.size(); na++) {
311         for (i = 0; mount_flags[i].name; i++) {
312             if (!args[na].compare(mount_flags[i].name)) {
313                 flags |= mount_flags[i].flag;
314                 break;
315             }
316         }
317 
318         if (!mount_flags[i].name) {
319             if (!args[na].compare("wait"))
320                 wait = 1;
321             /* if our last argument isn't a flag, wolf it up as an option string */
322             else if (na + 1 == args.size())
323                 options = args[na].c_str();
324         }
325     }
326 
327     system = args[1].c_str();
328     source = args[2].c_str();
329     target = args[3].c_str();
330 
331     if (!strncmp(source, "loop@", 5)) {
332         int mode, loop, fd;
333         struct loop_info info;
334 
335         mode = (flags & MS_RDONLY) ? O_RDONLY : O_RDWR;
336         fd = open(source + 5, mode | O_CLOEXEC);
337         if (fd < 0) {
338             return -1;
339         }
340 
341         for (n = 0; ; n++) {
342             snprintf(tmp, sizeof(tmp), "/dev/block/loop%d", n);
343             loop = open(tmp, mode | O_CLOEXEC);
344             if (loop < 0) {
345                 close(fd);
346                 return -1;
347             }
348 
349             /* if it is a blank loop device */
350             if (ioctl(loop, LOOP_GET_STATUS, &info) < 0 && errno == ENXIO) {
351                 /* if it becomes our loop device */
352                 if (ioctl(loop, LOOP_SET_FD, fd) >= 0) {
353                     close(fd);
354 
355                     if (mount(tmp, target, system, flags, options) < 0) {
356                         ioctl(loop, LOOP_CLR_FD, 0);
357                         close(loop);
358                         return -1;
359                     }
360 
361                     close(loop);
362                     goto exit_success;
363                 }
364             }
365 
366             close(loop);
367         }
368 
369         close(fd);
370         LOG(ERROR) << "out of loopback devices";
371         return -1;
372     } else {
373         if (wait)
374             wait_for_file(source, kCommandRetryTimeout);
375         if (mount(source, target, system, flags, options) < 0) {
376             return -1;
377         }
378 
379     }
380 
381 exit_success:
382     return 0;
383 
384 }
385 
386 /* Imports .rc files from the specified paths. Default ones are applied if none is given.
387  *
388  * start_index: index of the first path in the args list
389  */
import_late(const std::vector<std::string> & args,size_t start_index,size_t end_index)390 static void import_late(const std::vector<std::string>& args, size_t start_index, size_t end_index) {
391     Parser& parser = Parser::GetInstance();
392     if (end_index <= start_index) {
393         // Fallbacks for partitions on which early mount isn't enabled.
394         if (!parser.is_system_etc_init_loaded()) {
395             parser.ParseConfig("/system/etc/init");
396             parser.set_is_system_etc_init_loaded(true);
397         }
398         if (!parser.is_vendor_etc_init_loaded()) {
399             parser.ParseConfig("/vendor/etc/init");
400             parser.set_is_vendor_etc_init_loaded(true);
401         }
402         if (!parser.is_odm_etc_init_loaded()) {
403             parser.ParseConfig("/odm/etc/init");
404             parser.set_is_odm_etc_init_loaded(true);
405         }
406     } else {
407         for (size_t i = start_index; i < end_index; ++i) {
408             parser.ParseConfig(args[i]);
409         }
410     }
411 
412     // Turning this on and letting the INFO logging be discarded adds 0.2s to
413     // Nexus 9 boot time, so it's disabled by default.
414     if (false) DumpState();
415 }
416 
417 /* mount_fstab
418  *
419  *  Call fs_mgr_mount_all() to mount the given fstab
420  */
mount_fstab(const char * fstabfile,int mount_mode)421 static int mount_fstab(const char* fstabfile, int mount_mode) {
422     int ret = -1;
423 
424     /*
425      * Call fs_mgr_mount_all() to mount all filesystems.  We fork(2) and
426      * do the call in the child to provide protection to the main init
427      * process if anything goes wrong (crash or memory leak), and wait for
428      * the child to finish in the parent.
429      */
430     pid_t pid = fork();
431     if (pid > 0) {
432         /* Parent.  Wait for the child to return */
433         int status;
434         int wp_ret = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
435         if (wp_ret == -1) {
436             // Unexpected error code. We will continue anyway.
437             PLOG(WARNING) << "waitpid failed";
438         }
439 
440         if (WIFEXITED(status)) {
441             ret = WEXITSTATUS(status);
442         } else {
443             ret = -1;
444         }
445     } else if (pid == 0) {
446         /* child, call fs_mgr_mount_all() */
447 
448         // So we can always see what fs_mgr_mount_all() does.
449         // Only needed if someone explicitly changes the default log level in their init.rc.
450         android::base::ScopedLogSeverity info(android::base::INFO);
451 
452         struct fstab* fstab = fs_mgr_read_fstab(fstabfile);
453         int child_ret = fs_mgr_mount_all(fstab, mount_mode);
454         fs_mgr_free_fstab(fstab);
455         if (child_ret == -1) {
456             PLOG(ERROR) << "fs_mgr_mount_all returned an error";
457         }
458         _exit(child_ret);
459     } else {
460         /* fork failed, return an error */
461         return -1;
462     }
463     return ret;
464 }
465 
466 /* Queue event based on fs_mgr return code.
467  *
468  * code: return code of fs_mgr_mount_all
469  *
470  * This function might request a reboot, in which case it will
471  * not return.
472  *
473  * return code is processed based on input code
474  */
queue_fs_event(int code)475 static int queue_fs_event(int code) {
476     int ret = code;
477     if (code == FS_MGR_MNTALL_DEV_NEEDS_ENCRYPTION) {
478         ActionManager::GetInstance().QueueEventTrigger("encrypt");
479     } else if (code == FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED) {
480         property_set("ro.crypto.state", "encrypted");
481         property_set("ro.crypto.type", "block");
482         ActionManager::GetInstance().QueueEventTrigger("defaultcrypto");
483     } else if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTED) {
484         property_set("ro.crypto.state", "unencrypted");
485         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
486     } else if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
487         property_set("ro.crypto.state", "unsupported");
488         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
489     } else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
490         /* Setup a wipe via recovery, and reboot into recovery */
491         PLOG(ERROR) << "fs_mgr_mount_all suggested recovery, so wiping data via recovery.";
492         const std::vector<std::string> options = {"--wipe_data", "--reason=fs_mgr_mount_all" };
493         reboot_into_recovery(options);
494         return 0;
495         /* If reboot worked, there is no return. */
496     } else if (code == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED) {
497         if (e4crypt_install_keyring()) {
498             return -1;
499         }
500         property_set("ro.crypto.state", "encrypted");
501         property_set("ro.crypto.type", "file");
502 
503         // Although encrypted, we have device key, so we do not need to
504         // do anything different from the nonencrypted case.
505         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
506     } else if (code == FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED) {
507         if (e4crypt_install_keyring()) {
508             return -1;
509         }
510         property_set("ro.crypto.state", "encrypted");
511         property_set("ro.crypto.type", "file");
512 
513         // defaultcrypto detects file/block encryption. init flow is same for each.
514         ActionManager::GetInstance().QueueEventTrigger("defaultcrypto");
515     } else if (code == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
516         if (e4crypt_install_keyring()) {
517             return -1;
518         }
519         property_set("ro.crypto.type", "file");
520 
521         // encrypt detects file/block encryption. init flow is same for each.
522         ActionManager::GetInstance().QueueEventTrigger("encrypt");
523     } else if (code > 0) {
524         PLOG(ERROR) << "fs_mgr_mount_all returned unexpected error " << code;
525     }
526     /* else ... < 0: error */
527 
528     return ret;
529 }
530 
531 /* mount_all <fstab> [ <path> ]* [--<options>]*
532  *
533  * This function might request a reboot, in which case it will
534  * not return.
535  */
do_mount_all(const std::vector<std::string> & args)536 static int do_mount_all(const std::vector<std::string>& args) {
537     std::size_t na = 0;
538     bool import_rc = true;
539     bool queue_event = true;
540     int mount_mode = MOUNT_MODE_DEFAULT;
541     const char* fstabfile = args[1].c_str();
542     std::size_t path_arg_end = args.size();
543     const char* prop_post_fix = "default";
544 
545     for (na = args.size() - 1; na > 1; --na) {
546         if (args[na] == "--early") {
547             path_arg_end = na;
548             queue_event = false;
549             mount_mode = MOUNT_MODE_EARLY;
550             prop_post_fix = "early";
551         } else if (args[na] == "--late") {
552             path_arg_end = na;
553             import_rc = false;
554             mount_mode = MOUNT_MODE_LATE;
555             prop_post_fix = "late";
556         }
557     }
558 
559     std::string prop_name = "ro.boottime.init.mount_all."s + prop_post_fix;
560     android::base::Timer t;
561     int ret =  mount_fstab(fstabfile, mount_mode);
562     property_set(prop_name, std::to_string(t.duration().count()));
563 
564     if (import_rc) {
565         /* Paths of .rc files are specified at the 2nd argument and beyond */
566         import_late(args, 2, path_arg_end);
567     }
568 
569     if (queue_event) {
570         /* queue_fs_event will queue event based on mount_fstab return code
571          * and return processed return code*/
572         ret = queue_fs_event(ret);
573     }
574 
575     return ret;
576 }
577 
do_swapon_all(const std::vector<std::string> & args)578 static int do_swapon_all(const std::vector<std::string>& args) {
579     struct fstab *fstab;
580     int ret;
581 
582     fstab = fs_mgr_read_fstab(args[1].c_str());
583     ret = fs_mgr_swapon_all(fstab);
584     fs_mgr_free_fstab(fstab);
585 
586     return ret;
587 }
588 
do_setprop(const std::vector<std::string> & args)589 static int do_setprop(const std::vector<std::string>& args) {
590     property_set(args[1], args[2]);
591     return 0;
592 }
593 
do_setrlimit(const std::vector<std::string> & args)594 static int do_setrlimit(const std::vector<std::string>& args) {
595     struct rlimit limit;
596     int resource;
597     if (android::base::ParseInt(args[1], &resource) &&
598         android::base::ParseUint(args[2], &limit.rlim_cur) &&
599         android::base::ParseUint(args[3], &limit.rlim_max)) {
600         return setrlimit(resource, &limit);
601     }
602     LOG(WARNING) << "ignoring setrlimit " << args[1] << " " << args[2] << " " << args[3];
603     return -1;
604 }
605 
do_start(const std::vector<std::string> & args)606 static int do_start(const std::vector<std::string>& args) {
607     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
608     if (!svc) {
609         LOG(ERROR) << "do_start: Service " << args[1] << " not found";
610         return -1;
611     }
612     if (!svc->Start())
613         return -1;
614     return 0;
615 }
616 
do_stop(const std::vector<std::string> & args)617 static int do_stop(const std::vector<std::string>& args) {
618     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
619     if (!svc) {
620         LOG(ERROR) << "do_stop: Service " << args[1] << " not found";
621         return -1;
622     }
623     svc->Stop();
624     return 0;
625 }
626 
do_restart(const std::vector<std::string> & args)627 static int do_restart(const std::vector<std::string>& args) {
628     Service* svc = ServiceManager::GetInstance().FindServiceByName(args[1]);
629     if (!svc) {
630         LOG(ERROR) << "do_restart: Service " << args[1] << " not found";
631         return -1;
632     }
633     svc->Restart();
634     return 0;
635 }
636 
do_trigger(const std::vector<std::string> & args)637 static int do_trigger(const std::vector<std::string>& args) {
638     ActionManager::GetInstance().QueueEventTrigger(args[1]);
639     return 0;
640 }
641 
do_symlink(const std::vector<std::string> & args)642 static int do_symlink(const std::vector<std::string>& args) {
643     return symlink(args[1].c_str(), args[2].c_str());
644 }
645 
do_rm(const std::vector<std::string> & args)646 static int do_rm(const std::vector<std::string>& args) {
647     return unlink(args[1].c_str());
648 }
649 
do_rmdir(const std::vector<std::string> & args)650 static int do_rmdir(const std::vector<std::string>& args) {
651     return rmdir(args[1].c_str());
652 }
653 
do_sysclktz(const std::vector<std::string> & args)654 static int do_sysclktz(const std::vector<std::string>& args) {
655     struct timezone tz = {};
656     if (android::base::ParseInt(args[1], &tz.tz_minuteswest) && settimeofday(NULL, &tz) != -1) {
657         return 0;
658     }
659     return -1;
660 }
661 
do_verity_load_state(const std::vector<std::string> & args)662 static int do_verity_load_state(const std::vector<std::string>& args) {
663     int mode = -1;
664     bool loaded = fs_mgr_load_verity_state(&mode);
665     if (loaded && mode != VERITY_MODE_DEFAULT) {
666         ActionManager::GetInstance().QueueEventTrigger("verity-logging");
667     }
668     return loaded ? 0 : 1;
669 }
670 
verity_update_property(fstab_rec * fstab,const char * mount_point,int mode,int status)671 static void verity_update_property(fstab_rec *fstab, const char *mount_point,
672                                    int mode, int status) {
673     property_set("partition."s + mount_point + ".verified", std::to_string(mode));
674 }
675 
do_verity_update_state(const std::vector<std::string> & args)676 static int do_verity_update_state(const std::vector<std::string>& args) {
677     return fs_mgr_update_verity_state(verity_update_property) ? 0 : 1;
678 }
679 
do_write(const std::vector<std::string> & args)680 static int do_write(const std::vector<std::string>& args) {
681     std::string err;
682     if (!WriteFile(args[1], args[2], &err)) {
683         LOG(ERROR) << err;
684         return -1;
685     }
686     return 0;
687 }
688 
do_copy(const std::vector<std::string> & args)689 static int do_copy(const std::vector<std::string>& args) {
690     std::string data;
691     std::string err;
692     if (!ReadFile(args[1], &data, &err)) {
693         LOG(ERROR) << err;
694         return -1;
695     }
696     if (!WriteFile(args[2], data, &err)) {
697         LOG(ERROR) << err;
698         return -1;
699     }
700     return 0;
701 }
702 
do_chown(const std::vector<std::string> & args)703 static int do_chown(const std::vector<std::string>& args) {
704     uid_t uid;
705     std::string decode_uid_err;
706     if (!DecodeUid(args[1], &uid, &decode_uid_err)) {
707         LOG(ERROR) << "Unable to find UID for '" << args[1] << "': " << decode_uid_err;
708         return -1;
709     }
710 
711     // GID is optional and pushes the index of path out by one if specified.
712     const std::string& path = (args.size() == 4) ? args[3] : args[2];
713     gid_t gid = -1;
714 
715     if (args.size() == 4) {
716         if (!DecodeUid(args[2], &gid, &decode_uid_err)) {
717             LOG(ERROR) << "Unable to find GID for '" << args[2] << "': " << decode_uid_err;
718             return -1;
719         }
720     }
721 
722     if (lchown(path.c_str(), uid, gid) == -1) return -errno;
723 
724     return 0;
725 }
726 
get_mode(const char * s)727 static mode_t get_mode(const char *s) {
728     mode_t mode = 0;
729     while (*s) {
730         if (*s >= '0' && *s <= '7') {
731             mode = (mode<<3) | (*s-'0');
732         } else {
733             return -1;
734         }
735         s++;
736     }
737     return mode;
738 }
739 
do_chmod(const std::vector<std::string> & args)740 static int do_chmod(const std::vector<std::string>& args) {
741     mode_t mode = get_mode(args[1].c_str());
742     if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) {
743         return -errno;
744     }
745     return 0;
746 }
747 
do_restorecon(const std::vector<std::string> & args)748 static int do_restorecon(const std::vector<std::string>& args) {
749     int ret = 0;
750 
751     struct flag_type {const char* name; int value;};
752     static const flag_type flags[] = {
753         {"--recursive", SELINUX_ANDROID_RESTORECON_RECURSE},
754         {"--skip-ce", SELINUX_ANDROID_RESTORECON_SKIPCE},
755         {"--cross-filesystems", SELINUX_ANDROID_RESTORECON_CROSS_FILESYSTEMS},
756         {0, 0}
757     };
758 
759     int flag = 0;
760 
761     bool in_flags = true;
762     for (size_t i = 1; i < args.size(); ++i) {
763         if (android::base::StartsWith(args[i], "--")) {
764             if (!in_flags) {
765                 LOG(ERROR) << "restorecon - flags must precede paths";
766                 return -1;
767             }
768             bool found = false;
769             for (size_t j = 0; flags[j].name; ++j) {
770                 if (args[i] == flags[j].name) {
771                     flag |= flags[j].value;
772                     found = true;
773                     break;
774                 }
775             }
776             if (!found) {
777                 LOG(ERROR) << "restorecon - bad flag " << args[i];
778                 return -1;
779             }
780         } else {
781             in_flags = false;
782             if (selinux_android_restorecon(args[i].c_str(), flag) < 0) {
783                 ret = -errno;
784             }
785         }
786     }
787     return ret;
788 }
789 
do_restorecon_recursive(const std::vector<std::string> & args)790 static int do_restorecon_recursive(const std::vector<std::string>& args) {
791     std::vector<std::string> non_const_args(args);
792     non_const_args.insert(std::next(non_const_args.begin()), "--recursive");
793     return do_restorecon(non_const_args);
794 }
795 
do_loglevel(const std::vector<std::string> & args)796 static int do_loglevel(const std::vector<std::string>& args) {
797     // TODO: support names instead/as well?
798     int log_level = -1;
799     android::base::ParseInt(args[1], &log_level);
800     android::base::LogSeverity severity;
801     switch (log_level) {
802         case 7: severity = android::base::DEBUG; break;
803         case 6: severity = android::base::INFO; break;
804         case 5:
805         case 4: severity = android::base::WARNING; break;
806         case 3: severity = android::base::ERROR; break;
807         case 2:
808         case 1:
809         case 0: severity = android::base::FATAL; break;
810         default:
811             LOG(ERROR) << "loglevel: invalid log level " << log_level;
812             return -EINVAL;
813     }
814     android::base::SetMinimumLogSeverity(severity);
815     return 0;
816 }
817 
do_load_persist_props(const std::vector<std::string> & args)818 static int do_load_persist_props(const std::vector<std::string>& args) {
819     load_persist_props();
820     return 0;
821 }
822 
do_load_system_props(const std::vector<std::string> & args)823 static int do_load_system_props(const std::vector<std::string>& args) {
824     load_system_props();
825     return 0;
826 }
827 
do_wait(const std::vector<std::string> & args)828 static int do_wait(const std::vector<std::string>& args) {
829     if (args.size() == 2) {
830         return wait_for_file(args[1].c_str(), kCommandRetryTimeout);
831     } else if (args.size() == 3) {
832         int timeout;
833         if (android::base::ParseInt(args[2], &timeout)) {
834             return wait_for_file(args[1].c_str(), std::chrono::seconds(timeout));
835         }
836     }
837     return -1;
838 }
839 
do_wait_for_prop(const std::vector<std::string> & args)840 static int do_wait_for_prop(const std::vector<std::string>& args) {
841     const char* name = args[1].c_str();
842     const char* value = args[2].c_str();
843     size_t value_len = strlen(value);
844 
845     if (!is_legal_property_name(name)) {
846         LOG(ERROR) << "do_wait_for_prop(\"" << name << "\", \"" << value
847                    << "\") failed: bad name";
848         return -1;
849     }
850     if (value_len >= PROP_VALUE_MAX) {
851         LOG(ERROR) << "do_wait_for_prop(\"" << name << "\", \"" << value
852                    << "\") failed: value too long";
853         return -1;
854     }
855     if (!start_waiting_for_property(name, value)) {
856         LOG(ERROR) << "do_wait_for_prop(\"" << name << "\", \"" << value
857                    << "\") failed: init already in waiting";
858         return -1;
859     }
860     return 0;
861 }
862 
863 /*
864  * Callback to make a directory from the ext4 code
865  */
do_installkeys_ensure_dir_exists(const char * dir)866 static int do_installkeys_ensure_dir_exists(const char* dir) {
867     if (make_dir(dir, 0700, sehandle) && errno != EEXIST) {
868         return -1;
869     }
870 
871     return 0;
872 }
873 
is_file_crypto()874 static bool is_file_crypto() {
875     return android::base::GetProperty("ro.crypto.type", "") == "file";
876 }
877 
do_installkey(const std::vector<std::string> & args)878 static int do_installkey(const std::vector<std::string>& args) {
879     if (!is_file_crypto()) {
880         return 0;
881     }
882     auto unencrypted_dir = args[1] + e4crypt_unencrypted_folder;
883     if (do_installkeys_ensure_dir_exists(unencrypted_dir.c_str())) {
884         PLOG(ERROR) << "Failed to create " << unencrypted_dir;
885         return -1;
886     }
887     std::vector<std::string> exec_args = {"exec", "/system/bin/vdc", "--wait", "cryptfs",
888                                           "enablefilecrypto"};
889     return do_exec(exec_args);
890 }
891 
do_init_user0(const std::vector<std::string> & args)892 static int do_init_user0(const std::vector<std::string>& args) {
893     std::vector<std::string> exec_args = {"exec", "/system/bin/vdc", "--wait", "cryptfs",
894                                           "init_user0"};
895     return do_exec(exec_args);
896 }
897 
map() const898 const BuiltinFunctionMap::Map& BuiltinFunctionMap::map() const {
899     constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
900     // clang-format off
901     static const Map builtin_functions = {
902         {"bootchart",               {1,     1,    do_bootchart}},
903         {"chmod",                   {2,     2,    do_chmod}},
904         {"chown",                   {2,     3,    do_chown}},
905         {"class_reset",             {1,     1,    do_class_reset}},
906         {"class_restart",           {1,     1,    do_class_restart}},
907         {"class_start",             {1,     1,    do_class_start}},
908         {"class_stop",              {1,     1,    do_class_stop}},
909         {"copy",                    {2,     2,    do_copy}},
910         {"domainname",              {1,     1,    do_domainname}},
911         {"enable",                  {1,     1,    do_enable}},
912         {"exec",                    {1,     kMax, do_exec}},
913         {"exec_start",              {1,     1,    do_exec_start}},
914         {"export",                  {2,     2,    do_export}},
915         {"hostname",                {1,     1,    do_hostname}},
916         {"ifup",                    {1,     1,    do_ifup}},
917         {"init_user0",              {0,     0,    do_init_user0}},
918         {"insmod",                  {1,     kMax, do_insmod}},
919         {"installkey",              {1,     1,    do_installkey}},
920         {"load_persist_props",      {0,     0,    do_load_persist_props}},
921         {"load_system_props",       {0,     0,    do_load_system_props}},
922         {"loglevel",                {1,     1,    do_loglevel}},
923         {"mkdir",                   {1,     4,    do_mkdir}},
924         {"mount_all",               {1,     kMax, do_mount_all}},
925         {"mount",                   {3,     kMax, do_mount}},
926         {"umount",                  {1,     1,    do_umount}},
927         {"restart",                 {1,     1,    do_restart}},
928         {"restorecon",              {1,     kMax, do_restorecon}},
929         {"restorecon_recursive",    {1,     kMax, do_restorecon_recursive}},
930         {"rm",                      {1,     1,    do_rm}},
931         {"rmdir",                   {1,     1,    do_rmdir}},
932         {"setprop",                 {2,     2,    do_setprop}},
933         {"setrlimit",               {3,     3,    do_setrlimit}},
934         {"start",                   {1,     1,    do_start}},
935         {"stop",                    {1,     1,    do_stop}},
936         {"swapon_all",              {1,     1,    do_swapon_all}},
937         {"symlink",                 {2,     2,    do_symlink}},
938         {"sysclktz",                {1,     1,    do_sysclktz}},
939         {"trigger",                 {1,     1,    do_trigger}},
940         {"verity_load_state",       {0,     0,    do_verity_load_state}},
941         {"verity_update_state",     {0,     0,    do_verity_update_state}},
942         {"wait",                    {1,     2,    do_wait}},
943         {"wait_for_prop",           {2,     2,    do_wait_for_prop}},
944         {"write",                   {2,     2,    do_write}},
945     };
946     // clang-format on
947     return builtin_functions;
948 }
949 
950 }  // namespace init
951 }  // namespace android
952