blob: 0375765b6c4fa8f17891cadcaeb49ec19375861c [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;
Martijn Coenen13ff6682019-12-24 12:57:16 +010058using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070059using android::base::StringPrintf;
60
Jeff Sharkeydeb24052015-03-02 21:01:40 -080061namespace android {
62namespace vold {
63
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070064security_context_t sBlkidContext = nullptr;
65security_context_t sBlkidUntrustedContext = nullptr;
66security_context_t sFsckContext = nullptr;
67security_context_t sFsckUntrustedContext = nullptr;
68
Paul Crowley56292ef2017-10-20 08:07:53 -070069bool sSleepOnUnmount = true;
70
Jeff Sharkey9c484982015-03-31 10:35:33 -070071static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070072static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070073
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
Martijn Coenen13ff6682019-12-24 12:57:16 +0100118int PrepareDirsFromRoot(std::string path, std::string root, mode_t mode, uid_t uid, gid_t gid) {
119 int ret = 0;
120 if (!StartsWith(path, root)) {
121 return -1;
122 }
123 std::string to_create_from_root = path.substr(root.length());
124
125 size_t pos = 0;
126 while ((pos = to_create_from_root.find('/')) != std::string::npos) {
127 auto component = to_create_from_root.substr(0, pos);
128 to_create_from_root.erase(0, pos + 1);
129 root = root + component + "/";
130 ret = fs_prepare_dir(root.c_str(), mode, uid, gid);
131 if (ret) {
132 break;
133 }
134 }
135
136 return ret;
137}
138
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700139status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600140 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700141 const char* cpath = path.c_str();
142
143 char* secontext = nullptr;
144 if (sehandle) {
145 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
146 setfscreatecon(secontext);
147 }
148 }
149
150 int res = fs_prepare_dir(cpath, mode, uid, gid);
151
152 if (secontext) {
153 setfscreatecon(nullptr);
154 freecon(secontext);
155 }
156
157 if (res == 0) {
158 return OK;
159 } else {
160 return -errno;
161 }
162}
163
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800164status_t ForceUnmount(const std::string& path) {
165 const char* cpath = path.c_str();
166 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
167 return OK;
168 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700169 // Apps might still be handling eject request, so wait before
170 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700171 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700172
Jeff Sharkey3472e522017-10-06 18:02:53 -0600173 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700174 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700175 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
176 return OK;
177 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700178
Jeff Sharkey3472e522017-10-06 18:02:53 -0600179 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700180 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800181 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
182 return OK;
183 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700184
Jeff Sharkey3472e522017-10-06 18:02:53 -0600185 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700186 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700187 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
188 return OK;
189 }
Zim3623a212019-07-19 16:46:53 +0100190 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800191 return -errno;
192}
193
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700194status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600195 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700196 return OK;
197 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700198 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700199
Jeff Sharkey3472e522017-10-06 18:02:53 -0600200 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700201 return OK;
202 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700203 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700204
Jeff Sharkey3472e522017-10-06 18:02:53 -0600205 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700206 return OK;
207 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700208 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700209
210 // Send SIGKILL a second time to determine if we've
211 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600212 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700213 return OK;
214 }
215 PLOG(ERROR) << "Failed to kill processes using " << path;
216 return -EBUSY;
217}
218
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700219status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800220 if (UnmountTree(target) < 0) {
221 return -errno;
222 }
223 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700224 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
225 return -errno;
226 }
227 return OK;
228}
229
Sudheer Shanka023b5392019-02-06 12:39:19 -0800230status_t Symlink(const std::string& target, const std::string& linkpath) {
231 if (Unlink(linkpath) < 0) {
232 return -errno;
233 }
234 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
235 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
236 return -errno;
237 }
238 return OK;
239}
240
241status_t Unlink(const std::string& linkpath) {
242 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
243 PLOG(ERROR) << "Failed to unlink " << linkpath;
244 return -errno;
245 }
246 return OK;
247}
248
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000249status_t CreateDir(const std::string& dir, mode_t mode) {
250 struct stat sb;
251 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
252 if (S_ISDIR(sb.st_mode)) {
253 return OK;
254 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
255 PLOG(ERROR) << "Failed to unlink " << dir;
256 return -errno;
257 }
258 } else if (errno != ENOENT) {
259 PLOG(ERROR) << "Failed to stat " << dir;
260 return -errno;
261 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800262 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000263 PLOG(ERROR) << "Failed to mkdir " << dir;
264 return -errno;
265 }
266 return OK;
267}
268
Jeff Sharkey3472e522017-10-06 18:02:53 -0600269bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
270 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800271 size_t start = 0;
272 while (true) {
273 start = raw.find(qual, start);
274 if (start == std::string::npos) return false;
275 if (start == 0 || raw[start - 1] == ' ') {
276 break;
277 }
278 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600279 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600280 start += qual.length();
281
282 auto end = raw.find("\"", start);
283 if (end == std::string::npos) return false;
284
285 *value = raw.substr(start, end - start);
286 return true;
287}
288
Paul Crowley14c8c072018-09-18 13:30:21 -0700289static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
290 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600291 fsType->clear();
292 fsUuid->clear();
293 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700294
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700295 std::vector<std::string> cmd;
296 cmd.push_back(kBlkidPath);
297 cmd.push_back("-c");
298 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700299 cmd.push_back("-s");
300 cmd.push_back("TYPE");
301 cmd.push_back("-s");
302 cmd.push_back("UUID");
303 cmd.push_back("-s");
304 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700305 cmd.push_back(path);
306
307 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800308 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700309 if (res != OK) {
310 LOG(WARNING) << "blkid failed to identify " << path;
311 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700312 }
313
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700314 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700315 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600316 FindValue(line, "TYPE", fsType);
317 FindValue(line, "UUID", fsUuid);
318 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700319 }
320
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700321 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700322}
323
Paul Crowley14c8c072018-09-18 13:30:21 -0700324status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
325 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700326 return readMetadata(path, fsType, fsUuid, fsLabel, false);
327}
328
Paul Crowley14c8c072018-09-18 13:30:21 -0700329status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
330 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700331 return readMetadata(path, fsType, fsUuid, fsLabel, true);
332}
333
Paul Crowleyde2d6202018-11-30 11:43:47 -0800334static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
335 std::vector<const char*> argv;
336 argv.reserve(args.size() + 1);
337 for (const auto& arg : args) {
338 if (argv.empty()) {
339 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700340 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800341 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700342 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800343 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700344 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800345 argv.emplace_back(nullptr);
346 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700347}
348
Paul Crowleyde2d6202018-11-30 11:43:47 -0800349static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
350 android::base::unique_fd ufd) {
351 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700352 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800353 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700354 return -errno;
355 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800356 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700357 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800358 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700359 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800360 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700361 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800362 return OK;
363}
364
365status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
366 security_context_t context) {
367 auto argv = ConvertToArgv(args);
368
Paul Crowleye6d76632018-11-30 11:43:47 -0800369 android::base::unique_fd pipe_read, pipe_write;
370 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
371 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800372 return -errno;
373 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800374
375 pid_t pid = fork();
376 if (pid == 0) {
377 if (context) {
378 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800379 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800380 abort();
381 }
382 }
383 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800384 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
385 PLOG(ERROR) << "dup2 in ForkExecvp";
386 _exit(EXIT_FAILURE);
387 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800388 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800389 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800390 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800391 _exit(EXIT_FAILURE);
392 }
393 if (pid == -1) {
394 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700395 return -errno;
396 }
397
Paul Crowleyde2d6202018-11-30 11:43:47 -0800398 pipe_write.reset();
399 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
400 if (st != 0) return st;
401
402 int status;
403 if (waitpid(pid, &status, 0) == -1) {
404 PLOG(ERROR) << "waitpid in ForkExecvp";
405 return -errno;
406 }
407 if (!WIFEXITED(status)) {
408 LOG(ERROR) << "Process did not exit normally, status: " << status;
409 return -ECHILD;
410 }
411 if (WEXITSTATUS(status)) {
412 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
413 return WEXITSTATUS(status);
414 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700415 return OK;
416}
417
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700418pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800419 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700420
421 pid_t pid = fork();
422 if (pid == 0) {
423 close(STDIN_FILENO);
424 close(STDOUT_FILENO);
425 close(STDERR_FILENO);
426
Paul Crowleyde2d6202018-11-30 11:43:47 -0800427 execvp(argv[0], const_cast<char**>(argv.data()));
428 PLOG(ERROR) << "exec in ForkExecvpAsync";
429 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700430 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700431 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800432 PLOG(ERROR) << "fork in ForkExecvpAsync";
433 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700434 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700435 return pid;
436}
437
Jeff Sharkey9c484982015-03-31 10:35:33 -0700438status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100439 out.resize(bytes);
440 return ReadRandomBytes(bytes, &out[0]);
441}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700442
Pavel Grafove2e2d302017-08-01 17:15:53 +0100443status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700444 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
445 if (fd == -1) {
446 return -errno;
447 }
448
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800449 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100450 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700451 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100452 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700453 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700454 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700455
456 if (bytes == 0) {
457 return OK;
458 } else {
459 return -EIO;
460 }
461}
462
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600463status_t GenerateRandomUuid(std::string& out) {
464 status_t res = ReadRandomBytes(16, out);
465 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700466 out[6] &= 0x0f; /* clear version */
467 out[6] |= 0x40; /* set to version 4 */
468 out[8] &= 0x3f; /* clear variant */
469 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600470 }
471 return res;
472}
473
Jeff Sharkey9c484982015-03-31 10:35:33 -0700474status_t HexToStr(const std::string& hex, std::string& str) {
475 str.clear();
476 bool even = true;
477 char cur = 0;
478 for (size_t i = 0; i < hex.size(); i++) {
479 int val = 0;
480 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700481 // clang-format off
482 case ' ': case '-': case ':': continue;
483 case 'f': case 'F': val = 15; break;
484 case 'e': case 'E': val = 14; break;
485 case 'd': case 'D': val = 13; break;
486 case 'c': case 'C': val = 12; break;
487 case 'b': case 'B': val = 11; break;
488 case 'a': case 'A': val = 10; break;
489 case '9': val = 9; break;
490 case '8': val = 8; break;
491 case '7': val = 7; break;
492 case '6': val = 6; break;
493 case '5': val = 5; break;
494 case '4': val = 4; break;
495 case '3': val = 3; break;
496 case '2': val = 2; break;
497 case '1': val = 1; break;
498 case '0': val = 0; break;
499 default: return -EINVAL;
500 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700501 }
502
503 if (even) {
504 cur = val << 4;
505 } else {
506 cur += val;
507 str.push_back(cur);
508 cur = 0;
509 }
510 even = !even;
511 }
512 return even ? OK : -EINVAL;
513}
514
515static const char* kLookup = "0123456789abcdef";
516
517status_t StrToHex(const std::string& str, std::string& hex) {
518 hex.clear();
519 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700520 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700521 hex.push_back(kLookup[str[i] & 0x0F]);
522 }
523 return OK;
524}
525
Pavel Grafove2e2d302017-08-01 17:15:53 +0100526status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
527 hex.clear();
528 for (size_t i = 0; i < str.size(); i++) {
529 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
530 hex.push_back(kLookup[str.data()[i] & 0x0F]);
531 }
532 return OK;
533}
534
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700535status_t NormalizeHex(const std::string& in, std::string& out) {
536 std::string tmp;
537 if (HexToStr(in, tmp)) {
538 return -EINVAL;
539 }
540 return StrToHex(tmp, out);
541}
542
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200543status_t GetBlockDevSize(int fd, uint64_t* size) {
544 if (ioctl(fd, BLKGETSIZE64, size)) {
545 return -errno;
546 }
547
548 return OK;
549}
550
551status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
552 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
553 status_t res = OK;
554
555 if (fd < 0) {
556 return -errno;
557 }
558
559 res = GetBlockDevSize(fd, size);
560
561 close(fd);
562
563 return res;
564}
565
566status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
567 uint64_t size;
568 status_t res = GetBlockDevSize(path, &size);
569
570 if (res != OK) {
571 return res;
572 }
573
574 *nr_sec = size / 512;
575
576 return OK;
577}
578
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700579uint64_t GetFreeBytes(const std::string& path) {
580 struct statvfs sb;
581 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700582 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700583 } else {
584 return -1;
585 }
586}
587
588// TODO: borrowed from frameworks/native/libs/diskusage/ which should
589// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700590static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700591 int64_t blksize = s->st_blksize;
592 // count actual blocks used instead of nominal file size
593 int64_t size = s->st_blocks * 512;
594
595 if (blksize) {
596 /* round up to filesystem block size */
597 size = (size + blksize - 1) & (~(blksize - 1));
598 }
599
600 return size;
601}
602
603// TODO: borrowed from frameworks/native/libs/diskusage/ which should
604// eventually be migrated into system/
605int64_t calculate_dir_size(int dfd) {
606 int64_t size = 0;
607 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700608 DIR* d;
609 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700610
611 d = fdopendir(dfd);
612 if (d == NULL) {
613 close(dfd);
614 return 0;
615 }
616
617 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700618 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700619 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
620 size += stat_size(&s);
621 }
622 if (de->d_type == DT_DIR) {
623 int subfd;
624
625 /* always skip "." and ".." */
626 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700627 if (name[1] == 0) continue;
628 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700629 }
630
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600631 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700632 if (subfd >= 0) {
633 size += calculate_dir_size(subfd);
634 }
635 }
636 }
637 closedir(d);
638 return size;
639}
640
641uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600642 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700643 if (dirfd < 0) {
644 PLOG(WARNING) << "Failed to open " << path;
645 return -1;
646 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700647 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700648 }
649}
650
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700651bool IsFilesystemSupported(const std::string& fsType) {
652 std::string supported;
653 if (!ReadFileToString(kProcFilesystems, &supported)) {
654 PLOG(ERROR) << "Failed to read supported filesystems";
655 return false;
656 }
657 return supported.find(fsType + "\n") != std::string::npos;
658}
659
660status_t WipeBlockDevice(const std::string& path) {
661 status_t res = -1;
662 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200663 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700664
665 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
666 if (fd == -1) {
667 PLOG(ERROR) << "Failed to open " << path;
668 goto done;
669 }
670
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200671 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700672 PLOG(ERROR) << "Failed to determine size of " << path;
673 goto done;
674 }
675
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700676 LOG(INFO) << "About to discard " << range[1] << " on " << path;
677 if (ioctl(fd, BLKDISCARD, &range) == 0) {
678 LOG(INFO) << "Discard success on " << path;
679 res = 0;
680 } else {
681 PLOG(ERROR) << "Discard failure on " << path;
682 }
683
684done:
685 close(fd);
686 return res;
687}
688
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800689static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700690 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800691 return false;
692 } else {
693 return true;
694 }
695}
696
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700697std::string BuildKeyPath(const std::string& partGuid) {
698 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
699}
700
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600701std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700702 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600703}
704
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800705std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700706 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700707}
708
709std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700710 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700711}
712
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600713std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700714 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600715}
716
Jeff Sharkey47695b22016-02-01 17:02:29 -0700717std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700718 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700719}
720
721std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700722 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800723}
724
Calin Juravle79f55a42016-02-17 20:14:46 +0000725// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
726std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700727 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000728}
729
Andreas Huber71cd43f2018-01-22 11:25:29 -0800730std::string BuildDataVendorCePath(userid_t userId) {
731 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
732}
733
734std::string BuildDataVendorDePath(userid_t userId) {
735 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
736}
737
Paul Crowley3b71fc52017-10-09 10:55:21 -0700738std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800739 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700740 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800741 return "/data";
742 } else {
743 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700744 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800745 }
746}
747
Paul Crowley3b71fc52017-10-09 10:55:21 -0700748std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700749 // TODO: unify with installd path generation logic
750 std::string data(BuildDataPath(volumeUuid));
751 return StringPrintf("%s/media/%u", data.c_str(), userId);
752}
753
Paul Crowley3b71fc52017-10-09 10:55:21 -0700754std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800755 // TODO: unify with installd path generation logic
756 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700757 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800758 std::string legacy = StringPrintf("%s/data", data.c_str());
759 struct stat sb;
760 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
761 /* /data/data is dir, return /data/data for legacy system */
762 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800763 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800764 }
cjbaoeb501142017-04-12 00:09:00 +0800765 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800766}
767
Paul Crowley3b71fc52017-10-09 10:55:21 -0700768std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800769 // TODO: unify with installd path generation logic
770 std::string data(BuildDataPath(volumeUuid));
771 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
772}
773
Jeff Sharkey66270a22015-06-24 11:49:24 -0700774dev_t GetDevice(const std::string& path) {
775 struct stat sb;
776 if (stat(path.c_str(), &sb)) {
777 PLOG(WARNING) << "Failed to stat " << path;
778 return 0;
779 } else {
780 return sb.st_dev;
781 }
782}
783
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600784status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700785 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600786
Tom Cherryd6127ef2017-06-15 17:13:56 -0700787 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600788
Tom Cherryd6127ef2017-06-15 17:13:56 -0700789 android::base::SetProperty(kRestoreconString, "");
790 android::base::SetProperty(kRestoreconString, path);
791
792 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600793
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700794 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600795 return OK;
796}
797
Jeff Sharkey3472e522017-10-06 18:02:53 -0600798bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
799 // Shamelessly borrowed from android::base::Readlink()
800 result->clear();
801
802 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
803 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
804 // waste memory to just start there. We add 1 so that we can recognize
805 // whether it actually fit (rather than being truncated to 4095).
806 std::vector<char> buf(4095 + 1);
807 while (true) {
808 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
809 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700810 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600811 // It fit! (If size == buf.size(), it may have been truncated.)
812 if (static_cast<size_t>(size) < buf.size()) {
813 result->assign(&buf[0], size);
814 return true;
815 }
816 // Double our buffer and try again.
817 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900818 }
819}
820
Yu Ning942d4e82016-01-08 17:36:47 +0800821bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700822 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800823}
824
Sudheer Shanka295fb242019-01-16 23:04:07 -0800825static status_t findMountPointsWithPrefix(const std::string& prefix,
826 std::list<std::string>& mountPoints) {
827 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
828 // when the prefix is /foo/bar
829 std::string prefixWithSlash(prefix);
830 if (prefix.back() != '/') {
831 android::base::StringAppendF(&prefixWithSlash, "/");
832 }
833
834 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
835 if (!mnts) {
836 PLOG(ERROR) << "Unable to open /proc/mounts";
837 return -errno;
838 }
839
840 // Some volumes can be stacked on each other, so force unmount in
841 // reverse order to give us the best chance of success.
842 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
843 while ((mnt = getmntent(mnts.get())) != nullptr) {
844 auto mountPoint = std::string(mnt->mnt_dir) + "/";
845 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
846 mountPoints.push_front(mountPoint);
847 }
848 }
849 return OK;
850}
851
852// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
853status_t UnmountTreeWithPrefix(const std::string& prefix) {
854 std::list<std::string> toUnmount;
855 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
856 if (result < 0) {
857 return result;
858 }
859 for (const auto& path : toUnmount) {
860 if (umount2(path.c_str(), MNT_DETACH)) {
861 PLOG(ERROR) << "Failed to unmount " << path;
862 result = -errno;
863 }
864 }
865 return result;
866}
867
868status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800869 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
870 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800871 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700872 return -errno;
873 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700874 return OK;
875}
876
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700877static status_t delete_dir_contents(DIR* dir) {
878 // Shamelessly borrowed from android::installd
879 int dfd = dirfd(dir);
880 if (dfd < 0) {
881 return -errno;
882 }
883
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800884 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700885 struct dirent* de;
886 while ((de = readdir(dir))) {
887 const char* name = de->d_name;
888 if (de->d_type == DT_DIR) {
889 /* always skip "." and ".." */
890 if (name[0] == '.') {
891 if (name[1] == 0) continue;
892 if ((name[1] == '.') && (name[2] == 0)) continue;
893 }
894
895 android::base::unique_fd subfd(
896 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
897 if (subfd.get() == -1) {
898 PLOG(ERROR) << "Couldn't openat " << name;
899 result = -errno;
900 continue;
901 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800902 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
903 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700904 if (!subdirp) {
905 PLOG(ERROR) << "Couldn't fdopendir " << name;
906 result = -errno;
907 continue;
908 }
909 result = delete_dir_contents(subdirp.get());
910 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
911 PLOG(ERROR) << "Couldn't unlinkat " << name;
912 result = -errno;
913 }
914 } else {
915 if (unlinkat(dfd, name, 0) < 0) {
916 PLOG(ERROR) << "Couldn't unlinkat " << name;
917 result = -errno;
918 }
919 }
920 }
921 return result;
922}
923
924status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800925 status_t res = DeleteDirContents(pathname);
926 if (res < 0) {
927 return res;
928 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -0800929 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800930 PLOG(ERROR) << "rmdir failed on " << pathname;
931 return -errno;
932 }
933 LOG(VERBOSE) << "Success: rmdir on " << pathname;
934 return OK;
935}
936
937status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700938 // Shamelessly borrowed from android::installd
939 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
940 if (!dirp) {
941 if (errno == ENOENT) {
942 return OK;
943 }
944 PLOG(ERROR) << "Failed to opendir " << pathname;
945 return -errno;
946 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800947 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700948}
949
Paul Crowley298fa322018-10-30 15:59:24 -0700950// TODO(118708649): fix duplication with init/util.h
951status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
952 android::base::Timer t;
953 while (t.duration() < timeout) {
954 struct stat sb;
955 if (stat(filename, &sb) != -1) {
956 LOG(INFO) << "wait for '" << filename << "' took " << t;
957 return 0;
958 }
959 std::this_thread::sleep_for(10ms);
960 }
961 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
962 return -1;
963}
964
Paul Crowley621d9b92018-12-07 15:36:09 -0800965bool FsyncDirectory(const std::string& dirname) {
966 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
967 if (fd == -1) {
968 PLOG(ERROR) << "Failed to open " << dirname;
969 return false;
970 }
971 if (fsync(fd) == -1) {
972 if (errno == EROFS || errno == EINVAL) {
973 PLOG(WARNING) << "Skip fsync " << dirname
974 << " on a file system does not support synchronization";
975 } else {
976 PLOG(ERROR) << "Failed to fsync " << dirname;
977 return false;
978 }
979 }
980 return true;
981}
982
Tommy Chiu0bd2d112019-03-26 17:18:09 +0800983bool writeStringToFile(const std::string& payload, const std::string& filename) {
984 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
985 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
986 if (fd == -1) {
987 PLOG(ERROR) << "Failed to open " << filename;
988 return false;
989 }
990 if (!android::base::WriteStringToFd(payload, fd)) {
991 PLOG(ERROR) << "Failed to write to " << filename;
992 unlink(filename.c_str());
993 return false;
994 }
995 // fsync as close won't guarantee flush data
996 // see close(2), fsync(2) and b/68901441
997 if (fsync(fd) == -1) {
998 if (errno == EROFS || errno == EINVAL) {
999 PLOG(WARNING) << "Skip fsync " << filename
1000 << " on a file system does not support synchronization";
1001 } else {
1002 PLOG(ERROR) << "Failed to fsync " << filename;
1003 unlink(filename.c_str());
1004 return false;
1005 }
1006 }
1007 return true;
1008}
1009
Zima438b242019-09-25 14:37:38 +01001010status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1011 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1012 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1013 std::string fuse_path(
1014 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1015
1016 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1017 std::string pass_through_path(
1018 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001019
Zim3623a212019-07-19 16:46:53 +01001020 // Create directories.
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001021 auto result = PrepareDir(pre_fuse_path, 0700, AID_ROOT, AID_ROOT);
Zim3623a212019-07-19 16:46:53 +01001022 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001023 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001024 return -1;
1025 }
1026
Zima438b242019-09-25 14:37:38 +01001027 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1028 if (result != android::OK) {
1029 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1030 return -1;
1031 }
1032
1033 result = PrepareDir(pre_pass_through_path, 0755, AID_ROOT, AID_ROOT);
1034 if (result != android::OK) {
1035 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1036 return -1;
1037 }
1038
1039 result = PrepareDir(pass_through_path, 0755, AID_ROOT, AID_ROOT);
1040 if (result != android::OK) {
1041 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1042 return -1;
1043 }
1044
1045 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001046 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1047 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001048 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001049 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001050 return -1;
1051 }
Zime5393d42019-11-15 11:44:12 +00001052 linkpath += "/primary";
Zima438b242019-09-25 14:37:38 +01001053
Zime5393d42019-11-15 11:44:12 +00001054 Symlink(fuse_path + "/" + std::to_string(user_id), linkpath);
Zima438b242019-09-25 14:37:38 +01001055 }
1056
Nandana Dutta914cc72019-08-29 15:22:42 +01001057 // Open fuse fd.
1058 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1059 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001060 PLOG(ERROR) << "Failed to open /dev/fuse";
1061 return -1;
1062 }
1063
1064 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1065 // permission checks before routing to FUSE daemon.
1066 const auto opts = StringPrintf(
1067 "fd=%i,"
1068 "rootmode=40000,"
1069 "allow_other,"
1070 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001071 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001072
Zima438b242019-09-25 14:37:38 +01001073 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1074 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1075 opts.c_str()));
1076 if (result != 0) {
1077 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001078 return -errno;
1079 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001080
Martijn Coenen86f21a22020-01-06 09:48:14 +01001081 if (IsFilesystemSupported("sdcardfs")) {
1082 std::string sdcardfs_path(
1083 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1084
1085 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1086 return BindMount(sdcardfs_path, pass_through_path);
1087 } else {
1088 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1089 return BindMount(absolute_lower_path, pass_through_path);
1090 }
Zima438b242019-09-25 14:37:38 +01001091}
1092
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001093status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1094 const std::string& relative_upper_path) {
1095 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1096 std::string pass_through_path(
1097 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1098
Zima438b242019-09-25 14:37:38 +01001099 // Best effort unmount pass_through path
1100 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001101 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1102 auto status = ForceUnmount(pass_through_path);
1103 if (status != android::OK) {
1104 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1105 }
Martijn Coenen57002612019-11-28 11:56:13 +01001106 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001107
1108 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001109 android::status_t result = ForceUnmount(fuse_path);
1110 sSleepOnUnmount = true;
1111 if (result != android::OK) {
1112 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1113 // Figure out why we get EBUSY and remove this special casing if possible.
1114 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1115 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1116 errno != ENOENT) {
1117 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1118 return -errno;
1119 }
Martijn Coenen57002612019-11-28 11:56:13 +01001120 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001121 }
Martijn Coenen57002612019-11-28 11:56:13 +01001122 rmdir(fuse_path.c_str());
1123
Zima438b242019-09-25 14:37:38 +01001124 return result;
Zim3623a212019-07-19 16:46:53 +01001125}
1126
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001127} // namespace vold
1128} // namespace android