2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <android-base/chrono_utils.h>
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/properties.h>
26 #include <android-base/stringprintf.h>
27 #include <android-base/strings.h>
28 #include <android-base/unique_fd.h>
29 #include <cutils/fs.h>
30 #include <logwrap/logwrap.h>
31 #include <private/android_filesystem_config.h>
40 #include <sys/mount.h>
42 #include <sys/statvfs.h>
43 #include <sys/sysmacros.h>
44 #include <sys/types.h>
51 #ifndef UMOUNT_NOFOLLOW
52 #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
55 using namespace std::chrono_literals;
56 using android::base::ReadFileToString;
57 using android::base::StringPrintf;
62 security_context_t sBlkidContext = nullptr;
63 security_context_t sBlkidUntrustedContext = nullptr;
64 security_context_t sFsckContext = nullptr;
65 security_context_t sFsckUntrustedContext = nullptr;
67 bool sSleepOnUnmount = true;
69 static const char* kBlkidPath = "/system/bin/blkid";
70 static const char* kKeyPath = "/data/misc/vold";
72 static const char* kProcFilesystems = "/proc/filesystems";
74 // Lock used to protect process-level SELinux changes from racing with each
75 // other between multiple threads.
76 static std::mutex kSecurityLock;
78 status_t CreateDeviceNode(const std::string& path, dev_t dev) {
79 std::lock_guard<std::mutex> lock(kSecurityLock);
80 const char* cpath = path.c_str();
83 char* secontext = nullptr;
85 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
86 setfscreatecon(secontext);
90 mode_t mode = 0660 | S_IFBLK;
91 if (mknod(cpath, mode, dev) < 0) {
92 if (errno != EEXIST) {
93 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
100 setfscreatecon(nullptr);
107 status_t DestroyDeviceNode(const std::string& path) {
108 const char* cpath = path.c_str();
109 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
116 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
117 std::lock_guard<std::mutex> lock(kSecurityLock);
118 const char* cpath = path.c_str();
120 char* secontext = nullptr;
122 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
123 setfscreatecon(secontext);
127 int res = fs_prepare_dir(cpath, mode, uid, gid);
130 setfscreatecon(nullptr);
141 status_t ForceUnmount(const std::string& path) {
142 const char* cpath = path.c_str();
143 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
146 // Apps might still be handling eject request, so wait before
147 // we start sending signals
148 if (sSleepOnUnmount) sleep(5);
150 KillProcessesWithOpenFiles(path, SIGINT);
151 if (sSleepOnUnmount) sleep(5);
152 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
156 KillProcessesWithOpenFiles(path, SIGTERM);
157 if (sSleepOnUnmount) sleep(5);
158 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
162 KillProcessesWithOpenFiles(path, SIGKILL);
163 if (sSleepOnUnmount) sleep(5);
164 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
171 status_t KillProcessesUsingPath(const std::string& path) {
172 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
175 if (sSleepOnUnmount) sleep(5);
177 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
180 if (sSleepOnUnmount) sleep(5);
182 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
185 if (sSleepOnUnmount) sleep(5);
187 // Send SIGKILL a second time to determine if we've
188 // actually killed everyone with open files
189 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
192 PLOG(ERROR) << "Failed to kill processes using " << path;
196 status_t BindMount(const std::string& source, const std::string& target) {
197 if (UnmountTree(target) < 0) {
200 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
201 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
207 status_t Symlink(const std::string& target, const std::string& linkpath) {
208 if (Unlink(linkpath) < 0) {
211 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
212 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
218 status_t Unlink(const std::string& linkpath) {
219 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
220 PLOG(ERROR) << "Failed to unlink " << linkpath;
226 status_t CreateDir(const std::string& dir, mode_t mode) {
228 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
229 if (S_ISDIR(sb.st_mode)) {
231 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
232 PLOG(ERROR) << "Failed to unlink " << dir;
235 } else if (errno != ENOENT) {
236 PLOG(ERROR) << "Failed to stat " << dir;
239 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
240 PLOG(ERROR) << "Failed to mkdir " << dir;
246 bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
247 auto qual = key + "=\"";
250 start = raw.find(qual, start);
251 if (start == std::string::npos) return false;
252 if (start == 0 || raw[start - 1] == ' ') {
257 start += qual.length();
259 auto end = raw.find("\"", start);
260 if (end == std::string::npos) return false;
262 *value = raw.substr(start, end - start);
266 static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
267 std::string* fsLabel, bool untrusted) {
272 std::vector<std::string> cmd;
273 cmd.push_back(kBlkidPath);
275 cmd.push_back("/dev/null");
277 cmd.push_back("TYPE");
279 cmd.push_back("UUID");
281 cmd.push_back("LABEL");
284 std::vector<std::string> output;
285 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
287 LOG(WARNING) << "blkid failed to identify " << path;
291 for (const auto& line : output) {
292 // Extract values from blkid output, if defined
293 FindValue(line, "TYPE", fsType);
294 FindValue(line, "UUID", fsUuid);
295 FindValue(line, "LABEL", fsLabel);
301 status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
302 std::string* fsLabel) {
303 return readMetadata(path, fsType, fsUuid, fsLabel, false);
306 status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
307 std::string* fsLabel) {
308 return readMetadata(path, fsType, fsUuid, fsLabel, true);
311 static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
312 std::vector<const char*> argv;
313 argv.reserve(args.size() + 1);
314 for (const auto& arg : args) {
318 LOG(DEBUG) << " " << arg;
320 argv.emplace_back(arg.data());
322 argv.emplace_back(nullptr);
326 static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
327 android::base::unique_fd ufd) {
328 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
330 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
333 if (output) output->clear();
335 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
337 if (output) output->emplace_back(line);
342 status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
343 security_context_t context) {
344 auto argv = ConvertToArgv(args);
346 android::base::unique_fd pipe_read, pipe_write;
347 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
348 PLOG(ERROR) << "Pipe in ForkExecvp";
355 if (setexeccon(context)) {
356 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
361 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
362 PLOG(ERROR) << "dup2 in ForkExecvp";
366 execvp(argv[0], const_cast<char**>(argv.data()));
367 PLOG(ERROR) << "exec in ForkExecvp";
371 PLOG(ERROR) << "fork in ForkExecvp";
376 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
377 if (st != 0) return st;
380 if (waitpid(pid, &status, 0) == -1) {
381 PLOG(ERROR) << "waitpid in ForkExecvp";
384 if (!WIFEXITED(status)) {
385 LOG(ERROR) << "Process did not exit normally, status: " << status;
388 if (WEXITSTATUS(status)) {
389 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
390 return WEXITSTATUS(status);
395 pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
396 auto argv = ConvertToArgv(args);
401 close(STDOUT_FILENO);
402 close(STDERR_FILENO);
404 execvp(argv[0], const_cast<char**>(argv.data()));
405 PLOG(ERROR) << "exec in ForkExecvpAsync";
409 PLOG(ERROR) << "fork in ForkExecvpAsync";
415 status_t ReadRandomBytes(size_t bytes, std::string& out) {
417 return ReadRandomBytes(bytes, &out[0]);
420 status_t ReadRandomBytes(size_t bytes, char* buf) {
421 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
427 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
440 status_t GenerateRandomUuid(std::string& out) {
441 status_t res = ReadRandomBytes(16, out);
443 out[6] &= 0x0f; /* clear version */
444 out[6] |= 0x40; /* set to version 4 */
445 out[8] &= 0x3f; /* clear variant */
446 out[8] |= 0x80; /* set to IETF variant */
451 status_t HexToStr(const std::string& hex, std::string& str) {
455 for (size_t i = 0; i < hex.size(); i++) {
459 case ' ': case '-': case ':': continue;
460 case 'f': case 'F': val = 15; break;
461 case 'e': case 'E': val = 14; break;
462 case 'd': case 'D': val = 13; break;
463 case 'c': case 'C': val = 12; break;
464 case 'b': case 'B': val = 11; break;
465 case 'a': case 'A': val = 10; break;
466 case '9': val = 9; break;
467 case '8': val = 8; break;
468 case '7': val = 7; break;
469 case '6': val = 6; break;
470 case '5': val = 5; break;
471 case '4': val = 4; break;
472 case '3': val = 3; break;
473 case '2': val = 2; break;
474 case '1': val = 1; break;
475 case '0': val = 0; break;
476 default: return -EINVAL;
489 return even ? OK : -EINVAL;
492 static const char* kLookup = "0123456789abcdef";
494 status_t StrToHex(const std::string& str, std::string& hex) {
496 for (size_t i = 0; i < str.size(); i++) {
497 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
498 hex.push_back(kLookup[str[i] & 0x0F]);
503 status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
505 for (size_t i = 0; i < str.size(); i++) {
506 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
507 hex.push_back(kLookup[str.data()[i] & 0x0F]);
512 status_t NormalizeHex(const std::string& in, std::string& out) {
514 if (HexToStr(in, tmp)) {
517 return StrToHex(tmp, out);
520 status_t GetBlockDevSize(int fd, uint64_t* size) {
521 if (ioctl(fd, BLKGETSIZE64, size)) {
528 status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
529 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
536 res = GetBlockDevSize(fd, size);
543 status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
545 status_t res = GetBlockDevSize(path, &size);
551 *nr_sec = size / 512;
556 uint64_t GetFreeBytes(const std::string& path) {
558 if (statvfs(path.c_str(), &sb) == 0) {
559 return (uint64_t)sb.f_bavail * sb.f_frsize;
565 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
566 // eventually be migrated into system/
567 static int64_t stat_size(struct stat* s) {
568 int64_t blksize = s->st_blksize;
569 // count actual blocks used instead of nominal file size
570 int64_t size = s->st_blocks * 512;
573 /* round up to filesystem block size */
574 size = (size + blksize - 1) & (~(blksize - 1));
580 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
581 // eventually be migrated into system/
582 int64_t calculate_dir_size(int dfd) {
594 while ((de = readdir(d))) {
595 const char* name = de->d_name;
596 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
597 size += stat_size(&s);
599 if (de->d_type == DT_DIR) {
602 /* always skip "." and ".." */
603 if (name[0] == '.') {
604 if (name[1] == 0) continue;
605 if ((name[1] == '.') && (name[2] == 0)) continue;
608 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
610 size += calculate_dir_size(subfd);
618 uint64_t GetTreeBytes(const std::string& path) {
619 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
621 PLOG(WARNING) << "Failed to open " << path;
624 return calculate_dir_size(dirfd);
628 bool IsFilesystemSupported(const std::string& fsType) {
629 std::string supported;
630 if (!ReadFileToString(kProcFilesystems, &supported)) {
631 PLOG(ERROR) << "Failed to read supported filesystems";
634 return supported.find(fsType + "\n") != std::string::npos;
637 status_t WipeBlockDevice(const std::string& path) {
639 const char* c_path = path.c_str();
640 uint64_t range[2] = {0, 0};
642 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
644 PLOG(ERROR) << "Failed to open " << path;
648 if (GetBlockDevSize(fd, &range[1]) != OK) {
649 PLOG(ERROR) << "Failed to determine size of " << path;
653 LOG(INFO) << "About to discard " << range[1] << " on " << path;
654 if (ioctl(fd, BLKDISCARD, &range) == 0) {
655 LOG(INFO) << "Discard success on " << path;
658 PLOG(ERROR) << "Discard failure on " << path;
666 static bool isValidFilename(const std::string& name) {
667 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
674 std::string BuildKeyPath(const std::string& partGuid) {
675 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
678 std::string BuildDataSystemLegacyPath(userid_t userId) {
679 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
682 std::string BuildDataSystemCePath(userid_t userId) {
683 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
686 std::string BuildDataSystemDePath(userid_t userId) {
687 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
690 std::string BuildDataMiscLegacyPath(userid_t userId) {
691 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
694 std::string BuildDataMiscCePath(userid_t userId) {
695 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
698 std::string BuildDataMiscDePath(userid_t userId) {
699 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
702 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
703 std::string BuildDataProfilesDePath(userid_t userId) {
704 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
707 std::string BuildDataVendorCePath(userid_t userId) {
708 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
711 std::string BuildDataVendorDePath(userid_t userId) {
712 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
715 std::string BuildDataPath(const std::string& volumeUuid) {
716 // TODO: unify with installd path generation logic
717 if (volumeUuid.empty()) {
720 CHECK(isValidFilename(volumeUuid));
721 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
725 std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
726 // TODO: unify with installd path generation logic
727 std::string data(BuildDataPath(volumeUuid));
728 return StringPrintf("%s/media/%u", data.c_str(), userId);
731 std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
732 // TODO: unify with installd path generation logic
733 std::string data(BuildDataPath(volumeUuid));
734 if (volumeUuid.empty() && userId == 0) {
735 std::string legacy = StringPrintf("%s/data", data.c_str());
737 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
738 /* /data/data is dir, return /data/data for legacy system */
742 return StringPrintf("%s/user/%u", data.c_str(), userId);
745 std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
746 // TODO: unify with installd path generation logic
747 std::string data(BuildDataPath(volumeUuid));
748 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
751 dev_t GetDevice(const std::string& path) {
753 if (stat(path.c_str(), &sb)) {
754 PLOG(WARNING) << "Failed to stat " << path;
761 status_t RestoreconRecursive(const std::string& path) {
762 LOG(DEBUG) << "Starting restorecon of " << path;
764 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
766 android::base::SetProperty(kRestoreconString, "");
767 android::base::SetProperty(kRestoreconString, path);
769 android::base::WaitForProperty(kRestoreconString, path);
771 LOG(DEBUG) << "Finished restorecon of " << path;
775 bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
776 // Shamelessly borrowed from android::base::Readlink()
779 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
780 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
781 // waste memory to just start there. We add 1 so that we can recognize
782 // whether it actually fit (rather than being truncated to 4095).
783 std::vector<char> buf(4095 + 1);
785 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
786 // Unrecoverable error?
787 if (size == -1) return false;
788 // It fit! (If size == buf.size(), it may have been truncated.)
789 if (static_cast<size_t>(size) < buf.size()) {
790 result->assign(&buf[0], size);
793 // Double our buffer and try again.
794 buf.resize(buf.size() * 2);
798 bool IsRunningInEmulator() {
799 return android::base::GetBoolProperty("ro.kernel.qemu", false);
802 static status_t findMountPointsWithPrefix(const std::string& prefix,
803 std::list<std::string>& mountPoints) {
804 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
805 // when the prefix is /foo/bar
806 std::string prefixWithSlash(prefix);
807 if (prefix.back() != '/') {
808 android::base::StringAppendF(&prefixWithSlash, "/");
811 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
813 PLOG(ERROR) << "Unable to open /proc/mounts";
817 // Some volumes can be stacked on each other, so force unmount in
818 // reverse order to give us the best chance of success.
819 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
820 while ((mnt = getmntent(mnts.get())) != nullptr) {
821 auto mountPoint = std::string(mnt->mnt_dir) + "/";
822 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
823 mountPoints.push_front(mountPoint);
829 // Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
830 status_t UnmountTreeWithPrefix(const std::string& prefix) {
831 std::list<std::string> toUnmount;
832 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
836 for (const auto& path : toUnmount) {
837 if (umount2(path.c_str(), MNT_DETACH)) {
838 PLOG(ERROR) << "Failed to unmount " << path;
845 status_t UnmountTree(const std::string& mountPoint) {
846 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
848 PLOG(ERROR) << "Failed to unmount " << mountPoint;
854 static status_t delete_dir_contents(DIR* dir) {
855 // Shamelessly borrowed from android::installd
856 int dfd = dirfd(dir);
861 status_t result = OK;
863 while ((de = readdir(dir))) {
864 const char* name = de->d_name;
865 if (de->d_type == DT_DIR) {
866 /* always skip "." and ".." */
867 if (name[0] == '.') {
868 if (name[1] == 0) continue;
869 if ((name[1] == '.') && (name[2] == 0)) continue;
872 android::base::unique_fd subfd(
873 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
874 if (subfd.get() == -1) {
875 PLOG(ERROR) << "Couldn't openat " << name;
879 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
880 android::base::Fdopendir(std::move(subfd)), closedir);
882 PLOG(ERROR) << "Couldn't fdopendir " << name;
886 result = delete_dir_contents(subdirp.get());
887 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
888 PLOG(ERROR) << "Couldn't unlinkat " << name;
892 if (unlinkat(dfd, name, 0) < 0) {
893 PLOG(ERROR) << "Couldn't unlinkat " << name;
901 status_t DeleteDirContentsAndDir(const std::string& pathname) {
902 status_t res = DeleteDirContents(pathname);
906 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
907 PLOG(ERROR) << "rmdir failed on " << pathname;
910 LOG(VERBOSE) << "Success: rmdir on " << pathname;
914 status_t DeleteDirContents(const std::string& pathname) {
915 // Shamelessly borrowed from android::installd
916 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
918 if (errno == ENOENT) {
921 PLOG(ERROR) << "Failed to opendir " << pathname;
924 return delete_dir_contents(dirp.get());
927 // TODO(118708649): fix duplication with init/util.h
928 status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
929 android::base::Timer t;
930 while (t.duration() < timeout) {
932 if (stat(filename, &sb) != -1) {
933 LOG(INFO) << "wait for '" << filename << "' took " << t;
936 std::this_thread::sleep_for(10ms);
938 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
942 bool FsyncDirectory(const std::string& dirname) {
943 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
945 PLOG(ERROR) << "Failed to open " << dirname;
948 if (fsync(fd) == -1) {
949 if (errno == EROFS || errno == EINVAL) {
950 PLOG(WARNING) << "Skip fsync " << dirname
951 << " on a file system does not support synchronization";
953 PLOG(ERROR) << "Failed to fsync " << dirname;
960 bool writeStringToFile(const std::string& payload, const std::string& filename) {
961 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
962 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
964 PLOG(ERROR) << "Failed to open " << filename;
967 if (!android::base::WriteStringToFd(payload, fd)) {
968 PLOG(ERROR) << "Failed to write to " << filename;
969 unlink(filename.c_str());
972 // fsync as close won't guarantee flush data
973 // see close(2), fsync(2) and b/68901441
974 if (fsync(fd) == -1) {
975 if (errno == EROFS || errno == EINVAL) {
976 PLOG(WARNING) << "Skip fsync " << filename
977 << " on a file system does not support synchronization";
979 PLOG(ERROR) << "Failed to fsync " << filename;
980 unlink(filename.c_str());
988 } // namespace android