blob: 1616d80f6297221ca4e7b1dbab45b6903e287295 [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>
Tommy Chiu0bd2d112019-03-26 17:18:09 +080039#include <unistd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080040#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080041#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070042#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070043#include <sys/sysmacros.h>
44#include <sys/types.h>
45#include <sys/wait.h>
Paul Crowley747b4212019-04-05 04:09:57 -070046#include <unistd.h>
Paul Crowley298fa322018-10-30 15:59:24 -070047
Sudheer Shanka89ddf992018-09-25 14:22:07 -070048#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070049#include <mutex>
Paul Crowley298fa322018-10-30 15:59:24 -070050#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080051
52#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070053#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080054#endif
55
Paul Crowley298fa322018-10-30 15:59:24 -070056using namespace std::chrono_literals;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070057using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070058using android::base::StringPrintf;
59
Jeff Sharkeydeb24052015-03-02 21:01:40 -080060namespace android {
61namespace vold {
62
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070063security_context_t sBlkidContext = nullptr;
64security_context_t sBlkidUntrustedContext = nullptr;
65security_context_t sFsckContext = nullptr;
66security_context_t sFsckUntrustedContext = nullptr;
67
Paul Crowley56292ef2017-10-20 08:07:53 -070068bool sSleepOnUnmount = true;
69
Jeff Sharkey9c484982015-03-31 10:35:33 -070070static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070071static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070072
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070073static const char* kProcFilesystems = "/proc/filesystems";
74
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060075// Lock used to protect process-level SELinux changes from racing with each
76// other between multiple threads.
77static std::mutex kSecurityLock;
78
Jeff Sharkeydeb24052015-03-02 21:01:40 -080079status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060080 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080081 const char* cpath = path.c_str();
82 status_t res = 0;
83
84 char* secontext = nullptr;
85 if (sehandle) {
86 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
87 setfscreatecon(secontext);
88 }
89 }
90
91 mode_t mode = 0660 | S_IFBLK;
92 if (mknod(cpath, mode, dev) < 0) {
93 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070094 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
95 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080096 res = -errno;
97 }
98 }
99
100 if (secontext) {
101 setfscreatecon(nullptr);
102 freecon(secontext);
103 }
104
105 return res;
106}
107
108status_t DestroyDeviceNode(const std::string& path) {
109 const char* cpath = path.c_str();
110 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
111 return -errno;
112 } else {
113 return OK;
114 }
115}
116
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700117status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600118 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700119 const char* cpath = path.c_str();
120
121 char* secontext = nullptr;
122 if (sehandle) {
123 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
124 setfscreatecon(secontext);
125 }
126 }
127
128 int res = fs_prepare_dir(cpath, mode, uid, gid);
129
130 if (secontext) {
131 setfscreatecon(nullptr);
132 freecon(secontext);
133 }
134
135 if (res == 0) {
136 return OK;
137 } else {
138 return -errno;
139 }
140}
141
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800142status_t ForceUnmount(const std::string& path) {
143 const char* cpath = path.c_str();
144 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
145 return OK;
146 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700147 // Apps might still be handling eject request, so wait before
148 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700149 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700150
Jeff Sharkey3472e522017-10-06 18:02:53 -0600151 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700152 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700153 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
154 return OK;
155 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700156
Jeff Sharkey3472e522017-10-06 18:02:53 -0600157 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700158 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800159 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
160 return OK;
161 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700162
Jeff Sharkey3472e522017-10-06 18:02:53 -0600163 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700164 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700165 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
166 return OK;
167 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700168
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800169 return -errno;
170}
171
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700172status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600173 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700174 return OK;
175 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700176 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700177
Jeff Sharkey3472e522017-10-06 18:02:53 -0600178 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700179 return OK;
180 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700181 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700182
Jeff Sharkey3472e522017-10-06 18:02:53 -0600183 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700184 return OK;
185 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700186 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700187
188 // Send SIGKILL a second time to determine if we've
189 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600190 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700191 return OK;
192 }
193 PLOG(ERROR) << "Failed to kill processes using " << path;
194 return -EBUSY;
195}
196
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700197status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800198 if (UnmountTree(target) < 0) {
199 return -errno;
200 }
201 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700202 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
203 return -errno;
204 }
205 return OK;
206}
207
Sudheer Shanka023b5392019-02-06 12:39:19 -0800208status_t Symlink(const std::string& target, const std::string& linkpath) {
209 if (Unlink(linkpath) < 0) {
210 return -errno;
211 }
212 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
213 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
214 return -errno;
215 }
216 return OK;
217}
218
219status_t Unlink(const std::string& linkpath) {
220 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
221 PLOG(ERROR) << "Failed to unlink " << linkpath;
222 return -errno;
223 }
224 return OK;
225}
226
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000227status_t CreateDir(const std::string& dir, mode_t mode) {
228 struct stat sb;
229 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
230 if (S_ISDIR(sb.st_mode)) {
231 return OK;
232 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
233 PLOG(ERROR) << "Failed to unlink " << dir;
234 return -errno;
235 }
236 } else if (errno != ENOENT) {
237 PLOG(ERROR) << "Failed to stat " << dir;
238 return -errno;
239 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800240 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000241 PLOG(ERROR) << "Failed to mkdir " << dir;
242 return -errno;
243 }
244 return OK;
245}
246
Jeff Sharkey3472e522017-10-06 18:02:53 -0600247bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
248 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800249 size_t start = 0;
250 while (true) {
251 start = raw.find(qual, start);
252 if (start == std::string::npos) return false;
253 if (start == 0 || raw[start - 1] == ' ') {
254 break;
255 }
256 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600257 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600258 start += qual.length();
259
260 auto end = raw.find("\"", start);
261 if (end == std::string::npos) return false;
262
263 *value = raw.substr(start, end - start);
264 return true;
265}
266
Paul Crowley14c8c072018-09-18 13:30:21 -0700267static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
268 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600269 fsType->clear();
270 fsUuid->clear();
271 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700272
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700273 std::vector<std::string> cmd;
274 cmd.push_back(kBlkidPath);
275 cmd.push_back("-c");
276 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700277 cmd.push_back("-s");
278 cmd.push_back("TYPE");
279 cmd.push_back("-s");
280 cmd.push_back("UUID");
281 cmd.push_back("-s");
282 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700283 cmd.push_back(path);
284
285 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800286 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700287 if (res != OK) {
288 LOG(WARNING) << "blkid failed to identify " << path;
289 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700290 }
291
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700292 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700293 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600294 FindValue(line, "TYPE", fsType);
295 FindValue(line, "UUID", fsUuid);
296 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700297 }
298
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700299 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700300}
301
Paul Crowley14c8c072018-09-18 13:30:21 -0700302status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
303 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700304 return readMetadata(path, fsType, fsUuid, fsLabel, false);
305}
306
Paul Crowley14c8c072018-09-18 13:30:21 -0700307status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
308 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700309 return readMetadata(path, fsType, fsUuid, fsLabel, true);
310}
311
Paul Crowleyde2d6202018-11-30 11:43:47 -0800312static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
313 std::vector<const char*> argv;
314 argv.reserve(args.size() + 1);
315 for (const auto& arg : args) {
316 if (argv.empty()) {
317 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700318 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800319 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700320 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800321 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700322 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800323 argv.emplace_back(nullptr);
324 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700325}
326
Paul Crowleyde2d6202018-11-30 11:43:47 -0800327static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
328 android::base::unique_fd ufd) {
329 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700330 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800331 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700332 return -errno;
333 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800334 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700335 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800336 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700337 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800338 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700339 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800340 return OK;
341}
342
343status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
344 security_context_t context) {
345 auto argv = ConvertToArgv(args);
346
Paul Crowleye6d76632018-11-30 11:43:47 -0800347 android::base::unique_fd pipe_read, pipe_write;
348 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
349 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800350 return -errno;
351 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800352
353 pid_t pid = fork();
354 if (pid == 0) {
355 if (context) {
356 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800357 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800358 abort();
359 }
360 }
361 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800362 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
363 PLOG(ERROR) << "dup2 in ForkExecvp";
364 _exit(EXIT_FAILURE);
365 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800366 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800367 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800368 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800369 _exit(EXIT_FAILURE);
370 }
371 if (pid == -1) {
372 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700373 return -errno;
374 }
375
Paul Crowleyde2d6202018-11-30 11:43:47 -0800376 pipe_write.reset();
377 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
378 if (st != 0) return st;
379
380 int status;
381 if (waitpid(pid, &status, 0) == -1) {
382 PLOG(ERROR) << "waitpid in ForkExecvp";
383 return -errno;
384 }
385 if (!WIFEXITED(status)) {
386 LOG(ERROR) << "Process did not exit normally, status: " << status;
387 return -ECHILD;
388 }
389 if (WEXITSTATUS(status)) {
390 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
391 return WEXITSTATUS(status);
392 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700393 return OK;
394}
395
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700396pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800397 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700398
399 pid_t pid = fork();
400 if (pid == 0) {
401 close(STDIN_FILENO);
402 close(STDOUT_FILENO);
403 close(STDERR_FILENO);
404
Paul Crowleyde2d6202018-11-30 11:43:47 -0800405 execvp(argv[0], const_cast<char**>(argv.data()));
406 PLOG(ERROR) << "exec in ForkExecvpAsync";
407 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700408 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700409 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800410 PLOG(ERROR) << "fork in ForkExecvpAsync";
411 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700412 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700413 return pid;
414}
415
Jeff Sharkey9c484982015-03-31 10:35:33 -0700416status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100417 out.resize(bytes);
418 return ReadRandomBytes(bytes, &out[0]);
419}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700420
Pavel Grafove2e2d302017-08-01 17:15:53 +0100421status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700422 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
423 if (fd == -1) {
424 return -errno;
425 }
426
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800427 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100428 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700429 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100430 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700431 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700432 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700433
434 if (bytes == 0) {
435 return OK;
436 } else {
437 return -EIO;
438 }
439}
440
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600441status_t GenerateRandomUuid(std::string& out) {
442 status_t res = ReadRandomBytes(16, out);
443 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700444 out[6] &= 0x0f; /* clear version */
445 out[6] |= 0x40; /* set to version 4 */
446 out[8] &= 0x3f; /* clear variant */
447 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600448 }
449 return res;
450}
451
Jeff Sharkey9c484982015-03-31 10:35:33 -0700452status_t HexToStr(const std::string& hex, std::string& str) {
453 str.clear();
454 bool even = true;
455 char cur = 0;
456 for (size_t i = 0; i < hex.size(); i++) {
457 int val = 0;
458 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700459 // clang-format off
460 case ' ': case '-': case ':': continue;
461 case 'f': case 'F': val = 15; break;
462 case 'e': case 'E': val = 14; break;
463 case 'd': case 'D': val = 13; break;
464 case 'c': case 'C': val = 12; break;
465 case 'b': case 'B': val = 11; break;
466 case 'a': case 'A': val = 10; break;
467 case '9': val = 9; break;
468 case '8': val = 8; break;
469 case '7': val = 7; break;
470 case '6': val = 6; break;
471 case '5': val = 5; break;
472 case '4': val = 4; break;
473 case '3': val = 3; break;
474 case '2': val = 2; break;
475 case '1': val = 1; break;
476 case '0': val = 0; break;
477 default: return -EINVAL;
478 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700479 }
480
481 if (even) {
482 cur = val << 4;
483 } else {
484 cur += val;
485 str.push_back(cur);
486 cur = 0;
487 }
488 even = !even;
489 }
490 return even ? OK : -EINVAL;
491}
492
493static const char* kLookup = "0123456789abcdef";
494
495status_t StrToHex(const std::string& str, std::string& hex) {
496 hex.clear();
497 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700498 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700499 hex.push_back(kLookup[str[i] & 0x0F]);
500 }
501 return OK;
502}
503
Pavel Grafove2e2d302017-08-01 17:15:53 +0100504status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
505 hex.clear();
506 for (size_t i = 0; i < str.size(); i++) {
507 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
508 hex.push_back(kLookup[str.data()[i] & 0x0F]);
509 }
510 return OK;
511}
512
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700513status_t NormalizeHex(const std::string& in, std::string& out) {
514 std::string tmp;
515 if (HexToStr(in, tmp)) {
516 return -EINVAL;
517 }
518 return StrToHex(tmp, out);
519}
520
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200521status_t GetBlockDevSize(int fd, uint64_t* size) {
522 if (ioctl(fd, BLKGETSIZE64, size)) {
523 return -errno;
524 }
525
526 return OK;
527}
528
529status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
530 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
531 status_t res = OK;
532
533 if (fd < 0) {
534 return -errno;
535 }
536
537 res = GetBlockDevSize(fd, size);
538
539 close(fd);
540
541 return res;
542}
543
544status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
545 uint64_t size;
546 status_t res = GetBlockDevSize(path, &size);
547
548 if (res != OK) {
549 return res;
550 }
551
552 *nr_sec = size / 512;
553
554 return OK;
555}
556
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700557uint64_t GetFreeBytes(const std::string& path) {
558 struct statvfs sb;
559 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700560 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700561 } else {
562 return -1;
563 }
564}
565
566// TODO: borrowed from frameworks/native/libs/diskusage/ which should
567// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700568static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700569 int64_t blksize = s->st_blksize;
570 // count actual blocks used instead of nominal file size
571 int64_t size = s->st_blocks * 512;
572
573 if (blksize) {
574 /* round up to filesystem block size */
575 size = (size + blksize - 1) & (~(blksize - 1));
576 }
577
578 return size;
579}
580
581// TODO: borrowed from frameworks/native/libs/diskusage/ which should
582// eventually be migrated into system/
583int64_t calculate_dir_size(int dfd) {
584 int64_t size = 0;
585 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700586 DIR* d;
587 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700588
589 d = fdopendir(dfd);
590 if (d == NULL) {
591 close(dfd);
592 return 0;
593 }
594
595 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700596 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700597 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
598 size += stat_size(&s);
599 }
600 if (de->d_type == DT_DIR) {
601 int subfd;
602
603 /* always skip "." and ".." */
604 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700605 if (name[1] == 0) continue;
606 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700607 }
608
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600609 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700610 if (subfd >= 0) {
611 size += calculate_dir_size(subfd);
612 }
613 }
614 }
615 closedir(d);
616 return size;
617}
618
619uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600620 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700621 if (dirfd < 0) {
622 PLOG(WARNING) << "Failed to open " << path;
623 return -1;
624 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700625 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700626 }
627}
628
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700629bool IsFilesystemSupported(const std::string& fsType) {
630 std::string supported;
631 if (!ReadFileToString(kProcFilesystems, &supported)) {
632 PLOG(ERROR) << "Failed to read supported filesystems";
633 return false;
634 }
635 return supported.find(fsType + "\n") != std::string::npos;
636}
637
638status_t WipeBlockDevice(const std::string& path) {
639 status_t res = -1;
640 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200641 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700642
643 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
644 if (fd == -1) {
645 PLOG(ERROR) << "Failed to open " << path;
646 goto done;
647 }
648
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200649 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700650 PLOG(ERROR) << "Failed to determine size of " << path;
651 goto done;
652 }
653
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700654 LOG(INFO) << "About to discard " << range[1] << " on " << path;
655 if (ioctl(fd, BLKDISCARD, &range) == 0) {
656 LOG(INFO) << "Discard success on " << path;
657 res = 0;
658 } else {
659 PLOG(ERROR) << "Discard failure on " << path;
660 }
661
662done:
663 close(fd);
664 return res;
665}
666
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800667static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700668 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800669 return false;
670 } else {
671 return true;
672 }
673}
674
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700675std::string BuildKeyPath(const std::string& partGuid) {
676 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
677}
678
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600679std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700680 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600681}
682
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800683std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700684 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700685}
686
687std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700688 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700689}
690
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600691std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700692 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600693}
694
Jeff Sharkey47695b22016-02-01 17:02:29 -0700695std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700696 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700697}
698
699std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700700 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800701}
702
Calin Juravle79f55a42016-02-17 20:14:46 +0000703// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
704std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700705 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000706}
707
Andreas Huber71cd43f2018-01-22 11:25:29 -0800708std::string BuildDataVendorCePath(userid_t userId) {
709 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
710}
711
712std::string BuildDataVendorDePath(userid_t userId) {
713 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
714}
715
Paul Crowley3b71fc52017-10-09 10:55:21 -0700716std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800717 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700718 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800719 return "/data";
720 } else {
721 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700722 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800723 }
724}
725
Paul Crowley3b71fc52017-10-09 10:55:21 -0700726std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700727 // TODO: unify with installd path generation logic
728 std::string data(BuildDataPath(volumeUuid));
729 return StringPrintf("%s/media/%u", data.c_str(), userId);
730}
731
Paul Crowley3b71fc52017-10-09 10:55:21 -0700732std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800733 // TODO: unify with installd path generation logic
734 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700735 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800736 std::string legacy = StringPrintf("%s/data", data.c_str());
737 struct stat sb;
738 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
739 /* /data/data is dir, return /data/data for legacy system */
740 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800741 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800742 }
cjbaoeb501142017-04-12 00:09:00 +0800743 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800744}
745
Paul Crowley3b71fc52017-10-09 10:55:21 -0700746std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800747 // TODO: unify with installd path generation logic
748 std::string data(BuildDataPath(volumeUuid));
749 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
750}
751
Jeff Sharkey66270a22015-06-24 11:49:24 -0700752dev_t GetDevice(const std::string& path) {
753 struct stat sb;
754 if (stat(path.c_str(), &sb)) {
755 PLOG(WARNING) << "Failed to stat " << path;
756 return 0;
757 } else {
758 return sb.st_dev;
759 }
760}
761
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600762status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700763 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600764
Tom Cherryd6127ef2017-06-15 17:13:56 -0700765 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600766
Tom Cherryd6127ef2017-06-15 17:13:56 -0700767 android::base::SetProperty(kRestoreconString, "");
768 android::base::SetProperty(kRestoreconString, path);
769
770 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600771
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700772 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600773 return OK;
774}
775
Jeff Sharkey3472e522017-10-06 18:02:53 -0600776bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
777 // Shamelessly borrowed from android::base::Readlink()
778 result->clear();
779
780 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
781 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
782 // waste memory to just start there. We add 1 so that we can recognize
783 // whether it actually fit (rather than being truncated to 4095).
784 std::vector<char> buf(4095 + 1);
785 while (true) {
786 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
787 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700788 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600789 // It fit! (If size == buf.size(), it may have been truncated.)
790 if (static_cast<size_t>(size) < buf.size()) {
791 result->assign(&buf[0], size);
792 return true;
793 }
794 // Double our buffer and try again.
795 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900796 }
797}
798
Yu Ning942d4e82016-01-08 17:36:47 +0800799bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700800 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800801}
802
Sudheer Shanka295fb242019-01-16 23:04:07 -0800803static status_t findMountPointsWithPrefix(const std::string& prefix,
804 std::list<std::string>& mountPoints) {
805 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
806 // when the prefix is /foo/bar
807 std::string prefixWithSlash(prefix);
808 if (prefix.back() != '/') {
809 android::base::StringAppendF(&prefixWithSlash, "/");
810 }
811
812 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
813 if (!mnts) {
814 PLOG(ERROR) << "Unable to open /proc/mounts";
815 return -errno;
816 }
817
818 // Some volumes can be stacked on each other, so force unmount in
819 // reverse order to give us the best chance of success.
820 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
821 while ((mnt = getmntent(mnts.get())) != nullptr) {
822 auto mountPoint = std::string(mnt->mnt_dir) + "/";
823 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
824 mountPoints.push_front(mountPoint);
825 }
826 }
827 return OK;
828}
829
830// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
831status_t UnmountTreeWithPrefix(const std::string& prefix) {
832 std::list<std::string> toUnmount;
833 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
834 if (result < 0) {
835 return result;
836 }
837 for (const auto& path : toUnmount) {
838 if (umount2(path.c_str(), MNT_DETACH)) {
839 PLOG(ERROR) << "Failed to unmount " << path;
840 result = -errno;
841 }
842 }
843 return result;
844}
845
846status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800847 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
848 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800849 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700850 return -errno;
851 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700852 return OK;
853}
854
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700855static status_t delete_dir_contents(DIR* dir) {
856 // Shamelessly borrowed from android::installd
857 int dfd = dirfd(dir);
858 if (dfd < 0) {
859 return -errno;
860 }
861
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800862 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700863 struct dirent* de;
864 while ((de = readdir(dir))) {
865 const char* name = de->d_name;
866 if (de->d_type == DT_DIR) {
867 /* always skip "." and ".." */
868 if (name[0] == '.') {
869 if (name[1] == 0) continue;
870 if ((name[1] == '.') && (name[2] == 0)) continue;
871 }
872
873 android::base::unique_fd subfd(
874 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
875 if (subfd.get() == -1) {
876 PLOG(ERROR) << "Couldn't openat " << name;
877 result = -errno;
878 continue;
879 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800880 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
881 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700882 if (!subdirp) {
883 PLOG(ERROR) << "Couldn't fdopendir " << name;
884 result = -errno;
885 continue;
886 }
887 result = delete_dir_contents(subdirp.get());
888 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
889 PLOG(ERROR) << "Couldn't unlinkat " << name;
890 result = -errno;
891 }
892 } else {
893 if (unlinkat(dfd, name, 0) < 0) {
894 PLOG(ERROR) << "Couldn't unlinkat " << name;
895 result = -errno;
896 }
897 }
898 }
899 return result;
900}
901
902status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800903 status_t res = DeleteDirContents(pathname);
904 if (res < 0) {
905 return res;
906 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -0800907 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800908 PLOG(ERROR) << "rmdir failed on " << pathname;
909 return -errno;
910 }
911 LOG(VERBOSE) << "Success: rmdir on " << pathname;
912 return OK;
913}
914
915status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700916 // Shamelessly borrowed from android::installd
917 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
918 if (!dirp) {
919 if (errno == ENOENT) {
920 return OK;
921 }
922 PLOG(ERROR) << "Failed to opendir " << pathname;
923 return -errno;
924 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800925 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700926}
927
Paul Crowley298fa322018-10-30 15:59:24 -0700928// TODO(118708649): fix duplication with init/util.h
929status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
930 android::base::Timer t;
931 while (t.duration() < timeout) {
932 struct stat sb;
933 if (stat(filename, &sb) != -1) {
934 LOG(INFO) << "wait for '" << filename << "' took " << t;
935 return 0;
936 }
937 std::this_thread::sleep_for(10ms);
938 }
939 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
940 return -1;
941}
942
Paul Crowley621d9b92018-12-07 15:36:09 -0800943bool FsyncDirectory(const std::string& dirname) {
944 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
945 if (fd == -1) {
946 PLOG(ERROR) << "Failed to open " << dirname;
947 return false;
948 }
949 if (fsync(fd) == -1) {
950 if (errno == EROFS || errno == EINVAL) {
951 PLOG(WARNING) << "Skip fsync " << dirname
952 << " on a file system does not support synchronization";
953 } else {
954 PLOG(ERROR) << "Failed to fsync " << dirname;
955 return false;
956 }
957 }
958 return true;
959}
960
Tommy Chiu0bd2d112019-03-26 17:18:09 +0800961bool writeStringToFile(const std::string& payload, const std::string& filename) {
962 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
963 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
964 if (fd == -1) {
965 PLOG(ERROR) << "Failed to open " << filename;
966 return false;
967 }
968 if (!android::base::WriteStringToFd(payload, fd)) {
969 PLOG(ERROR) << "Failed to write to " << filename;
970 unlink(filename.c_str());
971 return false;
972 }
973 // fsync as close won't guarantee flush data
974 // see close(2), fsync(2) and b/68901441
975 if (fsync(fd) == -1) {
976 if (errno == EROFS || errno == EINVAL) {
977 PLOG(WARNING) << "Skip fsync " << filename
978 << " on a file system does not support synchronization";
979 } else {
980 PLOG(ERROR) << "Failed to fsync " << filename;
981 unlink(filename.c_str());
982 return false;
983 }
984 }
985 return true;
986}
987
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800988} // namespace vold
989} // namespace android