blob: 656d706fac39aab46b7bc647b4c33ffae77f06dd [file] [log] [blame]
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001/*
2 * Copyright (C) 2015 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
Jeff Sharkeydeb24052015-03-02 21:01:40 -080017#include "Utils.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070018
Jeff Sharkeydeb24052015-03-02 21:01:40 -080019#include "Process.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070020#include "sehandle.h"
Jeff Sharkeydeb24052015-03-02 21:01:40 -080021
Paul Crowley298fa322018-10-30 15:59:24 -070022#include <android-base/chrono_utils.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080023#include <android-base/file.h>
24#include <android-base/logging.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070025#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080026#include <android-base/stringprintf.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070027#include <android-base/strings.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070028#include <android-base/unique_fd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080029#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070030#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070031#include <private/android_filesystem_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080032
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070033#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080034#include <fcntl.h>
35#include <linux/fs.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070036#include <mntent.h>
37#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080038#include <stdlib.h>
39#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080040#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070041#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070042#include <sys/sysmacros.h>
43#include <sys/types.h>
44#include <sys/wait.h>
Paul Crowley298fa322018-10-30 15:59:24 -070045
Sudheer Shanka89ddf992018-09-25 14:22:07 -070046#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070047#include <mutex>
Paul Crowley298fa322018-10-30 15:59:24 -070048#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080049
50#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070051#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080052#endif
53
Paul Crowley298fa322018-10-30 15:59:24 -070054using namespace std::chrono_literals;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070055using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070056using android::base::StringPrintf;
57
Jeff Sharkeydeb24052015-03-02 21:01:40 -080058namespace android {
59namespace vold {
60
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070061security_context_t sBlkidContext = nullptr;
62security_context_t sBlkidUntrustedContext = nullptr;
63security_context_t sFsckContext = nullptr;
64security_context_t sFsckUntrustedContext = nullptr;
65
Paul Crowley56292ef2017-10-20 08:07:53 -070066bool sSleepOnUnmount = true;
67
Jeff Sharkey9c484982015-03-31 10:35:33 -070068static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070069static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070070
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070071static const char* kProcFilesystems = "/proc/filesystems";
72
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060073// Lock used to protect process-level SELinux changes from racing with each
74// other between multiple threads.
75static std::mutex kSecurityLock;
76
Jeff Sharkeydeb24052015-03-02 21:01:40 -080077status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060078 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080079 const char* cpath = path.c_str();
80 status_t res = 0;
81
82 char* secontext = nullptr;
83 if (sehandle) {
84 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
85 setfscreatecon(secontext);
86 }
87 }
88
89 mode_t mode = 0660 | S_IFBLK;
90 if (mknod(cpath, mode, dev) < 0) {
91 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070092 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
93 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080094 res = -errno;
95 }
96 }
97
98 if (secontext) {
99 setfscreatecon(nullptr);
100 freecon(secontext);
101 }
102
103 return res;
104}
105
106status_t DestroyDeviceNode(const std::string& path) {
107 const char* cpath = path.c_str();
108 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
109 return -errno;
110 } else {
111 return OK;
112 }
113}
114
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700115status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600116 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700117 const char* cpath = path.c_str();
118
119 char* secontext = nullptr;
120 if (sehandle) {
121 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
122 setfscreatecon(secontext);
123 }
124 }
125
126 int res = fs_prepare_dir(cpath, mode, uid, gid);
127
128 if (secontext) {
129 setfscreatecon(nullptr);
130 freecon(secontext);
131 }
132
133 if (res == 0) {
134 return OK;
135 } else {
136 return -errno;
137 }
138}
139
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800140status_t ForceUnmount(const std::string& path) {
141 const char* cpath = path.c_str();
142 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
143 return OK;
144 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700145 // Apps might still be handling eject request, so wait before
146 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700147 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700148
Jeff Sharkey3472e522017-10-06 18:02:53 -0600149 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700150 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700151 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
152 return OK;
153 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700154
Jeff Sharkey3472e522017-10-06 18:02:53 -0600155 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700156 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800157 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
158 return OK;
159 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700160
Jeff Sharkey3472e522017-10-06 18:02:53 -0600161 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700162 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700163 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
164 return OK;
165 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700166
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800167 return -errno;
168}
169
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700170status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600171 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700172 return OK;
173 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700174 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700175
Jeff Sharkey3472e522017-10-06 18:02:53 -0600176 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700177 return OK;
178 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700179 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700180
Jeff Sharkey3472e522017-10-06 18:02:53 -0600181 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700182 return OK;
183 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700184 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700185
186 // Send SIGKILL a second time to determine if we've
187 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600188 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700189 return OK;
190 }
191 PLOG(ERROR) << "Failed to kill processes using " << path;
192 return -EBUSY;
193}
194
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700195status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800196 if (UnmountTree(target) < 0) {
197 return -errno;
198 }
199 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700200 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
201 return -errno;
202 }
203 return OK;
204}
205
Sudheer Shanka023b5392019-02-06 12:39:19 -0800206status_t Symlink(const std::string& target, const std::string& linkpath) {
207 if (Unlink(linkpath) < 0) {
208 return -errno;
209 }
210 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
211 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
212 return -errno;
213 }
214 return OK;
215}
216
217status_t Unlink(const std::string& linkpath) {
218 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
219 PLOG(ERROR) << "Failed to unlink " << linkpath;
220 return -errno;
221 }
222 return OK;
223}
224
Jeff Sharkey3472e522017-10-06 18:02:53 -0600225bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
226 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800227 size_t start = 0;
228 while (true) {
229 start = raw.find(qual, start);
230 if (start == std::string::npos) return false;
231 if (start == 0 || raw[start - 1] == ' ') {
232 break;
233 }
234 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600235 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600236 start += qual.length();
237
238 auto end = raw.find("\"", start);
239 if (end == std::string::npos) return false;
240
241 *value = raw.substr(start, end - start);
242 return true;
243}
244
Paul Crowley14c8c072018-09-18 13:30:21 -0700245static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
246 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600247 fsType->clear();
248 fsUuid->clear();
249 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700250
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700251 std::vector<std::string> cmd;
252 cmd.push_back(kBlkidPath);
253 cmd.push_back("-c");
254 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700255 cmd.push_back("-s");
256 cmd.push_back("TYPE");
257 cmd.push_back("-s");
258 cmd.push_back("UUID");
259 cmd.push_back("-s");
260 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700261 cmd.push_back(path);
262
263 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800264 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700265 if (res != OK) {
266 LOG(WARNING) << "blkid failed to identify " << path;
267 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700268 }
269
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700270 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700271 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600272 FindValue(line, "TYPE", fsType);
273 FindValue(line, "UUID", fsUuid);
274 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700275 }
276
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700277 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700278}
279
Paul Crowley14c8c072018-09-18 13:30:21 -0700280status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
281 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700282 return readMetadata(path, fsType, fsUuid, fsLabel, false);
283}
284
Paul Crowley14c8c072018-09-18 13:30:21 -0700285status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
286 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700287 return readMetadata(path, fsType, fsUuid, fsLabel, true);
288}
289
Paul Crowleyde2d6202018-11-30 11:43:47 -0800290static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
291 std::vector<const char*> argv;
292 argv.reserve(args.size() + 1);
293 for (const auto& arg : args) {
294 if (argv.empty()) {
295 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700296 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800297 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700298 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800299 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700300 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800301 argv.emplace_back(nullptr);
302 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700303}
304
Paul Crowleyde2d6202018-11-30 11:43:47 -0800305static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
306 android::base::unique_fd ufd) {
307 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700308 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800309 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700310 return -errno;
311 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800312 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700313 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800314 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700315 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800316 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700317 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800318 return OK;
319}
320
321status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
322 security_context_t context) {
323 auto argv = ConvertToArgv(args);
324
Paul Crowleye6d76632018-11-30 11:43:47 -0800325 android::base::unique_fd pipe_read, pipe_write;
326 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
327 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800328 return -errno;
329 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800330
331 pid_t pid = fork();
332 if (pid == 0) {
333 if (context) {
334 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800335 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800336 abort();
337 }
338 }
339 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800340 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
341 PLOG(ERROR) << "dup2 in ForkExecvp";
342 _exit(EXIT_FAILURE);
343 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800344 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800345 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800346 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800347 _exit(EXIT_FAILURE);
348 }
349 if (pid == -1) {
350 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700351 return -errno;
352 }
353
Paul Crowleyde2d6202018-11-30 11:43:47 -0800354 pipe_write.reset();
355 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
356 if (st != 0) return st;
357
358 int status;
359 if (waitpid(pid, &status, 0) == -1) {
360 PLOG(ERROR) << "waitpid in ForkExecvp";
361 return -errno;
362 }
363 if (!WIFEXITED(status)) {
364 LOG(ERROR) << "Process did not exit normally, status: " << status;
365 return -ECHILD;
366 }
367 if (WEXITSTATUS(status)) {
368 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
369 return WEXITSTATUS(status);
370 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700371 return OK;
372}
373
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700374pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800375 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700376
377 pid_t pid = fork();
378 if (pid == 0) {
379 close(STDIN_FILENO);
380 close(STDOUT_FILENO);
381 close(STDERR_FILENO);
382
Paul Crowleyde2d6202018-11-30 11:43:47 -0800383 execvp(argv[0], const_cast<char**>(argv.data()));
384 PLOG(ERROR) << "exec in ForkExecvpAsync";
385 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700386 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700387 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800388 PLOG(ERROR) << "fork in ForkExecvpAsync";
389 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700390 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700391 return pid;
392}
393
Jeff Sharkey9c484982015-03-31 10:35:33 -0700394status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100395 out.resize(bytes);
396 return ReadRandomBytes(bytes, &out[0]);
397}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700398
Pavel Grafove2e2d302017-08-01 17:15:53 +0100399status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700400 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
401 if (fd == -1) {
402 return -errno;
403 }
404
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800405 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100406 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700407 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100408 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700409 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700410 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700411
412 if (bytes == 0) {
413 return OK;
414 } else {
415 return -EIO;
416 }
417}
418
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600419status_t GenerateRandomUuid(std::string& out) {
420 status_t res = ReadRandomBytes(16, out);
421 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700422 out[6] &= 0x0f; /* clear version */
423 out[6] |= 0x40; /* set to version 4 */
424 out[8] &= 0x3f; /* clear variant */
425 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600426 }
427 return res;
428}
429
Jeff Sharkey9c484982015-03-31 10:35:33 -0700430status_t HexToStr(const std::string& hex, std::string& str) {
431 str.clear();
432 bool even = true;
433 char cur = 0;
434 for (size_t i = 0; i < hex.size(); i++) {
435 int val = 0;
436 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700437 // clang-format off
438 case ' ': case '-': case ':': continue;
439 case 'f': case 'F': val = 15; break;
440 case 'e': case 'E': val = 14; break;
441 case 'd': case 'D': val = 13; break;
442 case 'c': case 'C': val = 12; break;
443 case 'b': case 'B': val = 11; break;
444 case 'a': case 'A': val = 10; break;
445 case '9': val = 9; break;
446 case '8': val = 8; break;
447 case '7': val = 7; break;
448 case '6': val = 6; break;
449 case '5': val = 5; break;
450 case '4': val = 4; break;
451 case '3': val = 3; break;
452 case '2': val = 2; break;
453 case '1': val = 1; break;
454 case '0': val = 0; break;
455 default: return -EINVAL;
456 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700457 }
458
459 if (even) {
460 cur = val << 4;
461 } else {
462 cur += val;
463 str.push_back(cur);
464 cur = 0;
465 }
466 even = !even;
467 }
468 return even ? OK : -EINVAL;
469}
470
471static const char* kLookup = "0123456789abcdef";
472
473status_t StrToHex(const std::string& str, std::string& hex) {
474 hex.clear();
475 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700476 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700477 hex.push_back(kLookup[str[i] & 0x0F]);
478 }
479 return OK;
480}
481
Pavel Grafove2e2d302017-08-01 17:15:53 +0100482status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
483 hex.clear();
484 for (size_t i = 0; i < str.size(); i++) {
485 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
486 hex.push_back(kLookup[str.data()[i] & 0x0F]);
487 }
488 return OK;
489}
490
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700491status_t NormalizeHex(const std::string& in, std::string& out) {
492 std::string tmp;
493 if (HexToStr(in, tmp)) {
494 return -EINVAL;
495 }
496 return StrToHex(tmp, out);
497}
498
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200499status_t GetBlockDevSize(int fd, uint64_t* size) {
500 if (ioctl(fd, BLKGETSIZE64, size)) {
501 return -errno;
502 }
503
504 return OK;
505}
506
507status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
508 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
509 status_t res = OK;
510
511 if (fd < 0) {
512 return -errno;
513 }
514
515 res = GetBlockDevSize(fd, size);
516
517 close(fd);
518
519 return res;
520}
521
522status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
523 uint64_t size;
524 status_t res = GetBlockDevSize(path, &size);
525
526 if (res != OK) {
527 return res;
528 }
529
530 *nr_sec = size / 512;
531
532 return OK;
533}
534
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700535uint64_t GetFreeBytes(const std::string& path) {
536 struct statvfs sb;
537 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700538 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700539 } else {
540 return -1;
541 }
542}
543
544// TODO: borrowed from frameworks/native/libs/diskusage/ which should
545// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700546static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700547 int64_t blksize = s->st_blksize;
548 // count actual blocks used instead of nominal file size
549 int64_t size = s->st_blocks * 512;
550
551 if (blksize) {
552 /* round up to filesystem block size */
553 size = (size + blksize - 1) & (~(blksize - 1));
554 }
555
556 return size;
557}
558
559// TODO: borrowed from frameworks/native/libs/diskusage/ which should
560// eventually be migrated into system/
561int64_t calculate_dir_size(int dfd) {
562 int64_t size = 0;
563 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700564 DIR* d;
565 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700566
567 d = fdopendir(dfd);
568 if (d == NULL) {
569 close(dfd);
570 return 0;
571 }
572
573 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700574 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700575 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
576 size += stat_size(&s);
577 }
578 if (de->d_type == DT_DIR) {
579 int subfd;
580
581 /* always skip "." and ".." */
582 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700583 if (name[1] == 0) continue;
584 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700585 }
586
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600587 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700588 if (subfd >= 0) {
589 size += calculate_dir_size(subfd);
590 }
591 }
592 }
593 closedir(d);
594 return size;
595}
596
597uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600598 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700599 if (dirfd < 0) {
600 PLOG(WARNING) << "Failed to open " << path;
601 return -1;
602 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700603 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700604 }
605}
606
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700607bool IsFilesystemSupported(const std::string& fsType) {
608 std::string supported;
609 if (!ReadFileToString(kProcFilesystems, &supported)) {
610 PLOG(ERROR) << "Failed to read supported filesystems";
611 return false;
612 }
613 return supported.find(fsType + "\n") != std::string::npos;
614}
615
616status_t WipeBlockDevice(const std::string& path) {
617 status_t res = -1;
618 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200619 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700620
621 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
622 if (fd == -1) {
623 PLOG(ERROR) << "Failed to open " << path;
624 goto done;
625 }
626
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200627 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700628 PLOG(ERROR) << "Failed to determine size of " << path;
629 goto done;
630 }
631
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700632 LOG(INFO) << "About to discard " << range[1] << " on " << path;
633 if (ioctl(fd, BLKDISCARD, &range) == 0) {
634 LOG(INFO) << "Discard success on " << path;
635 res = 0;
636 } else {
637 PLOG(ERROR) << "Discard failure on " << path;
638 }
639
640done:
641 close(fd);
642 return res;
643}
644
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800645static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700646 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800647 return false;
648 } else {
649 return true;
650 }
651}
652
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700653std::string BuildKeyPath(const std::string& partGuid) {
654 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
655}
656
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600657std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700658 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600659}
660
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800661std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700662 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700663}
664
665std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700666 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700667}
668
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600669std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700670 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600671}
672
Jeff Sharkey47695b22016-02-01 17:02:29 -0700673std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700674 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700675}
676
677std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700678 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800679}
680
Calin Juravle79f55a42016-02-17 20:14:46 +0000681// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
682std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700683 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000684}
685
Andreas Huber71cd43f2018-01-22 11:25:29 -0800686std::string BuildDataVendorCePath(userid_t userId) {
687 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
688}
689
690std::string BuildDataVendorDePath(userid_t userId) {
691 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
692}
693
Paul Crowley3b71fc52017-10-09 10:55:21 -0700694std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800695 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700696 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800697 return "/data";
698 } else {
699 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700700 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800701 }
702}
703
Paul Crowley3b71fc52017-10-09 10:55:21 -0700704std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700705 // TODO: unify with installd path generation logic
706 std::string data(BuildDataPath(volumeUuid));
707 return StringPrintf("%s/media/%u", data.c_str(), userId);
708}
709
Paul Crowley3b71fc52017-10-09 10:55:21 -0700710std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800711 // TODO: unify with installd path generation logic
712 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700713 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800714 std::string legacy = StringPrintf("%s/data", data.c_str());
715 struct stat sb;
716 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
717 /* /data/data is dir, return /data/data for legacy system */
718 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800719 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800720 }
cjbaoeb501142017-04-12 00:09:00 +0800721 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800722}
723
Paul Crowley3b71fc52017-10-09 10:55:21 -0700724std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800725 // TODO: unify with installd path generation logic
726 std::string data(BuildDataPath(volumeUuid));
727 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
728}
729
Jeff Sharkey66270a22015-06-24 11:49:24 -0700730dev_t GetDevice(const std::string& path) {
731 struct stat sb;
732 if (stat(path.c_str(), &sb)) {
733 PLOG(WARNING) << "Failed to stat " << path;
734 return 0;
735 } else {
736 return sb.st_dev;
737 }
738}
739
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600740status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700741 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600742
Tom Cherryd6127ef2017-06-15 17:13:56 -0700743 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600744
Tom Cherryd6127ef2017-06-15 17:13:56 -0700745 android::base::SetProperty(kRestoreconString, "");
746 android::base::SetProperty(kRestoreconString, path);
747
748 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600749
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700750 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600751 return OK;
752}
753
Jeff Sharkey3472e522017-10-06 18:02:53 -0600754bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
755 // Shamelessly borrowed from android::base::Readlink()
756 result->clear();
757
758 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
759 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
760 // waste memory to just start there. We add 1 so that we can recognize
761 // whether it actually fit (rather than being truncated to 4095).
762 std::vector<char> buf(4095 + 1);
763 while (true) {
764 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
765 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700766 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600767 // It fit! (If size == buf.size(), it may have been truncated.)
768 if (static_cast<size_t>(size) < buf.size()) {
769 result->assign(&buf[0], size);
770 return true;
771 }
772 // Double our buffer and try again.
773 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900774 }
775}
776
Yu Ning942d4e82016-01-08 17:36:47 +0800777bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700778 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800779}
780
Sudheer Shanka295fb242019-01-16 23:04:07 -0800781static status_t findMountPointsWithPrefix(const std::string& prefix,
782 std::list<std::string>& mountPoints) {
783 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
784 // when the prefix is /foo/bar
785 std::string prefixWithSlash(prefix);
786 if (prefix.back() != '/') {
787 android::base::StringAppendF(&prefixWithSlash, "/");
788 }
789
790 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
791 if (!mnts) {
792 PLOG(ERROR) << "Unable to open /proc/mounts";
793 return -errno;
794 }
795
796 // Some volumes can be stacked on each other, so force unmount in
797 // reverse order to give us the best chance of success.
798 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
799 while ((mnt = getmntent(mnts.get())) != nullptr) {
800 auto mountPoint = std::string(mnt->mnt_dir) + "/";
801 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
802 mountPoints.push_front(mountPoint);
803 }
804 }
805 return OK;
806}
807
808// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
809status_t UnmountTreeWithPrefix(const std::string& prefix) {
810 std::list<std::string> toUnmount;
811 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
812 if (result < 0) {
813 return result;
814 }
815 for (const auto& path : toUnmount) {
816 if (umount2(path.c_str(), MNT_DETACH)) {
817 PLOG(ERROR) << "Failed to unmount " << path;
818 result = -errno;
819 }
820 }
821 return result;
822}
823
824status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800825 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
826 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800827 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700828 return -errno;
829 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700830 return OK;
831}
832
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700833static status_t delete_dir_contents(DIR* dir) {
834 // Shamelessly borrowed from android::installd
835 int dfd = dirfd(dir);
836 if (dfd < 0) {
837 return -errno;
838 }
839
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800840 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700841 struct dirent* de;
842 while ((de = readdir(dir))) {
843 const char* name = de->d_name;
844 if (de->d_type == DT_DIR) {
845 /* always skip "." and ".." */
846 if (name[0] == '.') {
847 if (name[1] == 0) continue;
848 if ((name[1] == '.') && (name[2] == 0)) continue;
849 }
850
851 android::base::unique_fd subfd(
852 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
853 if (subfd.get() == -1) {
854 PLOG(ERROR) << "Couldn't openat " << name;
855 result = -errno;
856 continue;
857 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800858 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
859 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700860 if (!subdirp) {
861 PLOG(ERROR) << "Couldn't fdopendir " << name;
862 result = -errno;
863 continue;
864 }
865 result = delete_dir_contents(subdirp.get());
866 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
867 PLOG(ERROR) << "Couldn't unlinkat " << name;
868 result = -errno;
869 }
870 } else {
871 if (unlinkat(dfd, name, 0) < 0) {
872 PLOG(ERROR) << "Couldn't unlinkat " << name;
873 result = -errno;
874 }
875 }
876 }
877 return result;
878}
879
880status_t DeleteDirContentsAndDir(const std::string& pathname) {
881 // Shamelessly borrowed from android::installd
882 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
883 if (!dirp) {
884 if (errno == ENOENT) {
885 return OK;
886 }
887 PLOG(ERROR) << "Failed to opendir " << pathname;
888 return -errno;
889 }
890 status_t res = delete_dir_contents(dirp.get());
891 if (res < 0) {
892 return res;
893 }
894 dirp.reset(nullptr);
895 if (rmdir(pathname.c_str()) != 0) {
896 PLOG(ERROR) << "rmdir failed on " << pathname;
897 return -errno;
898 }
899 LOG(VERBOSE) << "Success: rmdir on " << pathname;
900 return OK;
901}
902
Paul Crowley298fa322018-10-30 15:59:24 -0700903// TODO(118708649): fix duplication with init/util.h
904status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
905 android::base::Timer t;
906 while (t.duration() < timeout) {
907 struct stat sb;
908 if (stat(filename, &sb) != -1) {
909 LOG(INFO) << "wait for '" << filename << "' took " << t;
910 return 0;
911 }
912 std::this_thread::sleep_for(10ms);
913 }
914 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
915 return -1;
916}
917
Paul Crowley621d9b92018-12-07 15:36:09 -0800918bool FsyncDirectory(const std::string& dirname) {
919 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
920 if (fd == -1) {
921 PLOG(ERROR) << "Failed to open " << dirname;
922 return false;
923 }
924 if (fsync(fd) == -1) {
925 if (errno == EROFS || errno == EINVAL) {
926 PLOG(WARNING) << "Skip fsync " << dirname
927 << " on a file system does not support synchronization";
928 } else {
929 PLOG(ERROR) << "Failed to fsync " << dirname;
930 return false;
931 }
932 }
933 return true;
934}
935
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800936} // namespace vold
937} // namespace android