• 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 <android/api-level.h>
20 #include <dirent.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <fts.h>
24 #include <glob.h>
25 #include <linux/loop.h>
26 #include <linux/module.h>
27 #include <mntent.h>
28 #include <net/if.h>
29 #include <sched.h>
30 #include <signal.h>
31 #include <stdint.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/mount.h>
36 #include <sys/resource.h>
37 #include <sys/socket.h>
38 #include <sys/stat.h>
39 #include <sys/syscall.h>
40 #include <sys/system_properties.h>
41 #include <sys/time.h>
42 #include <sys/types.h>
43 #include <sys/wait.h>
44 #include <unistd.h>
45 
46 #include <map>
47 #include <memory>
48 
49 #include <InitProperties.sysprop.h>
50 #include <android-base/chrono_utils.h>
51 #include <android-base/file.h>
52 #include <android-base/logging.h>
53 #include <android-base/parsedouble.h>
54 #include <android-base/parseint.h>
55 #include <android-base/properties.h>
56 #include <android-base/stringprintf.h>
57 #include <android-base/strings.h>
58 #include <android-base/unique_fd.h>
59 #include <bootloader_message/bootloader_message.h>
60 #include <cutils/android_reboot.h>
61 #include <fs_mgr.h>
62 #include <fscrypt/fscrypt.h>
63 #include <libgsi/libgsi.h>
64 #include <logwrap/logwrap.h>
65 #include <private/android_filesystem_config.h>
66 #include <selinux/android.h>
67 #include <selinux/label.h>
68 #include <selinux/selinux.h>
69 #include <system/thread_defs.h>
70 
71 #include "action_manager.h"
72 #include "bootchart.h"
73 #include "builtin_arguments.h"
74 #include "fscrypt_init_extensions.h"
75 #include "init.h"
76 #include "mount_namespace.h"
77 #include "parser.h"
78 #include "property_service.h"
79 #include "reboot.h"
80 #include "rlimit_parser.h"
81 #include "selabel.h"
82 #include "selinux.h"
83 #include "service.h"
84 #include "service_list.h"
85 #include "subcontext.h"
86 #include "util.h"
87 
88 using namespace std::literals::string_literals;
89 
90 using android::base::Basename;
91 using android::base::ResultError;
92 using android::base::SetProperty;
93 using android::base::Split;
94 using android::base::StartsWith;
95 using android::base::StringPrintf;
96 using android::base::unique_fd;
97 using android::fs_mgr::Fstab;
98 using android::fs_mgr::ReadFstabFromFile;
99 
100 #define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
101 
102 namespace android {
103 namespace init {
104 
105 // There are many legacy paths in rootdir/init.rc that will virtually never exist on a new
106 // device, such as '/sys/class/leds/jogball-backlight/brightness'.  As of this writing, there
107 // are 81 such failures on cuttlefish.  Instead of spamming the log reporting them, we do not
108 // report such failures unless we're running at the DEBUG log level.
109 class ErrorIgnoreEnoent {
110   public:
ErrorIgnoreEnoent()111     ErrorIgnoreEnoent()
112         : ignore_error_(errno == ENOENT &&
113                         android::base::GetMinimumLogSeverity() > android::base::DEBUG) {}
ErrorIgnoreEnoent(int errno_to_append)114     explicit ErrorIgnoreEnoent(int errno_to_append)
115         : error_(errno_to_append),
116           ignore_error_(errno_to_append == ENOENT &&
117                         android::base::GetMinimumLogSeverity() > android::base::DEBUG) {}
118 
119     template <typename T>
operator android::base::expected<T,ResultError<android::base::Errno>>()120     operator android::base::expected<T, ResultError<android::base::Errno>>() {
121         if (ignore_error_) {
122             return {};
123         }
124         return error_;
125     }
126 
127     template <typename T>
operator <<(T && t)128     ErrorIgnoreEnoent& operator<<(T&& t) {
129         error_ << t;
130         return *this;
131     }
132 
133   private:
134     Error<> error_;
135     bool ignore_error_;
136 };
137 
ErrnoErrorIgnoreEnoent()138 inline ErrorIgnoreEnoent ErrnoErrorIgnoreEnoent() {
139     return ErrorIgnoreEnoent(errno);
140 }
141 
142 std::vector<std::string> late_import_paths;
143 
144 static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
145 
reboot_into_recovery(const std::vector<std::string> & options)146 static Result<void> reboot_into_recovery(const std::vector<std::string>& options) {
147     LOG(ERROR) << "Rebooting into recovery";
148     std::string err;
149     if (!write_bootloader_message(options, &err)) {
150         return Error() << "Failed to set bootloader message: " << err;
151     }
152     trigger_shutdown("reboot,recovery");
153     return {};
154 }
155 
156 template <typename F>
ForEachServiceInClass(const std::string & classname,F function)157 static void ForEachServiceInClass(const std::string& classname, F function) {
158     for (const auto& service : ServiceList::GetInstance()) {
159         if (service->classnames().count(classname)) std::invoke(function, service);
160     }
161 }
162 
do_class_start(const BuiltinArguments & args)163 static Result<void> do_class_start(const BuiltinArguments& args) {
164     // Do not start a class if it has a property persist.dont_start_class.CLASS set to 1.
165     if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
166         return {};
167     // Starting a class does not start services which are explicitly disabled.
168     // They must  be started individually.
169     for (const auto& service : ServiceList::GetInstance()) {
170         if (service->classnames().count(args[1])) {
171             if (auto result = service->StartIfNotDisabled(); !result.ok()) {
172                 LOG(ERROR) << "Could not start service '" << service->name()
173                            << "' as part of class '" << args[1] << "': " << result.error();
174             }
175         }
176     }
177     return {};
178 }
179 
do_class_stop(const BuiltinArguments & args)180 static Result<void> do_class_stop(const BuiltinArguments& args) {
181     ForEachServiceInClass(args[1], &Service::Stop);
182     return {};
183 }
184 
do_class_reset(const BuiltinArguments & args)185 static Result<void> do_class_reset(const BuiltinArguments& args) {
186     ForEachServiceInClass(args[1], &Service::Reset);
187     return {};
188 }
189 
do_class_restart(const BuiltinArguments & args)190 static Result<void> do_class_restart(const BuiltinArguments& args) {
191     // Do not restart a class if it has a property persist.dont_start_class.CLASS set to 1.
192     if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
193         return {};
194 
195     std::string classname;
196 
197     CHECK(args.size() == 2 || args.size() == 3);
198 
199     bool only_enabled = false;
200     if (args.size() == 3) {
201         if (args[1] != "--only-enabled") {
202             return Error() << "Unexpected argument: " << args[1];
203         }
204         only_enabled = true;
205         classname = args[2];
206     } else if (args.size() == 2) {
207         classname = args[1];
208     }
209 
210     for (const auto& service : ServiceList::GetInstance()) {
211         if (!service->classnames().count(classname)) {
212             continue;
213         }
214         if (only_enabled && !service->IsEnabled()) {
215             continue;
216         }
217         service->Restart();
218     }
219     return {};
220 }
221 
do_domainname(const BuiltinArguments & args)222 static Result<void> do_domainname(const BuiltinArguments& args) {
223     if (auto result = WriteFile("/proc/sys/kernel/domainname", args[1]); !result.ok()) {
224         return Error() << "Unable to write to /proc/sys/kernel/domainname: " << result.error();
225     }
226     return {};
227 }
228 
do_enable(const BuiltinArguments & args)229 static Result<void> do_enable(const BuiltinArguments& args) {
230     Service* svc = ServiceList::GetInstance().FindService(args[1]);
231     if (!svc) return Error() << "Could not find service";
232 
233     if (auto result = svc->Enable(); !result.ok()) {
234         return Error() << "Could not enable service: " << result.error();
235     }
236 
237     return {};
238 }
239 
do_exec(const BuiltinArguments & args)240 static Result<void> do_exec(const BuiltinArguments& args) {
241     auto service = Service::MakeTemporaryOneshotService(args.args);
242     if (!service.ok()) {
243         return Error() << "Could not create exec service: " << service.error();
244     }
245     if (auto result = (*service)->ExecStart(); !result.ok()) {
246         return Error() << "Could not start exec service: " << result.error();
247     }
248 
249     ServiceList::GetInstance().AddService(std::move(*service));
250     return {};
251 }
252 
do_exec_background(const BuiltinArguments & args)253 static Result<void> do_exec_background(const BuiltinArguments& args) {
254     auto service = Service::MakeTemporaryOneshotService(args.args);
255     if (!service.ok()) {
256         return Error() << "Could not create exec background service: " << service.error();
257     }
258     if (auto result = (*service)->Start(); !result.ok()) {
259         return Error() << "Could not start exec background service: " << result.error();
260     }
261 
262     ServiceList::GetInstance().AddService(std::move(*service));
263     return {};
264 }
265 
do_exec_start(const BuiltinArguments & args)266 static Result<void> do_exec_start(const BuiltinArguments& args) {
267     Service* service = ServiceList::GetInstance().FindService(args[1]);
268     if (!service) {
269         return Error() << "Service not found";
270     }
271 
272     if (auto result = service->ExecStart(); !result.ok()) {
273         return Error() << "Could not start exec service: " << result.error();
274     }
275 
276     return {};
277 }
278 
do_export(const BuiltinArguments & args)279 static Result<void> do_export(const BuiltinArguments& args) {
280     if (setenv(args[1].c_str(), args[2].c_str(), 1) == -1) {
281         return ErrnoError() << "setenv() failed";
282     }
283     return {};
284 }
285 
do_load_exports(const BuiltinArguments & args)286 static Result<void> do_load_exports(const BuiltinArguments& args) {
287     auto file_contents = ReadFile(args[1]);
288     if (!file_contents.ok()) {
289         return Error() << "Could not read input file '" << args[1]
290                        << "': " << file_contents.error();
291     }
292 
293     auto lines = Split(*file_contents, "\n");
294     for (const auto& line : lines) {
295         if (line.empty()) {
296             continue;
297         }
298 
299         auto env = Split(line, " ");
300 
301         if (env.size() != 3) {
302             return ErrnoError() << "Expected a line as `export <name> <value>`, found: `" << line
303                                 << "`";
304         }
305 
306         if (env[0] != "export") {
307             return ErrnoError() << "Unknown action: '" << env[0] << "', expected 'export'";
308         }
309 
310         if (setenv(env[1].c_str(), env[2].c_str(), 1) == -1) {
311             return ErrnoError() << "Failed to export '" << line << "' from " << args[1];
312         }
313     }
314 
315     return {};
316 }
317 
do_hostname(const BuiltinArguments & args)318 static Result<void> do_hostname(const BuiltinArguments& args) {
319     if (auto result = WriteFile("/proc/sys/kernel/hostname", args[1]); !result.ok()) {
320         return Error() << "Unable to write to /proc/sys/kernel/hostname: " << result.error();
321     }
322     return {};
323 }
324 
do_ifup(const BuiltinArguments & args)325 static Result<void> do_ifup(const BuiltinArguments& args) {
326     struct ifreq ifr;
327 
328     strlcpy(ifr.ifr_name, args[1].c_str(), IFNAMSIZ);
329 
330     unique_fd s(TEMP_FAILURE_RETRY(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)));
331     if (s < 0) return ErrnoError() << "opening socket failed";
332 
333     if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) {
334         return ErrnoError() << "ioctl(..., SIOCGIFFLAGS, ...) failed";
335     }
336 
337     ifr.ifr_flags |= IFF_UP;
338 
339     if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) {
340         return ErrnoError() << "ioctl(..., SIOCSIFFLAGS, ...) failed";
341     }
342 
343     return {};
344 }
345 
do_insmod(const BuiltinArguments & args)346 static Result<void> do_insmod(const BuiltinArguments& args) {
347     int flags = 0;
348     auto it = args.begin() + 1;
349 
350     if (!(*it).compare("-f")) {
351         flags = MODULE_INIT_IGNORE_VERMAGIC | MODULE_INIT_IGNORE_MODVERSIONS;
352         it++;
353     }
354 
355     std::string filename = *it++;
356     std::string options = android::base::Join(std::vector<std::string>(it, args.end()), ' ');
357 
358     unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
359     if (fd == -1) return ErrnoError() << "open(\"" << filename << "\") failed";
360 
361     int rc = syscall(__NR_finit_module, fd.get(), options.c_str(), flags);
362     if (rc == -1) return ErrnoError() << "finit_module for \"" << filename << "\" failed";
363 
364     return {};
365 }
366 
do_interface_restart(const BuiltinArguments & args)367 static Result<void> do_interface_restart(const BuiltinArguments& args) {
368     Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
369     if (!svc) return Error() << "interface " << args[1] << " not found";
370     svc->Restart();
371     return {};
372 }
373 
do_interface_start(const BuiltinArguments & args)374 static Result<void> do_interface_start(const BuiltinArguments& args) {
375     Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
376     if (!svc) return Error() << "interface " << args[1] << " not found";
377     if (auto result = svc->Start(); !result.ok()) {
378         return Error() << "Could not start interface: " << result.error();
379     }
380     return {};
381 }
382 
do_interface_stop(const BuiltinArguments & args)383 static Result<void> do_interface_stop(const BuiltinArguments& args) {
384     Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
385     if (!svc) return Error() << "interface " << args[1] << " not found";
386     svc->Stop();
387     return {};
388 }
389 
make_dir_with_options(const MkdirOptions & options)390 static Result<void> make_dir_with_options(const MkdirOptions& options) {
391     std::string ref_basename;
392     if (options.ref_option == "ref") {
393         ref_basename = fscrypt_key_ref;
394     } else if (options.ref_option == "per_boot_ref") {
395         ref_basename = fscrypt_key_per_boot_ref;
396     } else {
397         return Error() << "Unknown key option: '" << options.ref_option << "'";
398     }
399 
400     struct stat mstat;
401     if (lstat(options.target.c_str(), &mstat) != 0) {
402         if (errno != ENOENT) {
403             return ErrnoError() << "lstat() failed on " << options.target;
404         }
405         if (!make_dir(options.target, options.mode)) {
406             return ErrnoErrorIgnoreEnoent() << "mkdir() failed on " << options.target;
407         }
408         if (lstat(options.target.c_str(), &mstat) != 0) {
409             return ErrnoError() << "lstat() failed on new " << options.target;
410         }
411     }
412     if (!S_ISDIR(mstat.st_mode)) {
413         return Error() << "Not a directory on " << options.target;
414     }
415     bool needs_chmod = (mstat.st_mode & ~S_IFMT) != options.mode;
416     if ((options.uid != static_cast<uid_t>(-1) && options.uid != mstat.st_uid) ||
417         (options.gid != static_cast<gid_t>(-1) && options.gid != mstat.st_gid)) {
418         if (lchown(options.target.c_str(), options.uid, options.gid) == -1) {
419             return ErrnoError() << "lchown failed on " << options.target;
420         }
421         // chown may have cleared S_ISUID and S_ISGID, chmod again
422         needs_chmod = true;
423     }
424     if (needs_chmod) {
425         if (fchmodat(AT_FDCWD, options.target.c_str(), options.mode, AT_SYMLINK_NOFOLLOW) == -1) {
426             return ErrnoError() << "fchmodat() failed on " << options.target;
427         }
428     }
429     if (fscrypt_is_native()) {
430         if (!FscryptSetDirectoryPolicy(ref_basename, options.fscrypt_action, options.target)) {
431             return reboot_into_recovery(
432                     {"--prompt_and_wipe_data", "--reason=set_policy_failed:"s + options.target});
433         }
434     }
435     return {};
436 }
437 
438 // mkdir <path> [mode] [owner] [group] [<option> ...]
do_mkdir(const BuiltinArguments & args)439 static Result<void> do_mkdir(const BuiltinArguments& args) {
440     auto options = ParseMkdir(args.args);
441     if (!options.ok()) return options.error();
442     return make_dir_with_options(*options);
443 }
444 
445 /* umount <path> */
do_umount(const BuiltinArguments & args)446 static Result<void> do_umount(const BuiltinArguments& args) {
447     if (umount(args[1].c_str()) < 0) {
448         return ErrnoError() << "umount() failed";
449     }
450     return {};
451 }
452 
453 static struct {
454     const char *name;
455     unsigned flag;
456 } mount_flags[] = {
457     { "noatime",    MS_NOATIME },
458     { "noexec",     MS_NOEXEC },
459     { "nosuid",     MS_NOSUID },
460     { "nodev",      MS_NODEV },
461     { "nodiratime", MS_NODIRATIME },
462     { "ro",         MS_RDONLY },
463     { "rw",         0 },
464     { "remount",    MS_REMOUNT },
465     { "bind",       MS_BIND },
466     { "rec",        MS_REC },
467     { "unbindable", MS_UNBINDABLE },
468     { "private",    MS_PRIVATE },
469     { "slave",      MS_SLAVE },
470     { "shared",     MS_SHARED },
471     { "defaults",   0 },
472     { 0,            0 },
473 };
474 
475 #define DATA_MNT_POINT "/data"
476 
477 /* mount <type> <device> <path> <flags ...> <options> */
do_mount(const BuiltinArguments & args)478 static Result<void> do_mount(const BuiltinArguments& args) {
479     const char* options = nullptr;
480     unsigned flags = 0;
481     bool wait = false;
482 
483     for (size_t na = 4; na < args.size(); na++) {
484         size_t i;
485         for (i = 0; mount_flags[i].name; i++) {
486             if (!args[na].compare(mount_flags[i].name)) {
487                 flags |= mount_flags[i].flag;
488                 break;
489             }
490         }
491 
492         if (!mount_flags[i].name) {
493             if (!args[na].compare("wait")) {
494                 wait = true;
495                 // If our last argument isn't a flag, wolf it up as an option string.
496             } else if (na + 1 == args.size()) {
497                 options = args[na].c_str();
498             }
499         }
500     }
501 
502     const char* system = args[1].c_str();
503     const char* source = args[2].c_str();
504     const char* target = args[3].c_str();
505 
506     if (android::base::StartsWith(source, "loop@")) {
507         int mode = (flags & MS_RDONLY) ? O_RDONLY : O_RDWR;
508         unique_fd fd(TEMP_FAILURE_RETRY(open(source + 5, mode | O_CLOEXEC)));
509         if (fd < 0) return ErrnoError() << "open(" << source + 5 << ", " << mode << ") failed";
510 
511         for (size_t n = 0;; n++) {
512             std::string tmp = android::base::StringPrintf("/dev/block/loop%zu", n);
513             unique_fd loop(TEMP_FAILURE_RETRY(open(tmp.c_str(), mode | O_CLOEXEC)));
514             if (loop < 0) return ErrnoError() << "open(" << tmp << ", " << mode << ") failed";
515 
516             loop_info info;
517             /* if it is a blank loop device */
518             if (ioctl(loop, LOOP_GET_STATUS, &info) < 0 && errno == ENXIO) {
519                 /* if it becomes our loop device */
520                 if (ioctl(loop, LOOP_SET_FD, fd.get()) >= 0) {
521                     if (mount(tmp.c_str(), target, system, flags, options) < 0) {
522                         ioctl(loop, LOOP_CLR_FD, 0);
523                         return ErrnoError() << "mount() failed";
524                     }
525                     return {};
526                 }
527             }
528         }
529 
530         return Error() << "out of loopback devices";
531     } else {
532         if (wait)
533             wait_for_file(source, kCommandRetryTimeout);
534         if (mount(source, target, system, flags, options) < 0) {
535             return ErrnoErrorIgnoreEnoent() << "mount() failed";
536         }
537 
538     }
539 
540     return {};
541 }
542 
543 /* Imports .rc files from the specified paths. Default ones are applied if none is given.
544  *
545  * rc_paths: list of paths to rc files to import
546  */
import_late(const std::vector<std::string> & rc_paths)547 static void import_late(const std::vector<std::string>& rc_paths) {
548     auto& action_manager = ActionManager::GetInstance();
549     auto& service_list = ServiceList::GetInstance();
550     Parser parser = CreateParser(action_manager, service_list);
551     if (rc_paths.empty()) {
552         // Fallbacks for partitions on which early mount isn't enabled.
553         for (const auto& path : late_import_paths) {
554             parser.ParseConfig(path);
555         }
556         late_import_paths.clear();
557     } else {
558         for (const auto& rc_path : rc_paths) {
559             parser.ParseConfig(rc_path);
560         }
561     }
562 
563     // Turning this on and letting the INFO logging be discarded adds 0.2s to
564     // Nexus 9 boot time, so it's disabled by default.
565     if (false) DumpState();
566 }
567 
568 /* Queue event based on fs_mgr return code.
569  *
570  * code: return code of fs_mgr_mount_all
571  *
572  * This function might request a reboot, in which case it will
573  * not return.
574  *
575  * return code is processed based on input code
576  */
queue_fs_event(int code,bool userdata_remount)577 static Result<void> queue_fs_event(int code, bool userdata_remount) {
578     if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
579         SetProperty("ro.crypto.state", "unsupported");
580         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
581         return {};
582     } else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
583         /* Setup a wipe via recovery, and reboot into recovery */
584         if (android::gsi::IsGsiRunning()) {
585             return Error() << "cannot wipe within GSI";
586         }
587         PLOG(ERROR) << "fs_mgr_mount_all suggested recovery, so wiping data via recovery.";
588         const std::vector<std::string> options = {"--wipe_data", "--reason=fs_mgr_mount_all" };
589         return reboot_into_recovery(options);
590         /* If reboot worked, there is no return. */
591     } else if (code == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED) {
592         if (!FscryptInstallKeyring()) {
593             return Error() << "FscryptInstallKeyring() failed";
594         }
595         SetProperty("ro.crypto.state", "encrypted");
596 
597         // Although encrypted, we have device key, so we do not need to
598         // do anything different from the nonencrypted case.
599         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
600         return {};
601     } else if (code == FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED) {
602         if (!FscryptInstallKeyring()) {
603             return Error() << "FscryptInstallKeyring() failed";
604         }
605         SetProperty("ro.crypto.state", "encrypted");
606 
607         // Although encrypted, vold has already set the device up, so we do not need to
608         // do anything different from the nonencrypted case.
609         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
610         return {};
611     } else if (code == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
612         if (!FscryptInstallKeyring()) {
613             return Error() << "FscryptInstallKeyring() failed";
614         }
615         SetProperty("ro.crypto.state", "encrypted");
616 
617         // Although encrypted, vold has already set the device up, so we do not need to
618         // do anything different from the nonencrypted case.
619         ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
620         return {};
621     } else if (code > 0) {
622         Error() << "fs_mgr_mount_all() returned unexpected error " << code;
623     }
624     /* else ... < 0: error */
625 
626     return Error() << "Invalid code: " << code;
627 }
628 
629 static int initial_mount_fstab_return_code = -1;
630 
631 /* <= Q: mount_all <fstab> [ <path> ]* [--<options>]*
632  * >= R: mount_all [ <fstab> ] [--<options>]*
633  *
634  * This function might request a reboot, in which case it will
635  * not return.
636  */
do_mount_all(const BuiltinArguments & args)637 static Result<void> do_mount_all(const BuiltinArguments& args) {
638     auto mount_all = ParseMountAll(args.args);
639     if (!mount_all.ok()) return mount_all.error();
640 
641     const char* prop_post_fix = "default";
642     bool queue_event = true;
643     if (mount_all->mode == MOUNT_MODE_EARLY) {
644         prop_post_fix = "early";
645         queue_event = false;
646     } else if (mount_all->mode == MOUNT_MODE_LATE) {
647         prop_post_fix = "late";
648     }
649 
650     std::string prop_name = "ro.boottime.init.mount_all."s + prop_post_fix;
651     android::base::Timer t;
652 
653     Fstab fstab;
654     if (mount_all->fstab_path.empty()) {
655         if (!ReadDefaultFstab(&fstab)) {
656             return Error() << "Could not read default fstab";
657         }
658     } else {
659         if (!ReadFstabFromFile(mount_all->fstab_path, &fstab)) {
660             return Error() << "Could not read fstab";
661         }
662     }
663 
664     auto mount_fstab_result = fs_mgr_mount_all(&fstab, mount_all->mode);
665     SetProperty(prop_name, std::to_string(t.duration().count()));
666 
667     if (mount_all->import_rc) {
668         import_late(mount_all->rc_paths);
669     }
670 
671     if (mount_fstab_result.userdata_mounted) {
672         // This call to fs_mgr_mount_all mounted userdata. Keep the result in
673         // order for userspace reboot to correctly remount userdata.
674         LOG(INFO) << "Userdata mounted using "
675                   << (mount_all->fstab_path.empty() ? "(default fstab)" : mount_all->fstab_path)
676                   << " result : " << mount_fstab_result.code;
677         initial_mount_fstab_return_code = mount_fstab_result.code;
678     }
679 
680     if (queue_event) {
681         /* queue_fs_event will queue event based on mount_fstab return code
682          * and return processed return code*/
683         auto queue_fs_result = queue_fs_event(mount_fstab_result.code, false);
684         if (!queue_fs_result.ok()) {
685             return Error() << "queue_fs_event() failed: " << queue_fs_result.error();
686         }
687     }
688 
689     return {};
690 }
691 
692 /* umount_all [ <fstab> ] */
do_umount_all(const BuiltinArguments & args)693 static Result<void> do_umount_all(const BuiltinArguments& args) {
694     auto umount_all = ParseUmountAll(args.args);
695     if (!umount_all.ok()) return umount_all.error();
696 
697     Fstab fstab;
698     if (umount_all->empty()) {
699         if (!ReadDefaultFstab(&fstab)) {
700             return Error() << "Could not read default fstab";
701         }
702     } else {
703         if (!ReadFstabFromFile(*umount_all, &fstab)) {
704             return Error() << "Could not read fstab";
705         }
706     }
707 
708     if (auto result = fs_mgr_umount_all(&fstab); result != 0) {
709         return Error() << "umount_fstab() failed " << result;
710     }
711     return {};
712 }
713 
714 /* swapon_all [ <fstab> ] */
do_swapon_all(const BuiltinArguments & args)715 static Result<void> do_swapon_all(const BuiltinArguments& args) {
716     auto swapon_all = ParseSwaponAll(args.args);
717     if (!swapon_all.ok()) return swapon_all.error();
718 
719     Fstab fstab;
720     if (swapon_all->empty()) {
721         if (!ReadDefaultFstab(&fstab)) {
722             return Error() << "Could not read default fstab";
723         }
724     } else {
725         if (!ReadFstabFromFile(*swapon_all, &fstab)) {
726             return Error() << "Could not read fstab '" << *swapon_all << "'";
727         }
728     }
729 
730     if (!fs_mgr_swapon_all(fstab)) {
731         return Error() << "fs_mgr_swapon_all() failed";
732     }
733 
734     return {};
735 }
736 
do_setprop(const BuiltinArguments & args)737 static Result<void> do_setprop(const BuiltinArguments& args) {
738     if (StartsWith(args[1], "ctl.")) {
739         return Error()
740                << "Cannot set ctl. properties from init; call the Service functions directly";
741     }
742     if (args[1] == kRestoreconProperty) {
743         return Error() << "Cannot set '" << kRestoreconProperty
744                        << "' from init; use the restorecon builtin directly";
745     }
746 
747     SetProperty(args[1], args[2]);
748     return {};
749 }
750 
do_setrlimit(const BuiltinArguments & args)751 static Result<void> do_setrlimit(const BuiltinArguments& args) {
752     auto rlimit = ParseRlimit(args.args);
753     if (!rlimit.ok()) return rlimit.error();
754 
755     if (setrlimit(rlimit->first, &rlimit->second) == -1) {
756         return ErrnoError() << "setrlimit failed";
757     }
758     return {};
759 }
760 
do_start(const BuiltinArguments & args)761 static Result<void> do_start(const BuiltinArguments& args) {
762     Service* svc = ServiceList::GetInstance().FindService(args[1]);
763     if (!svc) return Error() << "service " << args[1] << " not found";
764     if (auto result = svc->Start(); !result.ok()) {
765         return ErrorIgnoreEnoent() << "Could not start service: " << result.error();
766     }
767     return {};
768 }
769 
do_stop(const BuiltinArguments & args)770 static Result<void> do_stop(const BuiltinArguments& args) {
771     Service* svc = ServiceList::GetInstance().FindService(args[1]);
772     if (!svc) return Error() << "service " << args[1] << " not found";
773     svc->Stop();
774     return {};
775 }
776 
do_restart(const BuiltinArguments & args)777 static Result<void> do_restart(const BuiltinArguments& args) {
778     bool only_if_running = false;
779     if (args.size() == 3) {
780         if (args[1] == "--only-if-running") {
781             only_if_running = true;
782         } else {
783             return Error() << "Unknown argument to restart: " << args[1];
784         }
785     }
786 
787     const auto& classname = args[args.size() - 1];
788     Service* svc = ServiceList::GetInstance().FindService(classname);
789     if (!svc) return Error() << "service " << classname << " not found";
790     if (only_if_running && !svc->IsRunning()) {
791         return {};
792     }
793     svc->Restart();
794     return {};
795 }
796 
do_trigger(const BuiltinArguments & args)797 static Result<void> do_trigger(const BuiltinArguments& args) {
798     ActionManager::GetInstance().QueueEventTrigger(args[1]);
799     return {};
800 }
801 
MakeSymlink(const std::string & target,const std::string & linkpath)802 static int MakeSymlink(const std::string& target, const std::string& linkpath) {
803     std::string secontext;
804     // Passing 0 for mode should work.
805     if (SelabelLookupFileContext(linkpath, 0, &secontext) && !secontext.empty()) {
806         setfscreatecon(secontext.c_str());
807     }
808 
809     int rc = symlink(target.c_str(), linkpath.c_str());
810 
811     if (!secontext.empty()) {
812         int save_errno = errno;
813         setfscreatecon(nullptr);
814         errno = save_errno;
815     }
816 
817     return rc;
818 }
819 
do_symlink(const BuiltinArguments & args)820 static Result<void> do_symlink(const BuiltinArguments& args) {
821     if (MakeSymlink(args[1], args[2]) < 0) {
822         // The symlink builtin is often used to create symlinks for older devices to be backwards
823         // compatible with new paths, therefore we skip reporting this error.
824         return ErrnoErrorIgnoreEnoent() << "symlink() failed";
825     }
826     return {};
827 }
828 
do_rm(const BuiltinArguments & args)829 static Result<void> do_rm(const BuiltinArguments& args) {
830     if (unlink(args[1].c_str()) < 0) {
831         return ErrnoError() << "unlink() failed";
832     }
833     return {};
834 }
835 
do_rmdir(const BuiltinArguments & args)836 static Result<void> do_rmdir(const BuiltinArguments& args) {
837     if (rmdir(args[1].c_str()) < 0) {
838         return ErrnoError() << "rmdir() failed";
839     }
840     return {};
841 }
842 
do_sysclktz(const BuiltinArguments & args)843 static Result<void> do_sysclktz(const BuiltinArguments& args) {
844     struct timezone tz = {};
845     if (!android::base::ParseInt(args[1], &tz.tz_minuteswest)) {
846         return Error() << "Unable to parse mins_west_of_gmt";
847     }
848 
849     if (settimeofday(nullptr, &tz) == -1) {
850         return ErrnoError() << "settimeofday() failed";
851     }
852     return {};
853 }
854 
do_verity_update_state(const BuiltinArguments & args)855 static Result<void> do_verity_update_state(const BuiltinArguments& args) {
856     int mode;
857     if (!fs_mgr_load_verity_state(&mode)) {
858         return Error() << "fs_mgr_load_verity_state() failed";
859     }
860 
861     Fstab fstab;
862     if (!ReadDefaultFstab(&fstab)) {
863         return Error() << "Failed to read default fstab";
864     }
865 
866     for (const auto& entry : fstab) {
867         if (!fs_mgr_is_verity_enabled(entry)) {
868             continue;
869         }
870 
871         // To be consistent in vboot 1.0 and vboot 2.0 (AVB), use "system" for the partition even
872         // for system as root, so it has property [partition.system.verified].
873         std::string partition = entry.mount_point == "/" ? "system" : Basename(entry.mount_point);
874         SetProperty("partition." + partition + ".verified", std::to_string(mode));
875 
876         auto hashtree_info = fs_mgr_get_hashtree_info(entry);
877         if (hashtree_info) {
878             SetProperty("partition." + partition + ".verified.hash_alg", hashtree_info->algorithm);
879             SetProperty("partition." + partition + ".verified.root_digest",
880                         hashtree_info->root_digest);
881         }
882     }
883 
884     return {};
885 }
886 
do_write(const BuiltinArguments & args)887 static Result<void> do_write(const BuiltinArguments& args) {
888     if (auto result = WriteFile(args[1], args[2]); !result.ok()) {
889         return ErrorIgnoreEnoent()
890                << "Unable to write to file '" << args[1] << "': " << result.error();
891     }
892 
893     return {};
894 }
895 
readahead_file(const std::string & filename,bool fully)896 static Result<void> readahead_file(const std::string& filename, bool fully) {
897     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_CLOEXEC)));
898     if (fd == -1) {
899         return ErrnoError() << "Error opening file";
900     }
901     if (posix_fadvise(fd, 0, 0, POSIX_FADV_WILLNEED)) {
902         return ErrnoError() << "Error posix_fadvise file";
903     }
904     if (readahead(fd, 0, std::numeric_limits<size_t>::max())) {
905         return ErrnoError() << "Error readahead file";
906     }
907     if (fully) {
908         char buf[BUFSIZ];
909         ssize_t n;
910         while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) {
911         }
912         if (n != 0) {
913             return ErrnoError() << "Error reading file";
914         }
915     }
916     return {};
917 }
918 
do_readahead(const BuiltinArguments & args)919 static Result<void> do_readahead(const BuiltinArguments& args) {
920     struct stat sb;
921 
922     if (stat(args[1].c_str(), &sb)) {
923         return ErrnoError() << "Error opening " << args[1];
924     }
925 
926     bool readfully = false;
927     if (args.size() == 3 && args[2] == "--fully") {
928         readfully = true;
929     }
930     // We will do readahead in a forked process in order not to block init
931     // since it may block while it reads the
932     // filesystem metadata needed to locate the requested blocks.  This
933     // occurs frequently with ext[234] on large files using indirect blocks
934     // instead of extents, giving the appearance that the call blocks until
935     // the requested data has been read.
936     pid_t pid = fork();
937     if (pid == 0) {
938         if (setpriority(PRIO_PROCESS, 0, static_cast<int>(ANDROID_PRIORITY_LOWEST)) != 0) {
939             PLOG(WARNING) << "setpriority failed";
940         }
941         if (android_set_ioprio(0, IoSchedClass_IDLE, 7)) {
942             PLOG(WARNING) << "ioprio_get failed";
943         }
944         android::base::Timer t;
945         if (S_ISREG(sb.st_mode)) {
946             if (auto result = readahead_file(args[1], readfully); !result.ok()) {
947                 LOG(WARNING) << "Unable to readahead '" << args[1] << "': " << result.error();
948                 _exit(EXIT_FAILURE);
949             }
950         } else if (S_ISDIR(sb.st_mode)) {
951             char* paths[] = {const_cast<char*>(args[1].data()), nullptr};
952             std::unique_ptr<FTS, decltype(&fts_close)> fts(
953                 fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr), fts_close);
954             if (!fts) {
955                 PLOG(ERROR) << "Error opening directory: " << args[1];
956                 _exit(EXIT_FAILURE);
957             }
958             // Traverse the entire hierarchy and do readahead
959             for (FTSENT* ftsent = fts_read(fts.get()); ftsent != nullptr;
960                  ftsent = fts_read(fts.get())) {
961                 if (ftsent->fts_info & FTS_F) {
962                     const std::string filename = ftsent->fts_accpath;
963                     if (auto result = readahead_file(filename, readfully); !result.ok()) {
964                         LOG(WARNING)
965                             << "Unable to readahead '" << filename << "': " << result.error();
966                     }
967                 }
968             }
969         }
970         LOG(INFO) << "Readahead " << args[1] << " took " << t << " asynchronously";
971         _exit(0);
972     } else if (pid < 0) {
973         return ErrnoError() << "Fork failed";
974     }
975     return {};
976 }
977 
do_copy(const BuiltinArguments & args)978 static Result<void> do_copy(const BuiltinArguments& args) {
979     auto file_contents = ReadFile(args[1]);
980     if (!file_contents.ok()) {
981         return Error() << "Could not read input file '" << args[1] << "': " << file_contents.error();
982     }
983     if (auto result = WriteFile(args[2], *file_contents); !result.ok()) {
984         return Error() << "Could not write to output file '" << args[2] << "': " << result.error();
985     }
986 
987     return {};
988 }
989 
do_copy_per_line(const BuiltinArguments & args)990 static Result<void> do_copy_per_line(const BuiltinArguments& args) {
991     std::string file_contents;
992     if (!android::base::ReadFileToString(args[1], &file_contents, true)) {
993         return Error() << "Could not read input file '" << args[1] << "'";
994     }
995     auto lines = Split(file_contents, "\n");
996     for (const auto& line : lines) {
997         auto result = WriteFile(args[2], line);
998         if (!result.ok()) {
999             LOG(VERBOSE) << "Could not write to output file '" << args[2] << "' with '" << line
1000                          << "' : " << result.error();
1001         }
1002     }
1003 
1004     return {};
1005 }
1006 
do_chown(const BuiltinArguments & args)1007 static Result<void> do_chown(const BuiltinArguments& args) {
1008     auto uid = DecodeUid(args[1]);
1009     if (!uid.ok()) {
1010         return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error();
1011     }
1012 
1013     // GID is optional and pushes the index of path out by one if specified.
1014     const std::string& path = (args.size() == 4) ? args[3] : args[2];
1015     Result<gid_t> gid = -1;
1016 
1017     if (args.size() == 4) {
1018         gid = DecodeUid(args[2]);
1019         if (!gid.ok()) {
1020             return Error() << "Unable to decode GID for '" << args[2] << "': " << gid.error();
1021         }
1022     }
1023 
1024     if (lchown(path.c_str(), *uid, *gid) == -1) {
1025         return ErrnoErrorIgnoreEnoent() << "lchown() failed";
1026     }
1027 
1028     return {};
1029 }
1030 
get_mode(const char * s)1031 static mode_t get_mode(const char *s) {
1032     mode_t mode = 0;
1033     while (*s) {
1034         if (*s >= '0' && *s <= '7') {
1035             mode = (mode<<3) | (*s-'0');
1036         } else {
1037             return -1;
1038         }
1039         s++;
1040     }
1041     return mode;
1042 }
1043 
do_chmod(const BuiltinArguments & args)1044 static Result<void> do_chmod(const BuiltinArguments& args) {
1045     mode_t mode = get_mode(args[1].c_str());
1046     if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) {
1047         return ErrnoErrorIgnoreEnoent() << "fchmodat() failed";
1048     }
1049     return {};
1050 }
1051 
do_restorecon(const BuiltinArguments & args)1052 static Result<void> do_restorecon(const BuiltinArguments& args) {
1053     auto restorecon_info = ParseRestorecon(args.args);
1054     if (!restorecon_info.ok()) {
1055         return restorecon_info.error();
1056     }
1057 
1058     const auto& [flag, paths] = *restorecon_info;
1059 
1060     int ret = 0;
1061     for (const auto& path : paths) {
1062         if (selinux_android_restorecon(path.c_str(), flag) < 0) {
1063             ret = errno;
1064         }
1065     }
1066 
1067     if (ret) return ErrnoErrorIgnoreEnoent() << "selinux_android_restorecon() failed";
1068     return {};
1069 }
1070 
do_restorecon_recursive(const BuiltinArguments & args)1071 static Result<void> do_restorecon_recursive(const BuiltinArguments& args) {
1072     std::vector<std::string> non_const_args(args.args);
1073     non_const_args.insert(std::next(non_const_args.begin()), "--recursive");
1074     return do_restorecon({std::move(non_const_args), args.context});
1075 }
1076 
do_loglevel(const BuiltinArguments & args)1077 static Result<void> do_loglevel(const BuiltinArguments& args) {
1078     // TODO: support names instead/as well?
1079     int log_level = -1;
1080     android::base::ParseInt(args[1], &log_level);
1081     android::base::LogSeverity severity;
1082     switch (log_level) {
1083         case 7: severity = android::base::DEBUG; break;
1084         case 6: severity = android::base::INFO; break;
1085         case 5:
1086         case 4: severity = android::base::WARNING; break;
1087         case 3: severity = android::base::ERROR; break;
1088         case 2:
1089         case 1:
1090         case 0: severity = android::base::FATAL; break;
1091         default:
1092             return Error() << "invalid log level " << log_level;
1093     }
1094     android::base::SetMinimumLogSeverity(severity);
1095     return {};
1096 }
1097 
do_load_persist_props(const BuiltinArguments & args)1098 static Result<void> do_load_persist_props(const BuiltinArguments& args) {
1099     SendLoadPersistentPropertiesMessage();
1100 
1101     start_waiting_for_property("ro.persistent_properties.ready", "true");
1102     return {};
1103 }
1104 
do_load_system_props(const BuiltinArguments & args)1105 static Result<void> do_load_system_props(const BuiltinArguments& args) {
1106     LOG(INFO) << "deprecated action `load_system_props` called.";
1107     return {};
1108 }
1109 
do_wait(const BuiltinArguments & args)1110 static Result<void> do_wait(const BuiltinArguments& args) {
1111     auto timeout = kCommandRetryTimeout;
1112     if (args.size() == 3) {
1113         double timeout_double;
1114         if (!android::base::ParseDouble(args[2], &timeout_double, 0)) {
1115             return Error() << "failed to parse timeout";
1116         }
1117         timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(
1118                 std::chrono::duration<double>(timeout_double));
1119     }
1120 
1121     if (wait_for_file(args[1].c_str(), timeout) != 0) {
1122         return Error() << "wait_for_file() failed";
1123     }
1124 
1125     return {};
1126 }
1127 
do_wait_for_prop(const BuiltinArguments & args)1128 static Result<void> do_wait_for_prop(const BuiltinArguments& args) {
1129     const char* name = args[1].c_str();
1130     const char* value = args[2].c_str();
1131     size_t value_len = strlen(value);
1132 
1133     if (!IsLegalPropertyName(name)) {
1134         return Error() << "IsLegalPropertyName(" << name << ") failed";
1135     }
1136     if (value_len >= PROP_VALUE_MAX) {
1137         return Error() << "value too long";
1138     }
1139     if (!start_waiting_for_property(name, value)) {
1140         return Error() << "already waiting for a property";
1141     }
1142     return {};
1143 }
1144 
is_file_crypto()1145 static bool is_file_crypto() {
1146     return android::base::GetProperty("ro.crypto.type", "") == "file";
1147 }
1148 
ExecWithFunctionOnFailure(const std::vector<std::string> & args,std::function<void (const std::string &)> function)1149 static Result<void> ExecWithFunctionOnFailure(const std::vector<std::string>& args,
1150                                               std::function<void(const std::string&)> function) {
1151     auto service = Service::MakeTemporaryOneshotService(args);
1152     if (!service.ok()) {
1153         function("MakeTemporaryOneshotService failed: " + service.error().message());
1154     }
1155     (*service)->AddReapCallback([function](const siginfo_t& siginfo) {
1156         if (siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) {
1157             function(StringPrintf("Exec service failed, status %d", siginfo.si_status));
1158         }
1159     });
1160     if (auto result = (*service)->ExecStart(); !result.ok()) {
1161         function("ExecStart failed: " + result.error().message());
1162     }
1163     ServiceList::GetInstance().AddService(std::move(*service));
1164     return {};
1165 }
1166 
ExecVdcRebootOnFailure(const std::string & vdc_arg)1167 static Result<void> ExecVdcRebootOnFailure(const std::string& vdc_arg) {
1168     bool should_reboot_into_recovery = true;
1169     auto reboot_reason = vdc_arg + "_failed";
1170     if (android::sysprop::InitProperties::userspace_reboot_in_progress().value_or(false)) {
1171         should_reboot_into_recovery = false;
1172         reboot_reason = "userspace_failed," + vdc_arg;
1173     }
1174 
1175     auto reboot = [reboot_reason, should_reboot_into_recovery](const std::string& message) {
1176         // TODO (b/122850122): support this in gsi
1177         if (should_reboot_into_recovery) {
1178             if (fscrypt_is_native() && !android::gsi::IsGsiRunning()) {
1179                 LOG(ERROR) << message << ": Rebooting into recovery, reason: " << reboot_reason;
1180                 if (auto result = reboot_into_recovery(
1181                             {"--prompt_and_wipe_data", "--reason="s + reboot_reason});
1182                     !result.ok()) {
1183                     LOG(FATAL) << "Could not reboot into recovery: " << result.error();
1184                 }
1185             } else {
1186                 LOG(ERROR) << "Failure (reboot suppressed): " << reboot_reason;
1187             }
1188         } else {
1189             LOG(ERROR) << message << ": rebooting, reason: " << reboot_reason;
1190             trigger_shutdown("reboot," + reboot_reason);
1191         }
1192     };
1193 
1194     std::vector<std::string> args = {"exec", "/system/bin/vdc", "--wait", "cryptfs", vdc_arg};
1195     return ExecWithFunctionOnFailure(args, reboot);
1196 }
1197 
do_remount_userdata(const BuiltinArguments & args)1198 static Result<void> do_remount_userdata(const BuiltinArguments& args) {
1199     if (initial_mount_fstab_return_code == -1) {
1200         return Error() << "Calling remount_userdata too early";
1201     }
1202     Fstab fstab;
1203     if (!ReadDefaultFstab(&fstab)) {
1204         // TODO(b/135984674): should we reboot here?
1205         return Error() << "Failed to read fstab";
1206     }
1207     // TODO(b/135984674): check that fstab contains /data.
1208     if (auto rc = fs_mgr_remount_userdata_into_checkpointing(&fstab); rc < 0) {
1209         std::string proc_mounts_output;
1210         android::base::ReadFileToString("/proc/mounts", &proc_mounts_output, true);
1211         android::base::WriteStringToFile(proc_mounts_output,
1212                                          "/metadata/userspacereboot/mount_info.txt");
1213         trigger_shutdown("reboot,mount_userdata_failed");
1214     }
1215     if (auto result = queue_fs_event(initial_mount_fstab_return_code, true); !result.ok()) {
1216         return Error() << "queue_fs_event() failed: " << result.error();
1217     }
1218     return {};
1219 }
1220 
do_installkey(const BuiltinArguments & args)1221 static Result<void> do_installkey(const BuiltinArguments& args) {
1222     if (!is_file_crypto()) return {};
1223 
1224     auto unencrypted_dir = args[1] + fscrypt_unencrypted_folder;
1225     if (!make_dir(unencrypted_dir, 0700) && errno != EEXIST) {
1226         return ErrnoError() << "Failed to create " << unencrypted_dir;
1227     }
1228     return ExecVdcRebootOnFailure("enablefilecrypto");
1229 }
1230 
do_init_user0(const BuiltinArguments & args)1231 static Result<void> do_init_user0(const BuiltinArguments& args) {
1232     return ExecVdcRebootOnFailure("init_user0");
1233 }
1234 
do_mark_post_data(const BuiltinArguments & args)1235 static Result<void> do_mark_post_data(const BuiltinArguments& args) {
1236     ServiceList::GetInstance().MarkPostData();
1237 
1238     return {};
1239 }
1240 
GenerateLinkerConfiguration()1241 static Result<void> GenerateLinkerConfiguration() {
1242     const char* linkerconfig_binary = "/apex/com.android.runtime/bin/linkerconfig";
1243     const char* linkerconfig_target = "/linkerconfig";
1244     const char* arguments[] = {linkerconfig_binary, "--target", linkerconfig_target};
1245 
1246     if (logwrap_fork_execvp(arraysize(arguments), arguments, nullptr, false, LOG_KLOG, false,
1247                             nullptr) != 0) {
1248         return ErrnoError() << "failed to execute linkerconfig";
1249     }
1250 
1251     auto current_mount_ns = GetCurrentMountNamespace();
1252     if (!current_mount_ns.ok()) {
1253         return current_mount_ns.error();
1254     }
1255     if (*current_mount_ns == NS_DEFAULT) {
1256         SetDefaultMountNamespaceReady();
1257     }
1258 
1259     LOG(INFO) << "linkerconfig generated " << linkerconfig_target
1260               << " with mounted APEX modules info";
1261 
1262     return {};
1263 }
1264 
MountLinkerConfigForDefaultNamespace()1265 static Result<void> MountLinkerConfigForDefaultNamespace() {
1266     // No need to mount linkerconfig for default mount namespace if the path does not exist (which
1267     // would mean it is already mounted)
1268     if (access("/linkerconfig/default", 0) != 0) {
1269         return {};
1270     }
1271 
1272     if (mount("/linkerconfig/default", "/linkerconfig", nullptr, MS_BIND | MS_REC, nullptr) != 0) {
1273         return ErrnoError() << "Failed to mount linker configuration for default mount namespace.";
1274     }
1275 
1276     return {};
1277 }
do_update_linker_config(const BuiltinArguments &)1278 static Result<void> do_update_linker_config(const BuiltinArguments&) {
1279     return GenerateLinkerConfiguration();
1280 }
1281 
parse_apex_configs()1282 static Result<void> parse_apex_configs() {
1283     glob_t glob_result;
1284     static constexpr char glob_pattern[] = "/apex/*/etc/*rc";
1285     const int ret = glob(glob_pattern, GLOB_MARK, nullptr, &glob_result);
1286     if (ret != 0 && ret != GLOB_NOMATCH) {
1287         globfree(&glob_result);
1288         return Error() << "glob pattern '" << glob_pattern << "' failed";
1289     }
1290     std::vector<std::string> configs;
1291     Parser parser = CreateServiceOnlyParser(ServiceList::GetInstance(), true);
1292     for (size_t i = 0; i < glob_result.gl_pathc; i++) {
1293         std::string path = glob_result.gl_pathv[i];
1294         // Filter-out /apex/<name>@<ver> paths. The paths are bind-mounted to
1295         // /apex/<name> paths, so unless we filter them out, we will parse the
1296         // same file twice.
1297         std::vector<std::string> paths = android::base::Split(path, "/");
1298         if (paths.size() >= 3 && paths[2].find('@') != std::string::npos) {
1299             continue;
1300         }
1301         // Filter directories
1302         if (path.back() == '/') {
1303             continue;
1304         }
1305         configs.push_back(path);
1306     }
1307     globfree(&glob_result);
1308 
1309     int active_sdk = android::base::GetIntProperty("ro.build.version.sdk", INT_MAX);
1310 
1311     bool success = true;
1312     for (const auto& c : parser.FilterVersionedConfigs(configs, active_sdk)) {
1313         success &= parser.ParseConfigFile(c);
1314     }
1315     ServiceList::GetInstance().MarkServicesUpdate();
1316     if (success) {
1317         return {};
1318     } else {
1319         return Error() << "Could not parse apex configs";
1320     }
1321 }
1322 
1323 /*
1324  * Creates a directory under /data/misc/apexdata/ for each APEX.
1325  */
create_apex_data_dirs()1326 static Result<void> create_apex_data_dirs() {
1327     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir("/apex"), closedir);
1328     if (!dirp) {
1329         return ErrnoError() << "Unable to open apex directory";
1330     }
1331     struct dirent* entry;
1332     while ((entry = readdir(dirp.get())) != nullptr) {
1333         if (entry->d_type != DT_DIR) continue;
1334 
1335         const char* name = entry->d_name;
1336         // skip any starting with "."
1337         if (name[0] == '.') continue;
1338 
1339         if (strchr(name, '@') != nullptr) continue;
1340 
1341         auto path = "/data/misc/apexdata/" + std::string(name);
1342         auto options = MkdirOptions{path, 0771, AID_ROOT, AID_SYSTEM, FscryptAction::kNone, "ref"};
1343         make_dir_with_options(options);
1344     }
1345     return {};
1346 }
1347 
do_perform_apex_config(const BuiltinArguments & args)1348 static Result<void> do_perform_apex_config(const BuiltinArguments& args) {
1349     auto create_dirs = create_apex_data_dirs();
1350     if (!create_dirs.ok()) {
1351         return create_dirs.error();
1352     }
1353     auto parse_configs = parse_apex_configs();
1354     if (!parse_configs.ok()) {
1355         return parse_configs.error();
1356     }
1357 
1358     auto update_linker_config = do_update_linker_config(args);
1359     if (!update_linker_config.ok()) {
1360         return update_linker_config.error();
1361     }
1362 
1363     return {};
1364 }
1365 
do_enter_default_mount_ns(const BuiltinArguments & args)1366 static Result<void> do_enter_default_mount_ns(const BuiltinArguments& args) {
1367     if (auto result = SwitchToMountNamespaceIfNeeded(NS_DEFAULT); !result.ok()) {
1368         return result.error();
1369     }
1370     if (auto result = MountLinkerConfigForDefaultNamespace(); !result.ok()) {
1371         return result.error();
1372     }
1373     LOG(INFO) << "Switched to default mount namespace";
1374     return {};
1375 }
1376 
1377 // Builtin-function-map start
GetBuiltinFunctionMap()1378 const BuiltinFunctionMap& GetBuiltinFunctionMap() {
1379     constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
1380     // clang-format off
1381     static const BuiltinFunctionMap builtin_functions = {
1382         {"bootchart",               {1,     1,    {false,  do_bootchart}}},
1383         {"chmod",                   {2,     2,    {true,   do_chmod}}},
1384         {"chown",                   {2,     3,    {true,   do_chown}}},
1385         {"class_reset",             {1,     1,    {false,  do_class_reset}}},
1386         {"class_restart",           {1,     2,    {false,  do_class_restart}}},
1387         {"class_start",             {1,     1,    {false,  do_class_start}}},
1388         {"class_stop",              {1,     1,    {false,  do_class_stop}}},
1389         {"copy",                    {2,     2,    {true,   do_copy}}},
1390         {"copy_per_line",           {2,     2,    {true,   do_copy_per_line}}},
1391         {"domainname",              {1,     1,    {true,   do_domainname}}},
1392         {"enable",                  {1,     1,    {false,  do_enable}}},
1393         {"exec",                    {1,     kMax, {false,  do_exec}}},
1394         {"exec_background",         {1,     kMax, {false,  do_exec_background}}},
1395         {"exec_start",              {1,     1,    {false,  do_exec_start}}},
1396         {"export",                  {2,     2,    {false,  do_export}}},
1397         {"hostname",                {1,     1,    {true,   do_hostname}}},
1398         {"ifup",                    {1,     1,    {true,   do_ifup}}},
1399         {"init_user0",              {0,     0,    {false,  do_init_user0}}},
1400         {"insmod",                  {1,     kMax, {true,   do_insmod}}},
1401         {"installkey",              {1,     1,    {false,  do_installkey}}},
1402         {"interface_restart",       {1,     1,    {false,  do_interface_restart}}},
1403         {"interface_start",         {1,     1,    {false,  do_interface_start}}},
1404         {"interface_stop",          {1,     1,    {false,  do_interface_stop}}},
1405         {"load_exports",            {1,     1,    {false,  do_load_exports}}},
1406         {"load_persist_props",      {0,     0,    {false,  do_load_persist_props}}},
1407         {"load_system_props",       {0,     0,    {false,  do_load_system_props}}},
1408         {"loglevel",                {1,     1,    {false,  do_loglevel}}},
1409         {"mark_post_data",          {0,     0,    {false,  do_mark_post_data}}},
1410         {"mkdir",                   {1,     6,    {true,   do_mkdir}}},
1411         // TODO: Do mount operations in vendor_init.
1412         // mount_all is currently too complex to run in vendor_init as it queues action triggers,
1413         // imports rc scripts, etc.  It should be simplified and run in vendor_init context.
1414         // mount and umount are run in the same context as mount_all for symmetry.
1415         {"mount_all",               {0,     kMax, {false,  do_mount_all}}},
1416         {"mount",                   {3,     kMax, {false,  do_mount}}},
1417         {"perform_apex_config",     {0,     0,    {false,  do_perform_apex_config}}},
1418         {"umount",                  {1,     1,    {false,  do_umount}}},
1419         {"umount_all",              {0,     1,    {false,  do_umount_all}}},
1420         {"update_linker_config",    {0,     0,    {false,  do_update_linker_config}}},
1421         {"readahead",               {1,     2,    {true,   do_readahead}}},
1422         {"remount_userdata",        {0,     0,    {false,  do_remount_userdata}}},
1423         {"restart",                 {1,     2,    {false,  do_restart}}},
1424         {"restorecon",              {1,     kMax, {true,   do_restorecon}}},
1425         {"restorecon_recursive",    {1,     kMax, {true,   do_restorecon_recursive}}},
1426         {"rm",                      {1,     1,    {true,   do_rm}}},
1427         {"rmdir",                   {1,     1,    {true,   do_rmdir}}},
1428         {"setprop",                 {2,     2,    {true,   do_setprop}}},
1429         {"setrlimit",               {3,     3,    {false,  do_setrlimit}}},
1430         {"start",                   {1,     1,    {false,  do_start}}},
1431         {"stop",                    {1,     1,    {false,  do_stop}}},
1432         {"swapon_all",              {0,     1,    {false,  do_swapon_all}}},
1433         {"enter_default_mount_ns",  {0,     0,    {false,  do_enter_default_mount_ns}}},
1434         {"symlink",                 {2,     2,    {true,   do_symlink}}},
1435         {"sysclktz",                {1,     1,    {false,  do_sysclktz}}},
1436         {"trigger",                 {1,     1,    {false,  do_trigger}}},
1437         {"verity_update_state",     {0,     0,    {false,  do_verity_update_state}}},
1438         {"wait",                    {1,     2,    {true,   do_wait}}},
1439         {"wait_for_prop",           {2,     2,    {false,  do_wait_for_prop}}},
1440         {"write",                   {2,     2,    {true,   do_write}}},
1441     };
1442     // clang-format on
1443     return builtin_functions;
1444 }
1445 // Builtin-function-map end
1446 
1447 }  // namespace init
1448 }  // namespace android
1449