blob: 5dde4b03cd40d16e9ceb5ff72dcb6b6993f8a477 [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;
Martijn Coenenba9868b2020-01-31 15:49:24 +010057using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070058using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010059using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070060using android::base::StringPrintf;
61
Jeff Sharkeydeb24052015-03-02 21:01:40 -080062namespace android {
63namespace vold {
64
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070065security_context_t sBlkidContext = nullptr;
66security_context_t sBlkidUntrustedContext = nullptr;
67security_context_t sFsckContext = nullptr;
68security_context_t sFsckUntrustedContext = nullptr;
69
Paul Crowley56292ef2017-10-20 08:07:53 -070070bool sSleepOnUnmount = true;
71
Jeff Sharkey9c484982015-03-31 10:35:33 -070072static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070073static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070074
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070075static const char* kProcFilesystems = "/proc/filesystems";
76
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060077// Lock used to protect process-level SELinux changes from racing with each
78// other between multiple threads.
79static std::mutex kSecurityLock;
80
Jeff Sharkeydeb24052015-03-02 21:01:40 -080081status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060082 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080083 const char* cpath = path.c_str();
84 status_t res = 0;
85
86 char* secontext = nullptr;
87 if (sehandle) {
88 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
89 setfscreatecon(secontext);
90 }
91 }
92
93 mode_t mode = 0660 | S_IFBLK;
94 if (mknod(cpath, mode, dev) < 0) {
95 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070096 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
97 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080098 res = -errno;
99 }
100 }
101
102 if (secontext) {
103 setfscreatecon(nullptr);
104 freecon(secontext);
105 }
106
107 return res;
108}
109
110status_t DestroyDeviceNode(const std::string& path) {
111 const char* cpath = path.c_str();
112 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
113 return -errno;
114 } else {
115 return OK;
116 }
117}
118
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100119int SetQuotaProjectId(std::string path, long projectId) {
120 struct fsxattr fsx;
121
122 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
123 if (fd == -1) {
124 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
125 return -1;
126 }
127
128 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
129 if (ret == -1) {
130 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
131 return ret;
132 }
133
134 fsx.fsx_projid = projectId;
135 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
136}
137
Martijn Coenen62a4b272020-01-31 15:23:09 +0100138int PrepareAppDirsFromRoot(std::string path, std::string root, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen13ff6682019-12-24 12:57:16 +0100139 int ret = 0;
Martijn Coenenba9868b2020-01-31 15:49:24 +0100140 bool isCacheDir = false;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100141 if (!StartsWith(path, root)) {
142 return -1;
143 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100144 // Cache directories (eg "/storage/emulated/Android/data/com.foo/cache/") need special treatment
145 isCacheDir = EndsWith(root, "/Android/data/") && EndsWith(path, "cache/");
146
Martijn Coenen13ff6682019-12-24 12:57:16 +0100147 std::string to_create_from_root = path.substr(root.length());
148
149 size_t pos = 0;
150 while ((pos = to_create_from_root.find('/')) != std::string::npos) {
151 auto component = to_create_from_root.substr(0, pos);
152 to_create_from_root.erase(0, pos + 1);
153 root = root + component + "/";
154 ret = fs_prepare_dir(root.c_str(), mode, uid, gid);
155 if (ret) {
156 break;
157 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100158 if (!IsFilesystemSupported("sdcardfs")) {
159 long projectId;
160 // All app-specific directories share the same project-ID, except
161 // the cache directory
162 if (isCacheDir && component == "cache") {
163 // Note that this also matches paths like:
164 // /Android/data/com.foo/bar/cache/
165 // This is currently safe because we're never asked to create
166 // such directories.
167 projectId = uid - AID_APP_START + AID_CACHE_GID_START;
168 } else {
169 projectId = uid - AID_APP_START + AID_EXT_GID_START;
170 }
171 ret = SetQuotaProjectId(root, projectId);
172 }
Martijn Coenen13ff6682019-12-24 12:57:16 +0100173 }
174
175 return ret;
176}
177
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700178status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600179 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700180 const char* cpath = path.c_str();
181
182 char* secontext = nullptr;
183 if (sehandle) {
184 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
185 setfscreatecon(secontext);
186 }
187 }
188
189 int res = fs_prepare_dir(cpath, mode, uid, gid);
190
191 if (secontext) {
192 setfscreatecon(nullptr);
193 freecon(secontext);
194 }
195
196 if (res == 0) {
197 return OK;
198 } else {
199 return -errno;
200 }
201}
202
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800203status_t ForceUnmount(const std::string& path) {
204 const char* cpath = path.c_str();
205 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
206 return OK;
207 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700208 // Apps might still be handling eject request, so wait before
209 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700210 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700211
Jeff Sharkey3472e522017-10-06 18:02:53 -0600212 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700213 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700214 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
215 return OK;
216 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700217
Jeff Sharkey3472e522017-10-06 18:02:53 -0600218 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700219 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800220 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
221 return OK;
222 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700223
Jeff Sharkey3472e522017-10-06 18:02:53 -0600224 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700225 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700226 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
227 return OK;
228 }
Zim3623a212019-07-19 16:46:53 +0100229 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800230 return -errno;
231}
232
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700233status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600234 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700235 return OK;
236 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700237 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700238
Jeff Sharkey3472e522017-10-06 18:02:53 -0600239 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700240 return OK;
241 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700242 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700243
Jeff Sharkey3472e522017-10-06 18:02:53 -0600244 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700245 return OK;
246 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700247 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700248
249 // Send SIGKILL a second time to determine if we've
250 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600251 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700252 return OK;
253 }
254 PLOG(ERROR) << "Failed to kill processes using " << path;
255 return -EBUSY;
256}
257
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700258status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800259 if (UnmountTree(target) < 0) {
260 return -errno;
261 }
262 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700263 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
264 return -errno;
265 }
266 return OK;
267}
268
Sudheer Shanka023b5392019-02-06 12:39:19 -0800269status_t Symlink(const std::string& target, const std::string& linkpath) {
270 if (Unlink(linkpath) < 0) {
271 return -errno;
272 }
273 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
274 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
275 return -errno;
276 }
277 return OK;
278}
279
280status_t Unlink(const std::string& linkpath) {
281 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
282 PLOG(ERROR) << "Failed to unlink " << linkpath;
283 return -errno;
284 }
285 return OK;
286}
287
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000288status_t CreateDir(const std::string& dir, mode_t mode) {
289 struct stat sb;
290 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
291 if (S_ISDIR(sb.st_mode)) {
292 return OK;
293 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
294 PLOG(ERROR) << "Failed to unlink " << dir;
295 return -errno;
296 }
297 } else if (errno != ENOENT) {
298 PLOG(ERROR) << "Failed to stat " << dir;
299 return -errno;
300 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800301 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000302 PLOG(ERROR) << "Failed to mkdir " << dir;
303 return -errno;
304 }
305 return OK;
306}
307
Jeff Sharkey3472e522017-10-06 18:02:53 -0600308bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
309 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800310 size_t start = 0;
311 while (true) {
312 start = raw.find(qual, start);
313 if (start == std::string::npos) return false;
314 if (start == 0 || raw[start - 1] == ' ') {
315 break;
316 }
317 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600318 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600319 start += qual.length();
320
321 auto end = raw.find("\"", start);
322 if (end == std::string::npos) return false;
323
324 *value = raw.substr(start, end - start);
325 return true;
326}
327
Paul Crowley14c8c072018-09-18 13:30:21 -0700328static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
329 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600330 fsType->clear();
331 fsUuid->clear();
332 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700333
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700334 std::vector<std::string> cmd;
335 cmd.push_back(kBlkidPath);
336 cmd.push_back("-c");
337 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700338 cmd.push_back("-s");
339 cmd.push_back("TYPE");
340 cmd.push_back("-s");
341 cmd.push_back("UUID");
342 cmd.push_back("-s");
343 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700344 cmd.push_back(path);
345
346 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800347 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700348 if (res != OK) {
349 LOG(WARNING) << "blkid failed to identify " << path;
350 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700351 }
352
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700353 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700354 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600355 FindValue(line, "TYPE", fsType);
356 FindValue(line, "UUID", fsUuid);
357 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700358 }
359
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700360 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700361}
362
Paul Crowley14c8c072018-09-18 13:30:21 -0700363status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
364 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700365 return readMetadata(path, fsType, fsUuid, fsLabel, false);
366}
367
Paul Crowley14c8c072018-09-18 13:30:21 -0700368status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
369 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700370 return readMetadata(path, fsType, fsUuid, fsLabel, true);
371}
372
Paul Crowleyde2d6202018-11-30 11:43:47 -0800373static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
374 std::vector<const char*> argv;
375 argv.reserve(args.size() + 1);
376 for (const auto& arg : args) {
377 if (argv.empty()) {
378 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700379 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800380 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700381 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800382 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700383 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800384 argv.emplace_back(nullptr);
385 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700386}
387
Paul Crowleyde2d6202018-11-30 11:43:47 -0800388static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
389 android::base::unique_fd ufd) {
390 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700391 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800392 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700393 return -errno;
394 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800395 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700396 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800397 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700398 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800399 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700400 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800401 return OK;
402}
403
404status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
405 security_context_t context) {
406 auto argv = ConvertToArgv(args);
407
Paul Crowleye6d76632018-11-30 11:43:47 -0800408 android::base::unique_fd pipe_read, pipe_write;
409 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
410 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800411 return -errno;
412 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800413
414 pid_t pid = fork();
415 if (pid == 0) {
416 if (context) {
417 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800418 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800419 abort();
420 }
421 }
422 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800423 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
424 PLOG(ERROR) << "dup2 in ForkExecvp";
425 _exit(EXIT_FAILURE);
426 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800427 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800428 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800429 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800430 _exit(EXIT_FAILURE);
431 }
432 if (pid == -1) {
433 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700434 return -errno;
435 }
436
Paul Crowleyde2d6202018-11-30 11:43:47 -0800437 pipe_write.reset();
438 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
439 if (st != 0) return st;
440
441 int status;
442 if (waitpid(pid, &status, 0) == -1) {
443 PLOG(ERROR) << "waitpid in ForkExecvp";
444 return -errno;
445 }
446 if (!WIFEXITED(status)) {
447 LOG(ERROR) << "Process did not exit normally, status: " << status;
448 return -ECHILD;
449 }
450 if (WEXITSTATUS(status)) {
451 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
452 return WEXITSTATUS(status);
453 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700454 return OK;
455}
456
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700457pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800458 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700459
460 pid_t pid = fork();
461 if (pid == 0) {
462 close(STDIN_FILENO);
463 close(STDOUT_FILENO);
464 close(STDERR_FILENO);
465
Paul Crowleyde2d6202018-11-30 11:43:47 -0800466 execvp(argv[0], const_cast<char**>(argv.data()));
467 PLOG(ERROR) << "exec in ForkExecvpAsync";
468 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700469 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700470 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800471 PLOG(ERROR) << "fork in ForkExecvpAsync";
472 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700473 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700474 return pid;
475}
476
Jeff Sharkey9c484982015-03-31 10:35:33 -0700477status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100478 out.resize(bytes);
479 return ReadRandomBytes(bytes, &out[0]);
480}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700481
Pavel Grafove2e2d302017-08-01 17:15:53 +0100482status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700483 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
484 if (fd == -1) {
485 return -errno;
486 }
487
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800488 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100489 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700490 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100491 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700492 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700493 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700494
495 if (bytes == 0) {
496 return OK;
497 } else {
498 return -EIO;
499 }
500}
501
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600502status_t GenerateRandomUuid(std::string& out) {
503 status_t res = ReadRandomBytes(16, out);
504 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700505 out[6] &= 0x0f; /* clear version */
506 out[6] |= 0x40; /* set to version 4 */
507 out[8] &= 0x3f; /* clear variant */
508 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600509 }
510 return res;
511}
512
Jeff Sharkey9c484982015-03-31 10:35:33 -0700513status_t HexToStr(const std::string& hex, std::string& str) {
514 str.clear();
515 bool even = true;
516 char cur = 0;
517 for (size_t i = 0; i < hex.size(); i++) {
518 int val = 0;
519 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700520 // clang-format off
521 case ' ': case '-': case ':': continue;
522 case 'f': case 'F': val = 15; break;
523 case 'e': case 'E': val = 14; break;
524 case 'd': case 'D': val = 13; break;
525 case 'c': case 'C': val = 12; break;
526 case 'b': case 'B': val = 11; break;
527 case 'a': case 'A': val = 10; break;
528 case '9': val = 9; break;
529 case '8': val = 8; break;
530 case '7': val = 7; break;
531 case '6': val = 6; break;
532 case '5': val = 5; break;
533 case '4': val = 4; break;
534 case '3': val = 3; break;
535 case '2': val = 2; break;
536 case '1': val = 1; break;
537 case '0': val = 0; break;
538 default: return -EINVAL;
539 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700540 }
541
542 if (even) {
543 cur = val << 4;
544 } else {
545 cur += val;
546 str.push_back(cur);
547 cur = 0;
548 }
549 even = !even;
550 }
551 return even ? OK : -EINVAL;
552}
553
554static const char* kLookup = "0123456789abcdef";
555
556status_t StrToHex(const std::string& str, std::string& hex) {
557 hex.clear();
558 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700559 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700560 hex.push_back(kLookup[str[i] & 0x0F]);
561 }
562 return OK;
563}
564
Pavel Grafove2e2d302017-08-01 17:15:53 +0100565status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
566 hex.clear();
567 for (size_t i = 0; i < str.size(); i++) {
568 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
569 hex.push_back(kLookup[str.data()[i] & 0x0F]);
570 }
571 return OK;
572}
573
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700574status_t NormalizeHex(const std::string& in, std::string& out) {
575 std::string tmp;
576 if (HexToStr(in, tmp)) {
577 return -EINVAL;
578 }
579 return StrToHex(tmp, out);
580}
581
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200582status_t GetBlockDevSize(int fd, uint64_t* size) {
583 if (ioctl(fd, BLKGETSIZE64, size)) {
584 return -errno;
585 }
586
587 return OK;
588}
589
590status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
591 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
592 status_t res = OK;
593
594 if (fd < 0) {
595 return -errno;
596 }
597
598 res = GetBlockDevSize(fd, size);
599
600 close(fd);
601
602 return res;
603}
604
605status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
606 uint64_t size;
607 status_t res = GetBlockDevSize(path, &size);
608
609 if (res != OK) {
610 return res;
611 }
612
613 *nr_sec = size / 512;
614
615 return OK;
616}
617
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700618uint64_t GetFreeBytes(const std::string& path) {
619 struct statvfs sb;
620 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700621 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700622 } else {
623 return -1;
624 }
625}
626
627// TODO: borrowed from frameworks/native/libs/diskusage/ which should
628// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700629static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700630 int64_t blksize = s->st_blksize;
631 // count actual blocks used instead of nominal file size
632 int64_t size = s->st_blocks * 512;
633
634 if (blksize) {
635 /* round up to filesystem block size */
636 size = (size + blksize - 1) & (~(blksize - 1));
637 }
638
639 return size;
640}
641
642// TODO: borrowed from frameworks/native/libs/diskusage/ which should
643// eventually be migrated into system/
644int64_t calculate_dir_size(int dfd) {
645 int64_t size = 0;
646 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700647 DIR* d;
648 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700649
650 d = fdopendir(dfd);
651 if (d == NULL) {
652 close(dfd);
653 return 0;
654 }
655
656 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700657 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700658 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
659 size += stat_size(&s);
660 }
661 if (de->d_type == DT_DIR) {
662 int subfd;
663
664 /* always skip "." and ".." */
665 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700666 if (name[1] == 0) continue;
667 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700668 }
669
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600670 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700671 if (subfd >= 0) {
672 size += calculate_dir_size(subfd);
673 }
674 }
675 }
676 closedir(d);
677 return size;
678}
679
680uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600681 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700682 if (dirfd < 0) {
683 PLOG(WARNING) << "Failed to open " << path;
684 return -1;
685 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700686 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700687 }
688}
689
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700690bool IsFilesystemSupported(const std::string& fsType) {
691 std::string supported;
692 if (!ReadFileToString(kProcFilesystems, &supported)) {
693 PLOG(ERROR) << "Failed to read supported filesystems";
694 return false;
695 }
696 return supported.find(fsType + "\n") != std::string::npos;
697}
698
699status_t WipeBlockDevice(const std::string& path) {
700 status_t res = -1;
701 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200702 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700703
704 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
705 if (fd == -1) {
706 PLOG(ERROR) << "Failed to open " << path;
707 goto done;
708 }
709
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200710 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700711 PLOG(ERROR) << "Failed to determine size of " << path;
712 goto done;
713 }
714
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700715 LOG(INFO) << "About to discard " << range[1] << " on " << path;
716 if (ioctl(fd, BLKDISCARD, &range) == 0) {
717 LOG(INFO) << "Discard success on " << path;
718 res = 0;
719 } else {
720 PLOG(ERROR) << "Discard failure on " << path;
721 }
722
723done:
724 close(fd);
725 return res;
726}
727
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800728static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700729 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800730 return false;
731 } else {
732 return true;
733 }
734}
735
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700736std::string BuildKeyPath(const std::string& partGuid) {
737 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
738}
739
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600740std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700741 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600742}
743
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800744std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700745 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700746}
747
748std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700749 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700750}
751
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600752std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700753 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600754}
755
Jeff Sharkey47695b22016-02-01 17:02:29 -0700756std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700757 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700758}
759
760std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700761 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800762}
763
Calin Juravle79f55a42016-02-17 20:14:46 +0000764// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
765std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700766 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000767}
768
Andreas Huber71cd43f2018-01-22 11:25:29 -0800769std::string BuildDataVendorCePath(userid_t userId) {
770 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
771}
772
773std::string BuildDataVendorDePath(userid_t userId) {
774 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
775}
776
Paul Crowley3b71fc52017-10-09 10:55:21 -0700777std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800778 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700779 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800780 return "/data";
781 } else {
782 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700783 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800784 }
785}
786
Paul Crowley3b71fc52017-10-09 10:55:21 -0700787std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700788 // TODO: unify with installd path generation logic
789 std::string data(BuildDataPath(volumeUuid));
790 return StringPrintf("%s/media/%u", data.c_str(), userId);
791}
792
Paul Crowley3b71fc52017-10-09 10:55:21 -0700793std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800794 // TODO: unify with installd path generation logic
795 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700796 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800797 std::string legacy = StringPrintf("%s/data", data.c_str());
798 struct stat sb;
799 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
800 /* /data/data is dir, return /data/data for legacy system */
801 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800802 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800803 }
cjbaoeb501142017-04-12 00:09:00 +0800804 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800805}
806
Paul Crowley3b71fc52017-10-09 10:55:21 -0700807std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800808 // TODO: unify with installd path generation logic
809 std::string data(BuildDataPath(volumeUuid));
810 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
811}
812
Jeff Sharkey66270a22015-06-24 11:49:24 -0700813dev_t GetDevice(const std::string& path) {
814 struct stat sb;
815 if (stat(path.c_str(), &sb)) {
816 PLOG(WARNING) << "Failed to stat " << path;
817 return 0;
818 } else {
819 return sb.st_dev;
820 }
821}
822
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600823status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700824 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600825
Tom Cherryd6127ef2017-06-15 17:13:56 -0700826 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600827
Tom Cherryd6127ef2017-06-15 17:13:56 -0700828 android::base::SetProperty(kRestoreconString, "");
829 android::base::SetProperty(kRestoreconString, path);
830
831 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600832
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700833 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600834 return OK;
835}
836
Jeff Sharkey3472e522017-10-06 18:02:53 -0600837bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
838 // Shamelessly borrowed from android::base::Readlink()
839 result->clear();
840
841 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
842 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
843 // waste memory to just start there. We add 1 so that we can recognize
844 // whether it actually fit (rather than being truncated to 4095).
845 std::vector<char> buf(4095 + 1);
846 while (true) {
847 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
848 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700849 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600850 // It fit! (If size == buf.size(), it may have been truncated.)
851 if (static_cast<size_t>(size) < buf.size()) {
852 result->assign(&buf[0], size);
853 return true;
854 }
855 // Double our buffer and try again.
856 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900857 }
858}
859
Yu Ning942d4e82016-01-08 17:36:47 +0800860bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700861 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800862}
863
Sudheer Shanka295fb242019-01-16 23:04:07 -0800864static status_t findMountPointsWithPrefix(const std::string& prefix,
865 std::list<std::string>& mountPoints) {
866 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
867 // when the prefix is /foo/bar
868 std::string prefixWithSlash(prefix);
869 if (prefix.back() != '/') {
870 android::base::StringAppendF(&prefixWithSlash, "/");
871 }
872
873 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
874 if (!mnts) {
875 PLOG(ERROR) << "Unable to open /proc/mounts";
876 return -errno;
877 }
878
879 // Some volumes can be stacked on each other, so force unmount in
880 // reverse order to give us the best chance of success.
881 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
882 while ((mnt = getmntent(mnts.get())) != nullptr) {
883 auto mountPoint = std::string(mnt->mnt_dir) + "/";
884 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
885 mountPoints.push_front(mountPoint);
886 }
887 }
888 return OK;
889}
890
891// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
892status_t UnmountTreeWithPrefix(const std::string& prefix) {
893 std::list<std::string> toUnmount;
894 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
895 if (result < 0) {
896 return result;
897 }
898 for (const auto& path : toUnmount) {
899 if (umount2(path.c_str(), MNT_DETACH)) {
900 PLOG(ERROR) << "Failed to unmount " << path;
901 result = -errno;
902 }
903 }
904 return result;
905}
906
907status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800908 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
909 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800910 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700911 return -errno;
912 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700913 return OK;
914}
915
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700916static status_t delete_dir_contents(DIR* dir) {
917 // Shamelessly borrowed from android::installd
918 int dfd = dirfd(dir);
919 if (dfd < 0) {
920 return -errno;
921 }
922
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800923 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700924 struct dirent* de;
925 while ((de = readdir(dir))) {
926 const char* name = de->d_name;
927 if (de->d_type == DT_DIR) {
928 /* always skip "." and ".." */
929 if (name[0] == '.') {
930 if (name[1] == 0) continue;
931 if ((name[1] == '.') && (name[2] == 0)) continue;
932 }
933
934 android::base::unique_fd subfd(
935 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
936 if (subfd.get() == -1) {
937 PLOG(ERROR) << "Couldn't openat " << name;
938 result = -errno;
939 continue;
940 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800941 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
942 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700943 if (!subdirp) {
944 PLOG(ERROR) << "Couldn't fdopendir " << name;
945 result = -errno;
946 continue;
947 }
948 result = delete_dir_contents(subdirp.get());
949 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
950 PLOG(ERROR) << "Couldn't unlinkat " << name;
951 result = -errno;
952 }
953 } else {
954 if (unlinkat(dfd, name, 0) < 0) {
955 PLOG(ERROR) << "Couldn't unlinkat " << name;
956 result = -errno;
957 }
958 }
959 }
960 return result;
961}
962
963status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800964 status_t res = DeleteDirContents(pathname);
965 if (res < 0) {
966 return res;
967 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -0800968 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800969 PLOG(ERROR) << "rmdir failed on " << pathname;
970 return -errno;
971 }
972 LOG(VERBOSE) << "Success: rmdir on " << pathname;
973 return OK;
974}
975
976status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700977 // Shamelessly borrowed from android::installd
978 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
979 if (!dirp) {
980 if (errno == ENOENT) {
981 return OK;
982 }
983 PLOG(ERROR) << "Failed to opendir " << pathname;
984 return -errno;
985 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800986 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700987}
988
Paul Crowley298fa322018-10-30 15:59:24 -0700989// TODO(118708649): fix duplication with init/util.h
990status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
991 android::base::Timer t;
992 while (t.duration() < timeout) {
993 struct stat sb;
994 if (stat(filename, &sb) != -1) {
995 LOG(INFO) << "wait for '" << filename << "' took " << t;
996 return 0;
997 }
998 std::this_thread::sleep_for(10ms);
999 }
1000 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1001 return -1;
1002}
1003
Paul Crowley621d9b92018-12-07 15:36:09 -08001004bool FsyncDirectory(const std::string& dirname) {
1005 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1006 if (fd == -1) {
1007 PLOG(ERROR) << "Failed to open " << dirname;
1008 return false;
1009 }
1010 if (fsync(fd) == -1) {
1011 if (errno == EROFS || errno == EINVAL) {
1012 PLOG(WARNING) << "Skip fsync " << dirname
1013 << " on a file system does not support synchronization";
1014 } else {
1015 PLOG(ERROR) << "Failed to fsync " << dirname;
1016 return false;
1017 }
1018 }
1019 return true;
1020}
1021
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001022bool writeStringToFile(const std::string& payload, const std::string& filename) {
1023 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1024 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1025 if (fd == -1) {
1026 PLOG(ERROR) << "Failed to open " << filename;
1027 return false;
1028 }
1029 if (!android::base::WriteStringToFd(payload, fd)) {
1030 PLOG(ERROR) << "Failed to write to " << filename;
1031 unlink(filename.c_str());
1032 return false;
1033 }
1034 // fsync as close won't guarantee flush data
1035 // see close(2), fsync(2) and b/68901441
1036 if (fsync(fd) == -1) {
1037 if (errno == EROFS || errno == EINVAL) {
1038 PLOG(WARNING) << "Skip fsync " << filename
1039 << " on a file system does not support synchronization";
1040 } else {
1041 PLOG(ERROR) << "Failed to fsync " << filename;
1042 unlink(filename.c_str());
1043 return false;
1044 }
1045 }
1046 return true;
1047}
1048
Zima438b242019-09-25 14:37:38 +01001049status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1050 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1051 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1052 std::string fuse_path(
1053 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1054
1055 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1056 std::string pass_through_path(
1057 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001058
Zim1242be82020-01-22 18:22:29 +00001059 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1060 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001061 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001062 if (result != android::OK) {
1063 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1064 return -1;
1065 }
1066
Zim06b0caf2020-01-05 02:11:47 +00001067 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1068 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1069 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1070 // These bits should be consistent with what is set in zygote in
1071 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001072 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001073 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001074 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001075 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001076 return -1;
1077 }
1078
Zima438b242019-09-25 14:37:38 +01001079 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1080 if (result != android::OK) {
1081 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1082 return -1;
1083 }
1084
Zim26eec702020-01-31 16:00:58 +00001085 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001086 if (result != android::OK) {
1087 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1088 return -1;
1089 }
1090
Zim26eec702020-01-31 16:00:58 +00001091 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001092 if (result != android::OK) {
1093 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1094 return -1;
1095 }
1096
1097 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001098 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1099 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001100 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001101 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001102 return -1;
1103 }
Zime5393d42019-11-15 11:44:12 +00001104 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001105 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001106
1107 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001108 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001109 if (result != android::OK) {
1110 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1111 return -1;
1112 }
1113 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001114 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001115 }
1116
Nandana Dutta914cc72019-08-29 15:22:42 +01001117 // Open fuse fd.
1118 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1119 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001120 PLOG(ERROR) << "Failed to open /dev/fuse";
1121 return -1;
1122 }
1123
1124 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1125 // permission checks before routing to FUSE daemon.
1126 const auto opts = StringPrintf(
1127 "fd=%i,"
1128 "rootmode=40000,"
1129 "allow_other,"
1130 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001131 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001132
Zima438b242019-09-25 14:37:38 +01001133 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1134 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1135 opts.c_str()));
1136 if (result != 0) {
1137 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001138 return -errno;
1139 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001140
Martijn Coenen86f21a22020-01-06 09:48:14 +01001141 if (IsFilesystemSupported("sdcardfs")) {
1142 std::string sdcardfs_path(
1143 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1144
1145 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1146 return BindMount(sdcardfs_path, pass_through_path);
1147 } else {
1148 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1149 return BindMount(absolute_lower_path, pass_through_path);
1150 }
Zima438b242019-09-25 14:37:38 +01001151}
1152
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001153status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1154 const std::string& relative_upper_path) {
1155 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1156 std::string pass_through_path(
1157 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1158
Zima438b242019-09-25 14:37:38 +01001159 // Best effort unmount pass_through path
1160 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001161 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1162 auto status = ForceUnmount(pass_through_path);
1163 if (status != android::OK) {
1164 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1165 }
Martijn Coenen57002612019-11-28 11:56:13 +01001166 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001167
1168 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001169 android::status_t result = ForceUnmount(fuse_path);
1170 sSleepOnUnmount = true;
1171 if (result != android::OK) {
1172 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1173 // Figure out why we get EBUSY and remove this special casing if possible.
1174 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1175 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1176 errno != ENOENT) {
1177 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1178 return -errno;
1179 }
Martijn Coenen57002612019-11-28 11:56:13 +01001180 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001181 }
Martijn Coenen57002612019-11-28 11:56:13 +01001182 rmdir(fuse_path.c_str());
1183
Zima438b242019-09-25 14:37:38 +01001184 return result;
Zim3623a212019-07-19 16:46:53 +01001185}
1186
Martijn Coenen62a4b272020-01-31 15:23:09 +01001187status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1188 std::string androidDir = volumeRoot + kAndroidDir;
1189 std::string androidDataDir = volumeRoot + kAppDataDir;
1190 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001191 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001192
1193 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1194
1195 if (fs_prepare_dir(androidDir.c_str(), 0771, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1196 PLOG(ERROR) << "Failed to create " << androidDir;
1197 return -errno;
1198 }
1199
1200 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
1201 if (fs_prepare_dir(androidDataDir.c_str(), 0771, AID_MEDIA_RW, dataGid) != 0) {
1202 PLOG(ERROR) << "Failed to create " << androidDataDir;
1203 return -errno;
1204 }
1205
1206 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
1207 if (fs_prepare_dir(androidObbDir.c_str(), 0771, AID_MEDIA_RW, obbGid) != 0) {
1208 PLOG(ERROR) << "Failed to create " << androidObbDir;
1209 return -errno;
1210 }
1211
Zima13d81b2020-02-07 16:39:31 +00001212 if (fs_prepare_dir(androidMediaDir.c_str(), 0771, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1213 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1214 return -errno;
1215 }
1216
Martijn Coenen62a4b272020-01-31 15:23:09 +01001217 return OK;
1218}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001219} // namespace vold
1220} // namespace android