blob: d5e0ca8ee4a56da5d73af13920c05825f7eab8be [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 Coenen5fe1b162020-02-06 18:57:47 +0100119int SetQuotaInherit(const std::string& path) {
120 unsigned long flags;
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 inheritance.";
125 return -1;
126 }
127
128 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
129 if (ret == -1) {
130 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
131 return ret;
132 }
133
134 flags |= FS_PROJINHERIT_FL;
135
136 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
137 if (ret == -1) {
138 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
139 return ret;
140 }
141
142 return 0;
143}
144
145int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100146 struct fsxattr fsx;
147
148 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
149 if (fd == -1) {
150 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
151 return -1;
152 }
153
154 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
155 if (ret == -1) {
156 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
157 return ret;
158 }
159
160 fsx.fsx_projid = projectId;
161 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
162}
163
Martijn Coenen62a4b272020-01-31 15:23:09 +0100164int PrepareAppDirsFromRoot(std::string path, std::string root, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen13ff6682019-12-24 12:57:16 +0100165 int ret = 0;
Martijn Coenenba9868b2020-01-31 15:49:24 +0100166 bool isCacheDir = false;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100167 if (!StartsWith(path, root)) {
168 return -1;
169 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100170 // Cache directories (eg "/storage/emulated/Android/data/com.foo/cache/") need special treatment
171 isCacheDir = EndsWith(root, "/Android/data/") && EndsWith(path, "cache/");
172
Martijn Coenen13ff6682019-12-24 12:57:16 +0100173 std::string to_create_from_root = path.substr(root.length());
174
175 size_t pos = 0;
176 while ((pos = to_create_from_root.find('/')) != std::string::npos) {
177 auto component = to_create_from_root.substr(0, pos);
178 to_create_from_root.erase(0, pos + 1);
179 root = root + component + "/";
180 ret = fs_prepare_dir(root.c_str(), mode, uid, gid);
181 if (ret) {
182 break;
183 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100184 if (!IsFilesystemSupported("sdcardfs")) {
185 long projectId;
186 // All app-specific directories share the same project-ID, except
187 // the cache directory
188 if (isCacheDir && component == "cache") {
189 // Note that this also matches paths like:
190 // /Android/data/com.foo/bar/cache/
191 // This is currently safe because we're never asked to create
192 // such directories.
193 projectId = uid - AID_APP_START + AID_CACHE_GID_START;
194 } else {
195 projectId = uid - AID_APP_START + AID_EXT_GID_START;
196 }
197 ret = SetQuotaProjectId(root, projectId);
198 }
Martijn Coenen13ff6682019-12-24 12:57:16 +0100199 }
200
201 return ret;
202}
203
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700204status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600205 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700206 const char* cpath = path.c_str();
207
208 char* secontext = nullptr;
209 if (sehandle) {
210 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
211 setfscreatecon(secontext);
212 }
213 }
214
215 int res = fs_prepare_dir(cpath, mode, uid, gid);
216
217 if (secontext) {
218 setfscreatecon(nullptr);
219 freecon(secontext);
220 }
221
222 if (res == 0) {
223 return OK;
224 } else {
225 return -errno;
226 }
227}
228
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800229status_t ForceUnmount(const std::string& path) {
230 const char* cpath = path.c_str();
231 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
232 return OK;
233 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700234 // Apps might still be handling eject request, so wait before
235 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700236 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700237
Jeff Sharkey3472e522017-10-06 18:02:53 -0600238 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700239 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700240 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
241 return OK;
242 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700243
Jeff Sharkey3472e522017-10-06 18:02:53 -0600244 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700245 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800246 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
247 return OK;
248 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700249
Jeff Sharkey3472e522017-10-06 18:02:53 -0600250 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700251 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700252 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
253 return OK;
254 }
Zim3623a212019-07-19 16:46:53 +0100255 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800256 return -errno;
257}
258
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700259status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600260 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700261 return OK;
262 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700263 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700264
Jeff Sharkey3472e522017-10-06 18:02:53 -0600265 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700266 return OK;
267 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700268 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700269
Jeff Sharkey3472e522017-10-06 18:02:53 -0600270 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700271 return OK;
272 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700273 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700274
275 // Send SIGKILL a second time to determine if we've
276 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600277 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700278 return OK;
279 }
280 PLOG(ERROR) << "Failed to kill processes using " << path;
281 return -EBUSY;
282}
283
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700284status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800285 if (UnmountTree(target) < 0) {
286 return -errno;
287 }
288 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700289 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
290 return -errno;
291 }
292 return OK;
293}
294
Sudheer Shanka023b5392019-02-06 12:39:19 -0800295status_t Symlink(const std::string& target, const std::string& linkpath) {
296 if (Unlink(linkpath) < 0) {
297 return -errno;
298 }
299 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
300 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
301 return -errno;
302 }
303 return OK;
304}
305
306status_t Unlink(const std::string& linkpath) {
307 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
308 PLOG(ERROR) << "Failed to unlink " << linkpath;
309 return -errno;
310 }
311 return OK;
312}
313
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000314status_t CreateDir(const std::string& dir, mode_t mode) {
315 struct stat sb;
316 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
317 if (S_ISDIR(sb.st_mode)) {
318 return OK;
319 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
320 PLOG(ERROR) << "Failed to unlink " << dir;
321 return -errno;
322 }
323 } else if (errno != ENOENT) {
324 PLOG(ERROR) << "Failed to stat " << dir;
325 return -errno;
326 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800327 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000328 PLOG(ERROR) << "Failed to mkdir " << dir;
329 return -errno;
330 }
331 return OK;
332}
333
Jeff Sharkey3472e522017-10-06 18:02:53 -0600334bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
335 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800336 size_t start = 0;
337 while (true) {
338 start = raw.find(qual, start);
339 if (start == std::string::npos) return false;
340 if (start == 0 || raw[start - 1] == ' ') {
341 break;
342 }
343 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600344 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600345 start += qual.length();
346
347 auto end = raw.find("\"", start);
348 if (end == std::string::npos) return false;
349
350 *value = raw.substr(start, end - start);
351 return true;
352}
353
Paul Crowley14c8c072018-09-18 13:30:21 -0700354static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
355 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600356 fsType->clear();
357 fsUuid->clear();
358 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700359
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700360 std::vector<std::string> cmd;
361 cmd.push_back(kBlkidPath);
362 cmd.push_back("-c");
363 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700364 cmd.push_back("-s");
365 cmd.push_back("TYPE");
366 cmd.push_back("-s");
367 cmd.push_back("UUID");
368 cmd.push_back("-s");
369 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700370 cmd.push_back(path);
371
372 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800373 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700374 if (res != OK) {
375 LOG(WARNING) << "blkid failed to identify " << path;
376 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700377 }
378
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700379 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700380 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600381 FindValue(line, "TYPE", fsType);
382 FindValue(line, "UUID", fsUuid);
383 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700384 }
385
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700386 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700387}
388
Paul Crowley14c8c072018-09-18 13:30:21 -0700389status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
390 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700391 return readMetadata(path, fsType, fsUuid, fsLabel, false);
392}
393
Paul Crowley14c8c072018-09-18 13:30:21 -0700394status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
395 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700396 return readMetadata(path, fsType, fsUuid, fsLabel, true);
397}
398
Paul Crowleyde2d6202018-11-30 11:43:47 -0800399static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
400 std::vector<const char*> argv;
401 argv.reserve(args.size() + 1);
402 for (const auto& arg : args) {
403 if (argv.empty()) {
404 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700405 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800406 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700407 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800408 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700409 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800410 argv.emplace_back(nullptr);
411 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700412}
413
Paul Crowleyde2d6202018-11-30 11:43:47 -0800414static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
415 android::base::unique_fd ufd) {
416 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700417 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800418 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700419 return -errno;
420 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800421 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700422 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800423 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700424 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800425 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700426 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800427 return OK;
428}
429
430status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
431 security_context_t context) {
432 auto argv = ConvertToArgv(args);
433
Paul Crowleye6d76632018-11-30 11:43:47 -0800434 android::base::unique_fd pipe_read, pipe_write;
435 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
436 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800437 return -errno;
438 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800439
440 pid_t pid = fork();
441 if (pid == 0) {
442 if (context) {
443 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800444 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800445 abort();
446 }
447 }
448 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800449 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
450 PLOG(ERROR) << "dup2 in ForkExecvp";
451 _exit(EXIT_FAILURE);
452 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800453 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800454 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800455 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800456 _exit(EXIT_FAILURE);
457 }
458 if (pid == -1) {
459 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700460 return -errno;
461 }
462
Paul Crowleyde2d6202018-11-30 11:43:47 -0800463 pipe_write.reset();
464 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
465 if (st != 0) return st;
466
467 int status;
468 if (waitpid(pid, &status, 0) == -1) {
469 PLOG(ERROR) << "waitpid in ForkExecvp";
470 return -errno;
471 }
472 if (!WIFEXITED(status)) {
473 LOG(ERROR) << "Process did not exit normally, status: " << status;
474 return -ECHILD;
475 }
476 if (WEXITSTATUS(status)) {
477 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
478 return WEXITSTATUS(status);
479 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700480 return OK;
481}
482
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700483pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800484 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700485
486 pid_t pid = fork();
487 if (pid == 0) {
488 close(STDIN_FILENO);
489 close(STDOUT_FILENO);
490 close(STDERR_FILENO);
491
Paul Crowleyde2d6202018-11-30 11:43:47 -0800492 execvp(argv[0], const_cast<char**>(argv.data()));
493 PLOG(ERROR) << "exec in ForkExecvpAsync";
494 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700495 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700496 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800497 PLOG(ERROR) << "fork in ForkExecvpAsync";
498 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700499 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700500 return pid;
501}
502
Jeff Sharkey9c484982015-03-31 10:35:33 -0700503status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100504 out.resize(bytes);
505 return ReadRandomBytes(bytes, &out[0]);
506}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700507
Pavel Grafove2e2d302017-08-01 17:15:53 +0100508status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700509 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
510 if (fd == -1) {
511 return -errno;
512 }
513
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800514 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100515 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700516 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100517 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700518 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700519 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700520
521 if (bytes == 0) {
522 return OK;
523 } else {
524 return -EIO;
525 }
526}
527
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600528status_t GenerateRandomUuid(std::string& out) {
529 status_t res = ReadRandomBytes(16, out);
530 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700531 out[6] &= 0x0f; /* clear version */
532 out[6] |= 0x40; /* set to version 4 */
533 out[8] &= 0x3f; /* clear variant */
534 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600535 }
536 return res;
537}
538
Jeff Sharkey9c484982015-03-31 10:35:33 -0700539status_t HexToStr(const std::string& hex, std::string& str) {
540 str.clear();
541 bool even = true;
542 char cur = 0;
543 for (size_t i = 0; i < hex.size(); i++) {
544 int val = 0;
545 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700546 // clang-format off
547 case ' ': case '-': case ':': continue;
548 case 'f': case 'F': val = 15; break;
549 case 'e': case 'E': val = 14; break;
550 case 'd': case 'D': val = 13; break;
551 case 'c': case 'C': val = 12; break;
552 case 'b': case 'B': val = 11; break;
553 case 'a': case 'A': val = 10; break;
554 case '9': val = 9; break;
555 case '8': val = 8; break;
556 case '7': val = 7; break;
557 case '6': val = 6; break;
558 case '5': val = 5; break;
559 case '4': val = 4; break;
560 case '3': val = 3; break;
561 case '2': val = 2; break;
562 case '1': val = 1; break;
563 case '0': val = 0; break;
564 default: return -EINVAL;
565 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700566 }
567
568 if (even) {
569 cur = val << 4;
570 } else {
571 cur += val;
572 str.push_back(cur);
573 cur = 0;
574 }
575 even = !even;
576 }
577 return even ? OK : -EINVAL;
578}
579
580static const char* kLookup = "0123456789abcdef";
581
582status_t StrToHex(const std::string& str, std::string& hex) {
583 hex.clear();
584 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700585 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700586 hex.push_back(kLookup[str[i] & 0x0F]);
587 }
588 return OK;
589}
590
Pavel Grafove2e2d302017-08-01 17:15:53 +0100591status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
592 hex.clear();
593 for (size_t i = 0; i < str.size(); i++) {
594 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
595 hex.push_back(kLookup[str.data()[i] & 0x0F]);
596 }
597 return OK;
598}
599
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700600status_t NormalizeHex(const std::string& in, std::string& out) {
601 std::string tmp;
602 if (HexToStr(in, tmp)) {
603 return -EINVAL;
604 }
605 return StrToHex(tmp, out);
606}
607
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200608status_t GetBlockDevSize(int fd, uint64_t* size) {
609 if (ioctl(fd, BLKGETSIZE64, size)) {
610 return -errno;
611 }
612
613 return OK;
614}
615
616status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
617 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
618 status_t res = OK;
619
620 if (fd < 0) {
621 return -errno;
622 }
623
624 res = GetBlockDevSize(fd, size);
625
626 close(fd);
627
628 return res;
629}
630
631status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
632 uint64_t size;
633 status_t res = GetBlockDevSize(path, &size);
634
635 if (res != OK) {
636 return res;
637 }
638
639 *nr_sec = size / 512;
640
641 return OK;
642}
643
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700644uint64_t GetFreeBytes(const std::string& path) {
645 struct statvfs sb;
646 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700647 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700648 } else {
649 return -1;
650 }
651}
652
653// TODO: borrowed from frameworks/native/libs/diskusage/ which should
654// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700655static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700656 int64_t blksize = s->st_blksize;
657 // count actual blocks used instead of nominal file size
658 int64_t size = s->st_blocks * 512;
659
660 if (blksize) {
661 /* round up to filesystem block size */
662 size = (size + blksize - 1) & (~(blksize - 1));
663 }
664
665 return size;
666}
667
668// TODO: borrowed from frameworks/native/libs/diskusage/ which should
669// eventually be migrated into system/
670int64_t calculate_dir_size(int dfd) {
671 int64_t size = 0;
672 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700673 DIR* d;
674 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700675
676 d = fdopendir(dfd);
677 if (d == NULL) {
678 close(dfd);
679 return 0;
680 }
681
682 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700683 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700684 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
685 size += stat_size(&s);
686 }
687 if (de->d_type == DT_DIR) {
688 int subfd;
689
690 /* always skip "." and ".." */
691 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700692 if (name[1] == 0) continue;
693 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700694 }
695
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600696 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700697 if (subfd >= 0) {
698 size += calculate_dir_size(subfd);
699 }
700 }
701 }
702 closedir(d);
703 return size;
704}
705
706uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600707 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700708 if (dirfd < 0) {
709 PLOG(WARNING) << "Failed to open " << path;
710 return -1;
711 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700712 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700713 }
714}
715
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700716bool IsFilesystemSupported(const std::string& fsType) {
717 std::string supported;
718 if (!ReadFileToString(kProcFilesystems, &supported)) {
719 PLOG(ERROR) << "Failed to read supported filesystems";
720 return false;
721 }
722 return supported.find(fsType + "\n") != std::string::npos;
723}
724
725status_t WipeBlockDevice(const std::string& path) {
726 status_t res = -1;
727 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200728 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700729
730 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
731 if (fd == -1) {
732 PLOG(ERROR) << "Failed to open " << path;
733 goto done;
734 }
735
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200736 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700737 PLOG(ERROR) << "Failed to determine size of " << path;
738 goto done;
739 }
740
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700741 LOG(INFO) << "About to discard " << range[1] << " on " << path;
742 if (ioctl(fd, BLKDISCARD, &range) == 0) {
743 LOG(INFO) << "Discard success on " << path;
744 res = 0;
745 } else {
746 PLOG(ERROR) << "Discard failure on " << path;
747 }
748
749done:
750 close(fd);
751 return res;
752}
753
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800754static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700755 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800756 return false;
757 } else {
758 return true;
759 }
760}
761
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700762std::string BuildKeyPath(const std::string& partGuid) {
763 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
764}
765
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600766std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700767 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600768}
769
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800770std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700771 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700772}
773
774std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700775 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700776}
777
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600778std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700779 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600780}
781
Jeff Sharkey47695b22016-02-01 17:02:29 -0700782std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700783 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700784}
785
786std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700787 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800788}
789
Calin Juravle79f55a42016-02-17 20:14:46 +0000790// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
791std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700792 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000793}
794
Andreas Huber71cd43f2018-01-22 11:25:29 -0800795std::string BuildDataVendorCePath(userid_t userId) {
796 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
797}
798
799std::string BuildDataVendorDePath(userid_t userId) {
800 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
801}
802
Paul Crowley3b71fc52017-10-09 10:55:21 -0700803std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800804 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700805 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800806 return "/data";
807 } else {
808 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700809 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800810 }
811}
812
Paul Crowley3b71fc52017-10-09 10:55:21 -0700813std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700814 // TODO: unify with installd path generation logic
815 std::string data(BuildDataPath(volumeUuid));
816 return StringPrintf("%s/media/%u", data.c_str(), userId);
817}
818
Paul Crowley3b71fc52017-10-09 10:55:21 -0700819std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800820 // TODO: unify with installd path generation logic
821 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700822 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800823 std::string legacy = StringPrintf("%s/data", data.c_str());
824 struct stat sb;
825 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
826 /* /data/data is dir, return /data/data for legacy system */
827 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800828 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800829 }
cjbaoeb501142017-04-12 00:09:00 +0800830 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800831}
832
Paul Crowley3b71fc52017-10-09 10:55:21 -0700833std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800834 // TODO: unify with installd path generation logic
835 std::string data(BuildDataPath(volumeUuid));
836 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
837}
838
Jeff Sharkey66270a22015-06-24 11:49:24 -0700839dev_t GetDevice(const std::string& path) {
840 struct stat sb;
841 if (stat(path.c_str(), &sb)) {
842 PLOG(WARNING) << "Failed to stat " << path;
843 return 0;
844 } else {
845 return sb.st_dev;
846 }
847}
848
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600849status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700850 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600851
Tom Cherryd6127ef2017-06-15 17:13:56 -0700852 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600853
Tom Cherryd6127ef2017-06-15 17:13:56 -0700854 android::base::SetProperty(kRestoreconString, "");
855 android::base::SetProperty(kRestoreconString, path);
856
857 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600858
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700859 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600860 return OK;
861}
862
Jeff Sharkey3472e522017-10-06 18:02:53 -0600863bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
864 // Shamelessly borrowed from android::base::Readlink()
865 result->clear();
866
867 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
868 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
869 // waste memory to just start there. We add 1 so that we can recognize
870 // whether it actually fit (rather than being truncated to 4095).
871 std::vector<char> buf(4095 + 1);
872 while (true) {
873 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
874 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700875 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600876 // It fit! (If size == buf.size(), it may have been truncated.)
877 if (static_cast<size_t>(size) < buf.size()) {
878 result->assign(&buf[0], size);
879 return true;
880 }
881 // Double our buffer and try again.
882 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900883 }
884}
885
Yu Ning942d4e82016-01-08 17:36:47 +0800886bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700887 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800888}
889
Sudheer Shanka295fb242019-01-16 23:04:07 -0800890static status_t findMountPointsWithPrefix(const std::string& prefix,
891 std::list<std::string>& mountPoints) {
892 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
893 // when the prefix is /foo/bar
894 std::string prefixWithSlash(prefix);
895 if (prefix.back() != '/') {
896 android::base::StringAppendF(&prefixWithSlash, "/");
897 }
898
899 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
900 if (!mnts) {
901 PLOG(ERROR) << "Unable to open /proc/mounts";
902 return -errno;
903 }
904
905 // Some volumes can be stacked on each other, so force unmount in
906 // reverse order to give us the best chance of success.
907 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
908 while ((mnt = getmntent(mnts.get())) != nullptr) {
909 auto mountPoint = std::string(mnt->mnt_dir) + "/";
910 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
911 mountPoints.push_front(mountPoint);
912 }
913 }
914 return OK;
915}
916
917// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
918status_t UnmountTreeWithPrefix(const std::string& prefix) {
919 std::list<std::string> toUnmount;
920 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
921 if (result < 0) {
922 return result;
923 }
924 for (const auto& path : toUnmount) {
925 if (umount2(path.c_str(), MNT_DETACH)) {
926 PLOG(ERROR) << "Failed to unmount " << path;
927 result = -errno;
928 }
929 }
930 return result;
931}
932
933status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800934 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
935 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800936 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700937 return -errno;
938 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700939 return OK;
940}
941
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700942static status_t delete_dir_contents(DIR* dir) {
943 // Shamelessly borrowed from android::installd
944 int dfd = dirfd(dir);
945 if (dfd < 0) {
946 return -errno;
947 }
948
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800949 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700950 struct dirent* de;
951 while ((de = readdir(dir))) {
952 const char* name = de->d_name;
953 if (de->d_type == DT_DIR) {
954 /* always skip "." and ".." */
955 if (name[0] == '.') {
956 if (name[1] == 0) continue;
957 if ((name[1] == '.') && (name[2] == 0)) continue;
958 }
959
960 android::base::unique_fd subfd(
961 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
962 if (subfd.get() == -1) {
963 PLOG(ERROR) << "Couldn't openat " << name;
964 result = -errno;
965 continue;
966 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800967 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
968 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700969 if (!subdirp) {
970 PLOG(ERROR) << "Couldn't fdopendir " << name;
971 result = -errno;
972 continue;
973 }
974 result = delete_dir_contents(subdirp.get());
975 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
976 PLOG(ERROR) << "Couldn't unlinkat " << name;
977 result = -errno;
978 }
979 } else {
980 if (unlinkat(dfd, name, 0) < 0) {
981 PLOG(ERROR) << "Couldn't unlinkat " << name;
982 result = -errno;
983 }
984 }
985 }
986 return result;
987}
988
989status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800990 status_t res = DeleteDirContents(pathname);
991 if (res < 0) {
992 return res;
993 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -0800994 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800995 PLOG(ERROR) << "rmdir failed on " << pathname;
996 return -errno;
997 }
998 LOG(VERBOSE) << "Success: rmdir on " << pathname;
999 return OK;
1000}
1001
1002status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001003 // Shamelessly borrowed from android::installd
1004 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1005 if (!dirp) {
1006 if (errno == ENOENT) {
1007 return OK;
1008 }
1009 PLOG(ERROR) << "Failed to opendir " << pathname;
1010 return -errno;
1011 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001012 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001013}
1014
Paul Crowley298fa322018-10-30 15:59:24 -07001015// TODO(118708649): fix duplication with init/util.h
1016status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1017 android::base::Timer t;
1018 while (t.duration() < timeout) {
1019 struct stat sb;
1020 if (stat(filename, &sb) != -1) {
1021 LOG(INFO) << "wait for '" << filename << "' took " << t;
1022 return 0;
1023 }
1024 std::this_thread::sleep_for(10ms);
1025 }
1026 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1027 return -1;
1028}
1029
Paul Crowley621d9b92018-12-07 15:36:09 -08001030bool FsyncDirectory(const std::string& dirname) {
1031 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1032 if (fd == -1) {
1033 PLOG(ERROR) << "Failed to open " << dirname;
1034 return false;
1035 }
1036 if (fsync(fd) == -1) {
1037 if (errno == EROFS || errno == EINVAL) {
1038 PLOG(WARNING) << "Skip fsync " << dirname
1039 << " on a file system does not support synchronization";
1040 } else {
1041 PLOG(ERROR) << "Failed to fsync " << dirname;
1042 return false;
1043 }
1044 }
1045 return true;
1046}
1047
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001048bool writeStringToFile(const std::string& payload, const std::string& filename) {
1049 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1050 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1051 if (fd == -1) {
1052 PLOG(ERROR) << "Failed to open " << filename;
1053 return false;
1054 }
1055 if (!android::base::WriteStringToFd(payload, fd)) {
1056 PLOG(ERROR) << "Failed to write to " << filename;
1057 unlink(filename.c_str());
1058 return false;
1059 }
1060 // fsync as close won't guarantee flush data
1061 // see close(2), fsync(2) and b/68901441
1062 if (fsync(fd) == -1) {
1063 if (errno == EROFS || errno == EINVAL) {
1064 PLOG(WARNING) << "Skip fsync " << filename
1065 << " on a file system does not support synchronization";
1066 } else {
1067 PLOG(ERROR) << "Failed to fsync " << filename;
1068 unlink(filename.c_str());
1069 return false;
1070 }
1071 }
1072 return true;
1073}
1074
Zima438b242019-09-25 14:37:38 +01001075status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1076 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1077 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1078 std::string fuse_path(
1079 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1080
1081 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1082 std::string pass_through_path(
1083 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001084
Zim1242be82020-01-22 18:22:29 +00001085 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1086 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001087 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001088 if (result != android::OK) {
1089 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1090 return -1;
1091 }
1092
Zim06b0caf2020-01-05 02:11:47 +00001093 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1094 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1095 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1096 // These bits should be consistent with what is set in zygote in
1097 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001098 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001099 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001100 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001101 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001102 return -1;
1103 }
1104
Zima438b242019-09-25 14:37:38 +01001105 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1106 if (result != android::OK) {
1107 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1108 return -1;
1109 }
1110
Zim26eec702020-01-31 16:00:58 +00001111 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001112 if (result != android::OK) {
1113 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1114 return -1;
1115 }
1116
Zim26eec702020-01-31 16:00:58 +00001117 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001118 if (result != android::OK) {
1119 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1120 return -1;
1121 }
1122
1123 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001124 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1125 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001126 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001127 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001128 return -1;
1129 }
Zime5393d42019-11-15 11:44:12 +00001130 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001131 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001132
1133 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001134 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001135 if (result != android::OK) {
1136 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1137 return -1;
1138 }
1139 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001140 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001141 }
1142
Nandana Dutta914cc72019-08-29 15:22:42 +01001143 // Open fuse fd.
1144 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1145 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001146 PLOG(ERROR) << "Failed to open /dev/fuse";
1147 return -1;
1148 }
1149
1150 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1151 // permission checks before routing to FUSE daemon.
1152 const auto opts = StringPrintf(
1153 "fd=%i,"
1154 "rootmode=40000,"
1155 "allow_other,"
1156 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001157 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001158
Zima438b242019-09-25 14:37:38 +01001159 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1160 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1161 opts.c_str()));
1162 if (result != 0) {
1163 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001164 return -errno;
1165 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001166
Martijn Coenen86f21a22020-01-06 09:48:14 +01001167 if (IsFilesystemSupported("sdcardfs")) {
1168 std::string sdcardfs_path(
1169 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1170
1171 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1172 return BindMount(sdcardfs_path, pass_through_path);
1173 } else {
1174 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1175 return BindMount(absolute_lower_path, pass_through_path);
1176 }
Zima438b242019-09-25 14:37:38 +01001177}
1178
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001179status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1180 const std::string& relative_upper_path) {
1181 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1182 std::string pass_through_path(
1183 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1184
Zima438b242019-09-25 14:37:38 +01001185 // Best effort unmount pass_through path
1186 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001187 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1188 auto status = ForceUnmount(pass_through_path);
1189 if (status != android::OK) {
1190 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1191 }
Martijn Coenen57002612019-11-28 11:56:13 +01001192 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001193
1194 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001195 android::status_t result = ForceUnmount(fuse_path);
1196 sSleepOnUnmount = true;
1197 if (result != android::OK) {
1198 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1199 // Figure out why we get EBUSY and remove this special casing if possible.
1200 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1201 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1202 errno != ENOENT) {
1203 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1204 return -errno;
1205 }
Martijn Coenen57002612019-11-28 11:56:13 +01001206 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001207 }
Martijn Coenen57002612019-11-28 11:56:13 +01001208 rmdir(fuse_path.c_str());
1209
Zima438b242019-09-25 14:37:38 +01001210 return result;
Zim3623a212019-07-19 16:46:53 +01001211}
1212
Martijn Coenen62a4b272020-01-31 15:23:09 +01001213status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1214 std::string androidDir = volumeRoot + kAndroidDir;
1215 std::string androidDataDir = volumeRoot + kAppDataDir;
1216 std::string androidObbDir = volumeRoot + kAppObbDir;
1217
1218 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1219
1220 if (fs_prepare_dir(androidDir.c_str(), 0771, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1221 PLOG(ERROR) << "Failed to create " << androidDir;
1222 return -errno;
1223 }
1224
1225 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
1226 if (fs_prepare_dir(androidDataDir.c_str(), 0771, AID_MEDIA_RW, dataGid) != 0) {
1227 PLOG(ERROR) << "Failed to create " << androidDataDir;
1228 return -errno;
1229 }
1230
1231 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
1232 if (fs_prepare_dir(androidObbDir.c_str(), 0771, AID_MEDIA_RW, obbGid) != 0) {
1233 PLOG(ERROR) << "Failed to create " << androidObbDir;
1234 return -errno;
1235 }
1236
1237 return OK;
1238}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001239} // namespace vold
1240} // namespace android