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