blob: 3e879f65cd194a57e522ebc0a2e2620a9a5c35f3 [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
Alistair Delvad3c230b2020-05-14 16:35:03 -070073static const char* kProcDevices = "/proc/devices";
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070074static const char* kProcFilesystems = "/proc/filesystems";
75
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060076// Lock used to protect process-level SELinux changes from racing with each
77// other between multiple threads.
78static std::mutex kSecurityLock;
79
Jeff Sharkeydeb24052015-03-02 21:01:40 -080080status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060081 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080082 const char* cpath = path.c_str();
83 status_t res = 0;
84
85 char* secontext = nullptr;
86 if (sehandle) {
87 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
88 setfscreatecon(secontext);
89 }
90 }
91
92 mode_t mode = 0660 | S_IFBLK;
93 if (mknod(cpath, mode, dev) < 0) {
94 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070095 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
96 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080097 res = -errno;
98 }
99 }
100
101 if (secontext) {
102 setfscreatecon(nullptr);
103 freecon(secontext);
104 }
105
106 return res;
107}
108
109status_t DestroyDeviceNode(const std::string& path) {
110 const char* cpath = path.c_str();
111 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
112 return -errno;
113 } else {
114 return OK;
115 }
116}
117
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700118status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600119 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700120 const char* cpath = path.c_str();
121
122 char* secontext = nullptr;
123 if (sehandle) {
124 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
125 setfscreatecon(secontext);
126 }
127 }
128
129 int res = fs_prepare_dir(cpath, mode, uid, gid);
130
131 if (secontext) {
132 setfscreatecon(nullptr);
133 freecon(secontext);
134 }
135
136 if (res == 0) {
137 return OK;
138 } else {
139 return -errno;
140 }
141}
142
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800143status_t ForceUnmount(const std::string& path) {
144 const char* cpath = path.c_str();
145 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
146 return OK;
147 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700148 // Apps might still be handling eject request, so wait before
149 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700150 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700151
Jeff Sharkey3472e522017-10-06 18:02:53 -0600152 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700153 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700154 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
155 return OK;
156 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700157
Jeff Sharkey3472e522017-10-06 18:02:53 -0600158 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700159 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800160 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
161 return OK;
162 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700163
Jeff Sharkey3472e522017-10-06 18:02:53 -0600164 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700165 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700166 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
167 return OK;
168 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700169
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800170 return -errno;
171}
172
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700173status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600174 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700175 return OK;
176 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700177 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700178
Jeff Sharkey3472e522017-10-06 18:02:53 -0600179 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700180 return OK;
181 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700182 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700183
Jeff Sharkey3472e522017-10-06 18:02:53 -0600184 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700185 return OK;
186 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700187 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700188
189 // Send SIGKILL a second time to determine if we've
190 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600191 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700192 return OK;
193 }
194 PLOG(ERROR) << "Failed to kill processes using " << path;
195 return -EBUSY;
196}
197
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700198status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800199 if (UnmountTree(target) < 0) {
200 return -errno;
201 }
202 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700203 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
204 return -errno;
205 }
206 return OK;
207}
208
Sudheer Shanka023b5392019-02-06 12:39:19 -0800209status_t Symlink(const std::string& target, const std::string& linkpath) {
210 if (Unlink(linkpath) < 0) {
211 return -errno;
212 }
213 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
214 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
215 return -errno;
216 }
217 return OK;
218}
219
220status_t Unlink(const std::string& linkpath) {
221 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
222 PLOG(ERROR) << "Failed to unlink " << linkpath;
223 return -errno;
224 }
225 return OK;
226}
227
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000228status_t CreateDir(const std::string& dir, mode_t mode) {
229 struct stat sb;
230 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
231 if (S_ISDIR(sb.st_mode)) {
232 return OK;
233 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
234 PLOG(ERROR) << "Failed to unlink " << dir;
235 return -errno;
236 }
237 } else if (errno != ENOENT) {
238 PLOG(ERROR) << "Failed to stat " << dir;
239 return -errno;
240 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800241 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000242 PLOG(ERROR) << "Failed to mkdir " << dir;
243 return -errno;
244 }
245 return OK;
246}
247
Jeff Sharkey3472e522017-10-06 18:02:53 -0600248bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
249 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800250 size_t start = 0;
251 while (true) {
252 start = raw.find(qual, start);
253 if (start == std::string::npos) return false;
254 if (start == 0 || raw[start - 1] == ' ') {
255 break;
256 }
257 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600258 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600259 start += qual.length();
260
261 auto end = raw.find("\"", start);
262 if (end == std::string::npos) return false;
263
264 *value = raw.substr(start, end - start);
265 return true;
266}
267
Paul Crowley14c8c072018-09-18 13:30:21 -0700268static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
269 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600270 fsType->clear();
271 fsUuid->clear();
272 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700273
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700274 std::vector<std::string> cmd;
275 cmd.push_back(kBlkidPath);
276 cmd.push_back("-c");
277 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700278 cmd.push_back("-s");
279 cmd.push_back("TYPE");
280 cmd.push_back("-s");
281 cmd.push_back("UUID");
282 cmd.push_back("-s");
283 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700284 cmd.push_back(path);
285
286 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800287 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700288 if (res != OK) {
289 LOG(WARNING) << "blkid failed to identify " << path;
290 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700291 }
292
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700293 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700294 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600295 FindValue(line, "TYPE", fsType);
296 FindValue(line, "UUID", fsUuid);
297 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700298 }
299
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700300 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700301}
302
Paul Crowley14c8c072018-09-18 13:30:21 -0700303status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
304 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700305 return readMetadata(path, fsType, fsUuid, fsLabel, false);
306}
307
Paul Crowley14c8c072018-09-18 13:30:21 -0700308status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
309 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700310 return readMetadata(path, fsType, fsUuid, fsLabel, true);
311}
312
Paul Crowleyde2d6202018-11-30 11:43:47 -0800313static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
314 std::vector<const char*> argv;
315 argv.reserve(args.size() + 1);
316 for (const auto& arg : args) {
317 if (argv.empty()) {
318 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700319 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800320 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700321 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800322 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700323 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800324 argv.emplace_back(nullptr);
325 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700326}
327
Paul Crowleyde2d6202018-11-30 11:43:47 -0800328static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
329 android::base::unique_fd ufd) {
330 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700331 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800332 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700333 return -errno;
334 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800335 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700336 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800337 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700338 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800339 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700340 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800341 return OK;
342}
343
344status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
345 security_context_t context) {
346 auto argv = ConvertToArgv(args);
347
Paul Crowleye6d76632018-11-30 11:43:47 -0800348 android::base::unique_fd pipe_read, pipe_write;
349 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
350 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800351 return -errno;
352 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800353
354 pid_t pid = fork();
355 if (pid == 0) {
356 if (context) {
357 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800358 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800359 abort();
360 }
361 }
362 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800363 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
364 PLOG(ERROR) << "dup2 in ForkExecvp";
365 _exit(EXIT_FAILURE);
366 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800367 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800368 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800369 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800370 _exit(EXIT_FAILURE);
371 }
372 if (pid == -1) {
373 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700374 return -errno;
375 }
376
Paul Crowleyde2d6202018-11-30 11:43:47 -0800377 pipe_write.reset();
378 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
379 if (st != 0) return st;
380
381 int status;
382 if (waitpid(pid, &status, 0) == -1) {
383 PLOG(ERROR) << "waitpid in ForkExecvp";
384 return -errno;
385 }
386 if (!WIFEXITED(status)) {
387 LOG(ERROR) << "Process did not exit normally, status: " << status;
388 return -ECHILD;
389 }
390 if (WEXITSTATUS(status)) {
391 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
392 return WEXITSTATUS(status);
393 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700394 return OK;
395}
396
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700397pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800398 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700399
400 pid_t pid = fork();
401 if (pid == 0) {
402 close(STDIN_FILENO);
403 close(STDOUT_FILENO);
404 close(STDERR_FILENO);
405
Paul Crowleyde2d6202018-11-30 11:43:47 -0800406 execvp(argv[0], const_cast<char**>(argv.data()));
407 PLOG(ERROR) << "exec in ForkExecvpAsync";
408 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700409 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700410 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800411 PLOG(ERROR) << "fork in ForkExecvpAsync";
412 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700413 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700414 return pid;
415}
416
Jeff Sharkey9c484982015-03-31 10:35:33 -0700417status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100418 out.resize(bytes);
419 return ReadRandomBytes(bytes, &out[0]);
420}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700421
Pavel Grafove2e2d302017-08-01 17:15:53 +0100422status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700423 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
424 if (fd == -1) {
425 return -errno;
426 }
427
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800428 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100429 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700430 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100431 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700432 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700433 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700434
435 if (bytes == 0) {
436 return OK;
437 } else {
438 return -EIO;
439 }
440}
441
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600442status_t GenerateRandomUuid(std::string& out) {
443 status_t res = ReadRandomBytes(16, out);
444 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700445 out[6] &= 0x0f; /* clear version */
446 out[6] |= 0x40; /* set to version 4 */
447 out[8] &= 0x3f; /* clear variant */
448 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600449 }
450 return res;
451}
452
Jeff Sharkey9c484982015-03-31 10:35:33 -0700453status_t HexToStr(const std::string& hex, std::string& str) {
454 str.clear();
455 bool even = true;
456 char cur = 0;
457 for (size_t i = 0; i < hex.size(); i++) {
458 int val = 0;
459 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700460 // clang-format off
461 case ' ': case '-': case ':': continue;
462 case 'f': case 'F': val = 15; break;
463 case 'e': case 'E': val = 14; break;
464 case 'd': case 'D': val = 13; break;
465 case 'c': case 'C': val = 12; break;
466 case 'b': case 'B': val = 11; break;
467 case 'a': case 'A': val = 10; break;
468 case '9': val = 9; break;
469 case '8': val = 8; break;
470 case '7': val = 7; break;
471 case '6': val = 6; break;
472 case '5': val = 5; break;
473 case '4': val = 4; break;
474 case '3': val = 3; break;
475 case '2': val = 2; break;
476 case '1': val = 1; break;
477 case '0': val = 0; break;
478 default: return -EINVAL;
479 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700480 }
481
482 if (even) {
483 cur = val << 4;
484 } else {
485 cur += val;
486 str.push_back(cur);
487 cur = 0;
488 }
489 even = !even;
490 }
491 return even ? OK : -EINVAL;
492}
493
494static const char* kLookup = "0123456789abcdef";
495
496status_t StrToHex(const std::string& str, std::string& hex) {
497 hex.clear();
498 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700499 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700500 hex.push_back(kLookup[str[i] & 0x0F]);
501 }
502 return OK;
503}
504
Pavel Grafove2e2d302017-08-01 17:15:53 +0100505status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
506 hex.clear();
507 for (size_t i = 0; i < str.size(); i++) {
508 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
509 hex.push_back(kLookup[str.data()[i] & 0x0F]);
510 }
511 return OK;
512}
513
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700514status_t NormalizeHex(const std::string& in, std::string& out) {
515 std::string tmp;
516 if (HexToStr(in, tmp)) {
517 return -EINVAL;
518 }
519 return StrToHex(tmp, out);
520}
521
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200522status_t GetBlockDevSize(int fd, uint64_t* size) {
523 if (ioctl(fd, BLKGETSIZE64, size)) {
524 return -errno;
525 }
526
527 return OK;
528}
529
530status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
531 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
532 status_t res = OK;
533
534 if (fd < 0) {
535 return -errno;
536 }
537
538 res = GetBlockDevSize(fd, size);
539
540 close(fd);
541
542 return res;
543}
544
545status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
546 uint64_t size;
547 status_t res = GetBlockDevSize(path, &size);
548
549 if (res != OK) {
550 return res;
551 }
552
553 *nr_sec = size / 512;
554
555 return OK;
556}
557
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700558uint64_t GetFreeBytes(const std::string& path) {
559 struct statvfs sb;
560 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700561 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700562 } else {
563 return -1;
564 }
565}
566
567// TODO: borrowed from frameworks/native/libs/diskusage/ which should
568// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700569static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700570 int64_t blksize = s->st_blksize;
571 // count actual blocks used instead of nominal file size
572 int64_t size = s->st_blocks * 512;
573
574 if (blksize) {
575 /* round up to filesystem block size */
576 size = (size + blksize - 1) & (~(blksize - 1));
577 }
578
579 return size;
580}
581
582// TODO: borrowed from frameworks/native/libs/diskusage/ which should
583// eventually be migrated into system/
584int64_t calculate_dir_size(int dfd) {
585 int64_t size = 0;
586 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700587 DIR* d;
588 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700589
590 d = fdopendir(dfd);
591 if (d == NULL) {
592 close(dfd);
593 return 0;
594 }
595
596 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700597 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700598 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
599 size += stat_size(&s);
600 }
601 if (de->d_type == DT_DIR) {
602 int subfd;
603
604 /* always skip "." and ".." */
605 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700606 if (name[1] == 0) continue;
607 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700608 }
609
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600610 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700611 if (subfd >= 0) {
612 size += calculate_dir_size(subfd);
613 }
614 }
615 }
616 closedir(d);
617 return size;
618}
619
620uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600621 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700622 if (dirfd < 0) {
623 PLOG(WARNING) << "Failed to open " << path;
624 return -1;
625 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700626 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700627 }
628}
629
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700630bool IsFilesystemSupported(const std::string& fsType) {
631 std::string supported;
632 if (!ReadFileToString(kProcFilesystems, &supported)) {
633 PLOG(ERROR) << "Failed to read supported filesystems";
634 return false;
635 }
636 return supported.find(fsType + "\n") != std::string::npos;
637}
638
639status_t WipeBlockDevice(const std::string& path) {
640 status_t res = -1;
641 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200642 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700643
644 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
645 if (fd == -1) {
646 PLOG(ERROR) << "Failed to open " << path;
647 goto done;
648 }
649
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200650 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700651 PLOG(ERROR) << "Failed to determine size of " << path;
652 goto done;
653 }
654
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700655 LOG(INFO) << "About to discard " << range[1] << " on " << path;
656 if (ioctl(fd, BLKDISCARD, &range) == 0) {
657 LOG(INFO) << "Discard success on " << path;
658 res = 0;
659 } else {
660 PLOG(ERROR) << "Discard failure on " << path;
661 }
662
663done:
664 close(fd);
665 return res;
666}
667
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800668static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700669 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800670 return false;
671 } else {
672 return true;
673 }
674}
675
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700676std::string BuildKeyPath(const std::string& partGuid) {
677 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
678}
679
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600680std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700681 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600682}
683
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800684std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700685 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700686}
687
688std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700689 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700690}
691
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600692std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700693 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600694}
695
Jeff Sharkey47695b22016-02-01 17:02:29 -0700696std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700697 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700698}
699
700std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700701 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800702}
703
Calin Juravle79f55a42016-02-17 20:14:46 +0000704// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
705std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700706 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000707}
708
Andreas Huber71cd43f2018-01-22 11:25:29 -0800709std::string BuildDataVendorCePath(userid_t userId) {
710 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
711}
712
713std::string BuildDataVendorDePath(userid_t userId) {
714 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
715}
716
Paul Crowley3b71fc52017-10-09 10:55:21 -0700717std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800718 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700719 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800720 return "/data";
721 } else {
722 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700723 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800724 }
725}
726
Paul Crowley3b71fc52017-10-09 10:55:21 -0700727std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700728 // TODO: unify with installd path generation logic
729 std::string data(BuildDataPath(volumeUuid));
730 return StringPrintf("%s/media/%u", data.c_str(), userId);
731}
732
Paul Crowley3b71fc52017-10-09 10:55:21 -0700733std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800734 // TODO: unify with installd path generation logic
735 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700736 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800737 std::string legacy = StringPrintf("%s/data", data.c_str());
738 struct stat sb;
739 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
740 /* /data/data is dir, return /data/data for legacy system */
741 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800742 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800743 }
cjbaoeb501142017-04-12 00:09:00 +0800744 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800745}
746
Paul Crowley3b71fc52017-10-09 10:55:21 -0700747std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800748 // TODO: unify with installd path generation logic
749 std::string data(BuildDataPath(volumeUuid));
750 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
751}
752
Jeff Sharkey66270a22015-06-24 11:49:24 -0700753dev_t GetDevice(const std::string& path) {
754 struct stat sb;
755 if (stat(path.c_str(), &sb)) {
756 PLOG(WARNING) << "Failed to stat " << path;
757 return 0;
758 } else {
759 return sb.st_dev;
760 }
761}
762
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600763status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700764 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600765
Tom Cherryd6127ef2017-06-15 17:13:56 -0700766 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600767
Tom Cherryd6127ef2017-06-15 17:13:56 -0700768 android::base::SetProperty(kRestoreconString, "");
769 android::base::SetProperty(kRestoreconString, path);
770
771 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600772
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700773 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600774 return OK;
775}
776
Jeff Sharkey3472e522017-10-06 18:02:53 -0600777bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
778 // Shamelessly borrowed from android::base::Readlink()
779 result->clear();
780
781 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
782 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
783 // waste memory to just start there. We add 1 so that we can recognize
784 // whether it actually fit (rather than being truncated to 4095).
785 std::vector<char> buf(4095 + 1);
786 while (true) {
787 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
788 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700789 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600790 // It fit! (If size == buf.size(), it may have been truncated.)
791 if (static_cast<size_t>(size) < buf.size()) {
792 result->assign(&buf[0], size);
793 return true;
794 }
795 // Double our buffer and try again.
796 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900797 }
798}
799
Alistair Delvad3c230b2020-05-14 16:35:03 -0700800static unsigned int GetMajorBlockVirtioBlk() {
801 std::string devices;
802 if (!ReadFileToString(kProcDevices, &devices)) {
803 PLOG(ERROR) << "Unable to open /proc/devices";
804 return 0;
805 }
806
807 bool blockSection = false;
808 for (auto line : android::base::Split(devices, "\n")) {
809 if (line == "Block devices:") {
810 blockSection = true;
811 } else if (line == "Character devices:") {
812 blockSection = false;
813 } else if (blockSection) {
814 auto tokens = android::base::Split(line, " ");
815 if (tokens.size() == 2 && tokens[1] == "virtblk") {
816 return std::stoul(tokens[0]);
817 }
818 }
819 }
820
821 return 0;
822}
823
824bool IsVirtioBlkDevice(unsigned int major) {
825 // Most virtualized platforms expose block devices with the virtio-blk
826 // block device driver. Unfortunately, this driver does not use a fixed
827 // major number, but relies on the kernel to assign one from a specific
828 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
829 // per Documentation/devices.txt. This is true even for the latest Linux
830 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
831 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
832 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +0800833}
834
Sudheer Shanka295fb242019-01-16 23:04:07 -0800835static status_t findMountPointsWithPrefix(const std::string& prefix,
836 std::list<std::string>& mountPoints) {
837 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
838 // when the prefix is /foo/bar
839 std::string prefixWithSlash(prefix);
840 if (prefix.back() != '/') {
841 android::base::StringAppendF(&prefixWithSlash, "/");
842 }
843
844 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
845 if (!mnts) {
846 PLOG(ERROR) << "Unable to open /proc/mounts";
847 return -errno;
848 }
849
850 // Some volumes can be stacked on each other, so force unmount in
851 // reverse order to give us the best chance of success.
852 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
853 while ((mnt = getmntent(mnts.get())) != nullptr) {
854 auto mountPoint = std::string(mnt->mnt_dir) + "/";
855 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
856 mountPoints.push_front(mountPoint);
857 }
858 }
859 return OK;
860}
861
862// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
863status_t UnmountTreeWithPrefix(const std::string& prefix) {
864 std::list<std::string> toUnmount;
865 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
866 if (result < 0) {
867 return result;
868 }
869 for (const auto& path : toUnmount) {
870 if (umount2(path.c_str(), MNT_DETACH)) {
871 PLOG(ERROR) << "Failed to unmount " << path;
872 result = -errno;
873 }
874 }
875 return result;
876}
877
878status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800879 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
880 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800881 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700882 return -errno;
883 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700884 return OK;
885}
886
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700887static status_t delete_dir_contents(DIR* dir) {
888 // Shamelessly borrowed from android::installd
889 int dfd = dirfd(dir);
890 if (dfd < 0) {
891 return -errno;
892 }
893
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800894 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700895 struct dirent* de;
896 while ((de = readdir(dir))) {
897 const char* name = de->d_name;
898 if (de->d_type == DT_DIR) {
899 /* always skip "." and ".." */
900 if (name[0] == '.') {
901 if (name[1] == 0) continue;
902 if ((name[1] == '.') && (name[2] == 0)) continue;
903 }
904
905 android::base::unique_fd subfd(
906 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
907 if (subfd.get() == -1) {
908 PLOG(ERROR) << "Couldn't openat " << name;
909 result = -errno;
910 continue;
911 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800912 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
913 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700914 if (!subdirp) {
915 PLOG(ERROR) << "Couldn't fdopendir " << name;
916 result = -errno;
917 continue;
918 }
919 result = delete_dir_contents(subdirp.get());
920 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
921 PLOG(ERROR) << "Couldn't unlinkat " << name;
922 result = -errno;
923 }
924 } else {
925 if (unlinkat(dfd, name, 0) < 0) {
926 PLOG(ERROR) << "Couldn't unlinkat " << name;
927 result = -errno;
928 }
929 }
930 }
931 return result;
932}
933
934status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800935 status_t res = DeleteDirContents(pathname);
936 if (res < 0) {
937 return res;
938 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -0800939 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800940 PLOG(ERROR) << "rmdir failed on " << pathname;
941 return -errno;
942 }
943 LOG(VERBOSE) << "Success: rmdir on " << pathname;
944 return OK;
945}
946
947status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700948 // Shamelessly borrowed from android::installd
949 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
950 if (!dirp) {
951 if (errno == ENOENT) {
952 return OK;
953 }
954 PLOG(ERROR) << "Failed to opendir " << pathname;
955 return -errno;
956 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800957 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700958}
959
Paul Crowley298fa322018-10-30 15:59:24 -0700960// TODO(118708649): fix duplication with init/util.h
961status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
962 android::base::Timer t;
963 while (t.duration() < timeout) {
964 struct stat sb;
965 if (stat(filename, &sb) != -1) {
966 LOG(INFO) << "wait for '" << filename << "' took " << t;
967 return 0;
968 }
969 std::this_thread::sleep_for(10ms);
970 }
971 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
972 return -1;
973}
974
Paul Crowley621d9b92018-12-07 15:36:09 -0800975bool FsyncDirectory(const std::string& dirname) {
976 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
977 if (fd == -1) {
978 PLOG(ERROR) << "Failed to open " << dirname;
979 return false;
980 }
981 if (fsync(fd) == -1) {
982 if (errno == EROFS || errno == EINVAL) {
983 PLOG(WARNING) << "Skip fsync " << dirname
984 << " on a file system does not support synchronization";
985 } else {
986 PLOG(ERROR) << "Failed to fsync " << dirname;
987 return false;
988 }
989 }
990 return true;
991}
992
Tommy Chiu0bd2d112019-03-26 17:18:09 +0800993bool writeStringToFile(const std::string& payload, const std::string& filename) {
994 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
995 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
996 if (fd == -1) {
997 PLOG(ERROR) << "Failed to open " << filename;
998 return false;
999 }
1000 if (!android::base::WriteStringToFd(payload, fd)) {
1001 PLOG(ERROR) << "Failed to write to " << filename;
1002 unlink(filename.c_str());
1003 return false;
1004 }
1005 // fsync as close won't guarantee flush data
1006 // see close(2), fsync(2) and b/68901441
1007 if (fsync(fd) == -1) {
1008 if (errno == EROFS || errno == EINVAL) {
1009 PLOG(WARNING) << "Skip fsync " << filename
1010 << " on a file system does not support synchronization";
1011 } else {
1012 PLOG(ERROR) << "Failed to fsync " << filename;
1013 unlink(filename.c_str());
1014 return false;
1015 }
1016 }
1017 return true;
1018}
1019
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001020} // namespace vold
1021} // namespace android