blob: 0a16fc13bb726612d775d60ee35ed6748f87516c [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
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000225status_t CreateDir(const std::string& dir, mode_t mode) {
226 struct stat sb;
227 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
228 if (S_ISDIR(sb.st_mode)) {
229 return OK;
230 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
231 PLOG(ERROR) << "Failed to unlink " << dir;
232 return -errno;
233 }
234 } else if (errno != ENOENT) {
235 PLOG(ERROR) << "Failed to stat " << dir;
236 return -errno;
237 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800238 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000239 PLOG(ERROR) << "Failed to mkdir " << dir;
240 return -errno;
241 }
242 return OK;
243}
244
Jeff Sharkey3472e522017-10-06 18:02:53 -0600245bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
246 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800247 size_t start = 0;
248 while (true) {
249 start = raw.find(qual, start);
250 if (start == std::string::npos) return false;
251 if (start == 0 || raw[start - 1] == ' ') {
252 break;
253 }
254 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600255 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600256 start += qual.length();
257
258 auto end = raw.find("\"", start);
259 if (end == std::string::npos) return false;
260
261 *value = raw.substr(start, end - start);
262 return true;
263}
264
Paul Crowley14c8c072018-09-18 13:30:21 -0700265static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
266 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600267 fsType->clear();
268 fsUuid->clear();
269 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700270
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700271 std::vector<std::string> cmd;
272 cmd.push_back(kBlkidPath);
273 cmd.push_back("-c");
274 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700275 cmd.push_back("-s");
276 cmd.push_back("TYPE");
277 cmd.push_back("-s");
278 cmd.push_back("UUID");
279 cmd.push_back("-s");
280 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700281 cmd.push_back(path);
282
283 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800284 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700285 if (res != OK) {
286 LOG(WARNING) << "blkid failed to identify " << path;
287 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700288 }
289
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700290 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700291 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600292 FindValue(line, "TYPE", fsType);
293 FindValue(line, "UUID", fsUuid);
294 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700295 }
296
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700297 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700298}
299
Paul Crowley14c8c072018-09-18 13:30:21 -0700300status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
301 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700302 return readMetadata(path, fsType, fsUuid, fsLabel, false);
303}
304
Paul Crowley14c8c072018-09-18 13:30:21 -0700305status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
306 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700307 return readMetadata(path, fsType, fsUuid, fsLabel, true);
308}
309
Paul Crowleyde2d6202018-11-30 11:43:47 -0800310static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
311 std::vector<const char*> argv;
312 argv.reserve(args.size() + 1);
313 for (const auto& arg : args) {
314 if (argv.empty()) {
315 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700316 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800317 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700318 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800319 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700320 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800321 argv.emplace_back(nullptr);
322 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700323}
324
Paul Crowleyde2d6202018-11-30 11:43:47 -0800325static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
326 android::base::unique_fd ufd) {
327 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700328 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800329 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700330 return -errno;
331 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800332 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700333 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800334 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700335 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800336 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700337 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800338 return OK;
339}
340
341status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
342 security_context_t context) {
343 auto argv = ConvertToArgv(args);
344
Paul Crowleye6d76632018-11-30 11:43:47 -0800345 android::base::unique_fd pipe_read, pipe_write;
346 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
347 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800348 return -errno;
349 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800350
351 pid_t pid = fork();
352 if (pid == 0) {
353 if (context) {
354 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800355 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800356 abort();
357 }
358 }
359 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800360 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
361 PLOG(ERROR) << "dup2 in ForkExecvp";
362 _exit(EXIT_FAILURE);
363 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800364 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800365 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800366 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800367 _exit(EXIT_FAILURE);
368 }
369 if (pid == -1) {
370 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700371 return -errno;
372 }
373
Paul Crowleyde2d6202018-11-30 11:43:47 -0800374 pipe_write.reset();
375 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
376 if (st != 0) return st;
377
378 int status;
379 if (waitpid(pid, &status, 0) == -1) {
380 PLOG(ERROR) << "waitpid in ForkExecvp";
381 return -errno;
382 }
383 if (!WIFEXITED(status)) {
384 LOG(ERROR) << "Process did not exit normally, status: " << status;
385 return -ECHILD;
386 }
387 if (WEXITSTATUS(status)) {
388 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
389 return WEXITSTATUS(status);
390 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700391 return OK;
392}
393
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700394pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800395 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700396
397 pid_t pid = fork();
398 if (pid == 0) {
399 close(STDIN_FILENO);
400 close(STDOUT_FILENO);
401 close(STDERR_FILENO);
402
Paul Crowleyde2d6202018-11-30 11:43:47 -0800403 execvp(argv[0], const_cast<char**>(argv.data()));
404 PLOG(ERROR) << "exec in ForkExecvpAsync";
405 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700406 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700407 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800408 PLOG(ERROR) << "fork in ForkExecvpAsync";
409 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700410 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700411 return pid;
412}
413
Jeff Sharkey9c484982015-03-31 10:35:33 -0700414status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100415 out.resize(bytes);
416 return ReadRandomBytes(bytes, &out[0]);
417}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700418
Pavel Grafove2e2d302017-08-01 17:15:53 +0100419status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700420 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
421 if (fd == -1) {
422 return -errno;
423 }
424
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800425 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100426 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700427 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100428 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700429 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700430 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700431
432 if (bytes == 0) {
433 return OK;
434 } else {
435 return -EIO;
436 }
437}
438
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600439status_t GenerateRandomUuid(std::string& out) {
440 status_t res = ReadRandomBytes(16, out);
441 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700442 out[6] &= 0x0f; /* clear version */
443 out[6] |= 0x40; /* set to version 4 */
444 out[8] &= 0x3f; /* clear variant */
445 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600446 }
447 return res;
448}
449
Jeff Sharkey9c484982015-03-31 10:35:33 -0700450status_t HexToStr(const std::string& hex, std::string& str) {
451 str.clear();
452 bool even = true;
453 char cur = 0;
454 for (size_t i = 0; i < hex.size(); i++) {
455 int val = 0;
456 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700457 // clang-format off
458 case ' ': case '-': case ':': continue;
459 case 'f': case 'F': val = 15; break;
460 case 'e': case 'E': val = 14; break;
461 case 'd': case 'D': val = 13; break;
462 case 'c': case 'C': val = 12; break;
463 case 'b': case 'B': val = 11; break;
464 case 'a': case 'A': val = 10; break;
465 case '9': val = 9; break;
466 case '8': val = 8; break;
467 case '7': val = 7; break;
468 case '6': val = 6; break;
469 case '5': val = 5; break;
470 case '4': val = 4; break;
471 case '3': val = 3; break;
472 case '2': val = 2; break;
473 case '1': val = 1; break;
474 case '0': val = 0; break;
475 default: return -EINVAL;
476 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700477 }
478
479 if (even) {
480 cur = val << 4;
481 } else {
482 cur += val;
483 str.push_back(cur);
484 cur = 0;
485 }
486 even = !even;
487 }
488 return even ? OK : -EINVAL;
489}
490
491static const char* kLookup = "0123456789abcdef";
492
493status_t StrToHex(const std::string& str, std::string& hex) {
494 hex.clear();
495 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700496 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700497 hex.push_back(kLookup[str[i] & 0x0F]);
498 }
499 return OK;
500}
501
Pavel Grafove2e2d302017-08-01 17:15:53 +0100502status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
503 hex.clear();
504 for (size_t i = 0; i < str.size(); i++) {
505 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
506 hex.push_back(kLookup[str.data()[i] & 0x0F]);
507 }
508 return OK;
509}
510
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700511status_t NormalizeHex(const std::string& in, std::string& out) {
512 std::string tmp;
513 if (HexToStr(in, tmp)) {
514 return -EINVAL;
515 }
516 return StrToHex(tmp, out);
517}
518
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200519status_t GetBlockDevSize(int fd, uint64_t* size) {
520 if (ioctl(fd, BLKGETSIZE64, size)) {
521 return -errno;
522 }
523
524 return OK;
525}
526
527status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
528 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
529 status_t res = OK;
530
531 if (fd < 0) {
532 return -errno;
533 }
534
535 res = GetBlockDevSize(fd, size);
536
537 close(fd);
538
539 return res;
540}
541
542status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
543 uint64_t size;
544 status_t res = GetBlockDevSize(path, &size);
545
546 if (res != OK) {
547 return res;
548 }
549
550 *nr_sec = size / 512;
551
552 return OK;
553}
554
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700555uint64_t GetFreeBytes(const std::string& path) {
556 struct statvfs sb;
557 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700558 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700559 } else {
560 return -1;
561 }
562}
563
564// TODO: borrowed from frameworks/native/libs/diskusage/ which should
565// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700566static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700567 int64_t blksize = s->st_blksize;
568 // count actual blocks used instead of nominal file size
569 int64_t size = s->st_blocks * 512;
570
571 if (blksize) {
572 /* round up to filesystem block size */
573 size = (size + blksize - 1) & (~(blksize - 1));
574 }
575
576 return size;
577}
578
579// TODO: borrowed from frameworks/native/libs/diskusage/ which should
580// eventually be migrated into system/
581int64_t calculate_dir_size(int dfd) {
582 int64_t size = 0;
583 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700584 DIR* d;
585 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700586
587 d = fdopendir(dfd);
588 if (d == NULL) {
589 close(dfd);
590 return 0;
591 }
592
593 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700594 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700595 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
596 size += stat_size(&s);
597 }
598 if (de->d_type == DT_DIR) {
599 int subfd;
600
601 /* always skip "." and ".." */
602 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700603 if (name[1] == 0) continue;
604 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700605 }
606
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600607 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700608 if (subfd >= 0) {
609 size += calculate_dir_size(subfd);
610 }
611 }
612 }
613 closedir(d);
614 return size;
615}
616
617uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600618 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700619 if (dirfd < 0) {
620 PLOG(WARNING) << "Failed to open " << path;
621 return -1;
622 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700623 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700624 }
625}
626
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700627bool IsFilesystemSupported(const std::string& fsType) {
628 std::string supported;
629 if (!ReadFileToString(kProcFilesystems, &supported)) {
630 PLOG(ERROR) << "Failed to read supported filesystems";
631 return false;
632 }
633 return supported.find(fsType + "\n") != std::string::npos;
634}
635
636status_t WipeBlockDevice(const std::string& path) {
637 status_t res = -1;
638 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200639 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700640
641 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
642 if (fd == -1) {
643 PLOG(ERROR) << "Failed to open " << path;
644 goto done;
645 }
646
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200647 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700648 PLOG(ERROR) << "Failed to determine size of " << path;
649 goto done;
650 }
651
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700652 LOG(INFO) << "About to discard " << range[1] << " on " << path;
653 if (ioctl(fd, BLKDISCARD, &range) == 0) {
654 LOG(INFO) << "Discard success on " << path;
655 res = 0;
656 } else {
657 PLOG(ERROR) << "Discard failure on " << path;
658 }
659
660done:
661 close(fd);
662 return res;
663}
664
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800665static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700666 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800667 return false;
668 } else {
669 return true;
670 }
671}
672
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700673std::string BuildKeyPath(const std::string& partGuid) {
674 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
675}
676
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600677std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700678 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600679}
680
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800681std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700682 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700683}
684
685std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700686 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700687}
688
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600689std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700690 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600691}
692
Jeff Sharkey47695b22016-02-01 17:02:29 -0700693std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700694 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700695}
696
697std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700698 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800699}
700
Calin Juravle79f55a42016-02-17 20:14:46 +0000701// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
702std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700703 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000704}
705
Andreas Huber71cd43f2018-01-22 11:25:29 -0800706std::string BuildDataVendorCePath(userid_t userId) {
707 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
708}
709
710std::string BuildDataVendorDePath(userid_t userId) {
711 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
712}
713
Paul Crowley3b71fc52017-10-09 10:55:21 -0700714std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800715 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700716 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800717 return "/data";
718 } else {
719 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700720 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800721 }
722}
723
Paul Crowley3b71fc52017-10-09 10:55:21 -0700724std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700725 // TODO: unify with installd path generation logic
726 std::string data(BuildDataPath(volumeUuid));
727 return StringPrintf("%s/media/%u", data.c_str(), userId);
728}
729
Paul Crowley3b71fc52017-10-09 10:55:21 -0700730std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800731 // TODO: unify with installd path generation logic
732 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700733 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800734 std::string legacy = StringPrintf("%s/data", data.c_str());
735 struct stat sb;
736 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
737 /* /data/data is dir, return /data/data for legacy system */
738 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800739 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800740 }
cjbaoeb501142017-04-12 00:09:00 +0800741 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800742}
743
Paul Crowley3b71fc52017-10-09 10:55:21 -0700744std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800745 // TODO: unify with installd path generation logic
746 std::string data(BuildDataPath(volumeUuid));
747 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
748}
749
Jeff Sharkey66270a22015-06-24 11:49:24 -0700750dev_t GetDevice(const std::string& path) {
751 struct stat sb;
752 if (stat(path.c_str(), &sb)) {
753 PLOG(WARNING) << "Failed to stat " << path;
754 return 0;
755 } else {
756 return sb.st_dev;
757 }
758}
759
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600760status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700761 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600762
Tom Cherryd6127ef2017-06-15 17:13:56 -0700763 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600764
Tom Cherryd6127ef2017-06-15 17:13:56 -0700765 android::base::SetProperty(kRestoreconString, "");
766 android::base::SetProperty(kRestoreconString, path);
767
768 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600769
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700770 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600771 return OK;
772}
773
Jeff Sharkey3472e522017-10-06 18:02:53 -0600774bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
775 // Shamelessly borrowed from android::base::Readlink()
776 result->clear();
777
778 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
779 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
780 // waste memory to just start there. We add 1 so that we can recognize
781 // whether it actually fit (rather than being truncated to 4095).
782 std::vector<char> buf(4095 + 1);
783 while (true) {
784 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
785 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700786 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600787 // It fit! (If size == buf.size(), it may have been truncated.)
788 if (static_cast<size_t>(size) < buf.size()) {
789 result->assign(&buf[0], size);
790 return true;
791 }
792 // Double our buffer and try again.
793 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900794 }
795}
796
Yu Ning942d4e82016-01-08 17:36:47 +0800797bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700798 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800799}
800
Sudheer Shanka295fb242019-01-16 23:04:07 -0800801static status_t findMountPointsWithPrefix(const std::string& prefix,
802 std::list<std::string>& mountPoints) {
803 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
804 // when the prefix is /foo/bar
805 std::string prefixWithSlash(prefix);
806 if (prefix.back() != '/') {
807 android::base::StringAppendF(&prefixWithSlash, "/");
808 }
809
810 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
811 if (!mnts) {
812 PLOG(ERROR) << "Unable to open /proc/mounts";
813 return -errno;
814 }
815
816 // Some volumes can be stacked on each other, so force unmount in
817 // reverse order to give us the best chance of success.
818 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
819 while ((mnt = getmntent(mnts.get())) != nullptr) {
820 auto mountPoint = std::string(mnt->mnt_dir) + "/";
821 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
822 mountPoints.push_front(mountPoint);
823 }
824 }
825 return OK;
826}
827
828// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
829status_t UnmountTreeWithPrefix(const std::string& prefix) {
830 std::list<std::string> toUnmount;
831 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
832 if (result < 0) {
833 return result;
834 }
835 for (const auto& path : toUnmount) {
836 if (umount2(path.c_str(), MNT_DETACH)) {
837 PLOG(ERROR) << "Failed to unmount " << path;
838 result = -errno;
839 }
840 }
841 return result;
842}
843
844status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800845 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
846 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800847 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700848 return -errno;
849 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700850 return OK;
851}
852
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700853static status_t delete_dir_contents(DIR* dir) {
854 // Shamelessly borrowed from android::installd
855 int dfd = dirfd(dir);
856 if (dfd < 0) {
857 return -errno;
858 }
859
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800860 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700861 struct dirent* de;
862 while ((de = readdir(dir))) {
863 const char* name = de->d_name;
864 if (de->d_type == DT_DIR) {
865 /* always skip "." and ".." */
866 if (name[0] == '.') {
867 if (name[1] == 0) continue;
868 if ((name[1] == '.') && (name[2] == 0)) continue;
869 }
870
871 android::base::unique_fd subfd(
872 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
873 if (subfd.get() == -1) {
874 PLOG(ERROR) << "Couldn't openat " << name;
875 result = -errno;
876 continue;
877 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800878 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
879 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700880 if (!subdirp) {
881 PLOG(ERROR) << "Couldn't fdopendir " << name;
882 result = -errno;
883 continue;
884 }
885 result = delete_dir_contents(subdirp.get());
886 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
887 PLOG(ERROR) << "Couldn't unlinkat " << name;
888 result = -errno;
889 }
890 } else {
891 if (unlinkat(dfd, name, 0) < 0) {
892 PLOG(ERROR) << "Couldn't unlinkat " << name;
893 result = -errno;
894 }
895 }
896 }
897 return result;
898}
899
900status_t DeleteDirContentsAndDir(const std::string& pathname) {
901 // Shamelessly borrowed from android::installd
902 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
903 if (!dirp) {
904 if (errno == ENOENT) {
905 return OK;
906 }
907 PLOG(ERROR) << "Failed to opendir " << pathname;
908 return -errno;
909 }
910 status_t res = delete_dir_contents(dirp.get());
911 if (res < 0) {
912 return res;
913 }
914 dirp.reset(nullptr);
915 if (rmdir(pathname.c_str()) != 0) {
916 PLOG(ERROR) << "rmdir failed on " << pathname;
917 return -errno;
918 }
919 LOG(VERBOSE) << "Success: rmdir on " << pathname;
920 return OK;
921}
922
Paul Crowley298fa322018-10-30 15:59:24 -0700923// TODO(118708649): fix duplication with init/util.h
924status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
925 android::base::Timer t;
926 while (t.duration() < timeout) {
927 struct stat sb;
928 if (stat(filename, &sb) != -1) {
929 LOG(INFO) << "wait for '" << filename << "' took " << t;
930 return 0;
931 }
932 std::this_thread::sleep_for(10ms);
933 }
934 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
935 return -1;
936}
937
Paul Crowley621d9b92018-12-07 15:36:09 -0800938bool FsyncDirectory(const std::string& dirname) {
939 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
940 if (fd == -1) {
941 PLOG(ERROR) << "Failed to open " << dirname;
942 return false;
943 }
944 if (fsync(fd) == -1) {
945 if (errno == EROFS || errno == EINVAL) {
946 PLOG(WARNING) << "Skip fsync " << dirname
947 << " on a file system does not support synchronization";
948 } else {
949 PLOG(ERROR) << "Failed to fsync " << dirname;
950 return false;
951 }
952 }
953 return true;
954}
955
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800956} // namespace vold
957} // namespace android