blob: 6208efd1680edd13c038d01f3ad455f05426285f [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>
Martijn Coenenaee40512020-02-18 16:29:25 +010032#include <private/android_projectid_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080033
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070034#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080035#include <fcntl.h>
36#include <linux/fs.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010037#include <linux/posix_acl.h>
38#include <linux/posix_acl_xattr.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070039#include <mntent.h>
40#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080041#include <stdlib.h>
42#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080043#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070044#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070045#include <sys/sysmacros.h>
46#include <sys/types.h>
47#include <sys/wait.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010048#include <sys/xattr.h>
Paul Crowley747b4212019-04-05 04:09:57 -070049#include <unistd.h>
Paul Crowley298fa322018-10-30 15:59:24 -070050
Martijn Coenen816f4d92020-02-18 15:06:37 +010051#include <filesystem>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070052#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070053#include <mutex>
Martijn Coenen04bb17f2020-02-10 23:48:11 +010054#include <regex>
Paul Crowley298fa322018-10-30 15:59:24 -070055#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080056
57#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070058#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080059#endif
60
Paul Crowley298fa322018-10-30 15:59:24 -070061using namespace std::chrono_literals;
Martijn Coenenba9868b2020-01-31 15:49:24 +010062using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070063using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010064using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070065using android::base::StringPrintf;
Nikita Ioffedcee5c12020-06-12 12:59:45 +010066using android::base::unique_fd;
Jeff Sharkey9c484982015-03-31 10:35:33 -070067
Jeff Sharkeydeb24052015-03-02 21:01:40 -080068namespace android {
69namespace vold {
70
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070071security_context_t sBlkidContext = nullptr;
72security_context_t sBlkidUntrustedContext = nullptr;
73security_context_t sFsckContext = nullptr;
74security_context_t sFsckUntrustedContext = nullptr;
75
Paul Crowley56292ef2017-10-20 08:07:53 -070076bool sSleepOnUnmount = true;
77
Jeff Sharkey9c484982015-03-31 10:35:33 -070078static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070079static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070080
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070081static const char* kProcDevices = "/proc/devices";
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070082static const char* kProcFilesystems = "/proc/filesystems";
83
Martijn Coenen04bb17f2020-02-10 23:48:11 +010084static const char* kAndroidDir = "/Android/";
85static const char* kAppDataDir = "/Android/data/";
86static const char* kAppMediaDir = "/Android/media/";
87static const char* kAppObbDir = "/Android/obb/";
88
Ricky Wai07e64a42020-02-11 14:31:24 +000089static const char* kMediaProviderCtx = "u:r:mediaprovider:";
90static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
91
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060092// Lock used to protect process-level SELinux changes from racing with each
93// other between multiple threads.
94static std::mutex kSecurityLock;
95
Nikita Ioffedcee5c12020-06-12 12:59:45 +010096std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path) {
97 return StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str());
98}
99
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800100status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600101 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800102 const char* cpath = path.c_str();
103 status_t res = 0;
104
105 char* secontext = nullptr;
106 if (sehandle) {
107 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
108 setfscreatecon(secontext);
109 }
110 }
111
112 mode_t mode = 0660 | S_IFBLK;
113 if (mknod(cpath, mode, dev) < 0) {
114 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700115 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
116 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800117 res = -errno;
118 }
119 }
120
121 if (secontext) {
122 setfscreatecon(nullptr);
123 freecon(secontext);
124 }
125
126 return res;
127}
128
129status_t DestroyDeviceNode(const std::string& path) {
130 const char* cpath = path.c_str();
131 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
132 return -errno;
133 } else {
134 return OK;
135 }
136}
137
Martijn Coenen442bb832020-02-18 13:44:59 +0100138// Sets a default ACL on the directory.
Martijn Coenen1129b812020-06-16 14:58:52 +0200139int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
140 std::vector<gid_t> additionalGids) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700141 if (IsSdcardfsUsed()) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100142 // sdcardfs magically takes care of this
143 return OK;
144 }
145
Martijn Coenen1129b812020-06-16 14:58:52 +0200146 size_t num_entries = 3 + (additionalGids.size() > 0 ? additionalGids.size() + 1 : 0);
147 size_t size = sizeof(posix_acl_xattr_header) + num_entries * sizeof(posix_acl_xattr_entry);
Martijn Coenen879fa802020-02-11 12:37:25 +0100148 auto buf = std::make_unique<uint8_t[]>(size);
149
150 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
151 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
152
153 posix_acl_xattr_entry* entry =
154 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
155
Martijn Coenen1129b812020-06-16 14:58:52 +0200156 int tag_index = 0;
157
158 entry[tag_index].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100159 // The existing mode_t mask has the ACL in the lower 9 bits:
160 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
161 // Use the mode_t masks to get these bits out, and shift them to get the
162 // correct value per entity.
163 //
164 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
Martijn Coenen1129b812020-06-16 14:58:52 +0200165 entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
166 entry[tag_index].e_id = uid;
167 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100168
Martijn Coenen1129b812020-06-16 14:58:52 +0200169 entry[tag_index].e_tag = ACL_GROUP_OBJ;
170 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
171 entry[tag_index].e_id = gid;
172 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100173
Martijn Coenen1129b812020-06-16 14:58:52 +0200174 if (additionalGids.size() > 0) {
175 for (gid_t additional_gid : additionalGids) {
176 entry[tag_index].e_tag = ACL_GROUP;
177 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
178 entry[tag_index].e_id = additional_gid;
179 tag_index++;
180 }
181
182 entry[tag_index].e_tag = ACL_MASK;
183 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
184 entry[tag_index].e_id = 0;
185 tag_index++;
186 }
187
188 entry[tag_index].e_tag = ACL_OTHER;
189 entry[tag_index].e_perm = mode & S_IRWXO;
190 entry[tag_index].e_id = 0;
Martijn Coenen879fa802020-02-11 12:37:25 +0100191
192 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
193
194 if (ret != 0) {
195 PLOG(ERROR) << "Failed to set default ACL on " << path;
196 }
197
198 return ret;
199}
200
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100201int SetQuotaInherit(const std::string& path) {
202 unsigned long flags;
203
204 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
205 if (fd == -1) {
206 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
207 return -1;
208 }
209
210 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
211 if (ret == -1) {
212 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
213 return ret;
214 }
215
216 flags |= FS_PROJINHERIT_FL;
217
218 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
219 if (ret == -1) {
220 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
221 return ret;
222 }
223
224 return 0;
225}
226
227int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100228 struct fsxattr fsx;
229
230 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
231 if (fd == -1) {
232 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
233 return -1;
234 }
235
236 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
237 if (ret == -1) {
238 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
239 return ret;
240 }
241
242 fsx.fsx_projid = projectId;
243 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
244}
245
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100246int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
247 long projectId) {
248 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
249
250 if (ret != 0) {
251 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100252 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100253
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700254 if (!IsSdcardfsUsed()) {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100255 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100256 }
257
258 return ret;
259}
260
Martijn Coenen816f4d92020-02-18 15:06:37 +0100261static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
262 namespace fs = std::filesystem;
263
264 // Setup the directory itself correctly
265 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
266 if (ret != OK) {
267 return ret;
268 }
269
270 // Fixup all of its file entries
271 for (const auto& itEntry : fs::directory_iterator(path)) {
272 ret = lchown(itEntry.path().c_str(), uid, gid);
273 if (ret != 0) {
274 return ret;
275 }
276
277 ret = chmod(itEntry.path().c_str(), mode);
278 if (ret != 0) {
279 return ret;
280 }
281
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700282 if (!IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +0100283 ret = SetQuotaProjectId(itEntry.path(), projectId);
284 if (ret != 0) {
285 return ret;
286 }
287 }
288 }
289
290 return OK;
291}
292
293int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
294 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100295 long projectId;
296 size_t pos;
297 int ret = 0;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700298 bool sdcardfsSupport = IsSdcardfsUsed();
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100299
300 // Make sure the Android/ directories exist and are setup correctly
301 ret = PrepareAndroidDirs(root);
302 if (ret != 0) {
303 LOG(ERROR) << "Failed to prepare Android/ directories.";
304 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100305 }
306
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100307 // Now create the application-specific subdir(s)
308 // path is something like /data/media/0/Android/data/com.foo/files
309 // First, chop off the volume root, eg /data/media/0
310 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100311
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100312 uid_t uid = appUid;
313 gid_t gid = AID_MEDIA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200314 std::vector<gid_t> additionalGids;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100315 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100316
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100317 // Check that the next part matches one of the allowed Android/ dirs
318 if (StartsWith(pathFromRoot, kAppDataDir)) {
319 appDir = kAppDataDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700320 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100321 gid = AID_EXT_DATA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200322 // Also add the app's own UID as a group; since apps belong to a group
323 // that matches their UID, this ensures that they will always have access to
324 // the files created in these dirs, even if they are created by other processes
325 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100326 }
327 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
328 appDir = kAppMediaDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700329 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100330 gid = AID_MEDIA_RW;
331 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000332 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100333 appDir = kAppObbDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700334 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100335 gid = AID_EXT_OBB_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200336 // See comments for kAppDataDir above
337 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100338 }
339 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100340 LOG(ERROR) << "Invalid application directory: " << path;
341 return -EINVAL;
342 }
343
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100344 // mode = 770, plus sticky bit on directory to inherit GID when apps
345 // create subdirs
346 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100347 // the project ID for application-specific directories is directly
348 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100349
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100350 // Chop off the generic application-specific part, eg /Android/data/
351 // this leaves us with something like com.foo/files/
352 std::string leftToCreate = pathFromRoot.substr(appDir.length());
353 if (!EndsWith(leftToCreate, "/")) {
354 leftToCreate += "/";
355 }
356 std::string pathToCreate = root + appDir;
357 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100358 // Derive initial project ID
359 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
360 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
361 } else if (appDir == kAppObbDir) {
362 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
363 }
364
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100365 while ((pos = leftToCreate.find('/')) != std::string::npos) {
366 std::string component = leftToCreate.substr(0, pos + 1);
367 leftToCreate = leftToCreate.erase(0, pos + 1);
368 pathToCreate = pathToCreate + component;
369
370 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
371 // All dirs use the "app" project ID, except for the cache dirs in
372 // Android/data, eg Android/data/com.foo/cache
373 // Note that this "sticks" - eg subdirs of this dir need the same
374 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100375 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100376 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100377
378 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
379 // Fixup all files in this existing directory with the correct UID/GID
380 // and project ID.
381 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
382 } else {
383 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
384 }
385
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100386 if (ret != 0) {
387 return ret;
388 }
389
390 if (depth == 0) {
391 // Set the default ACL on the top-level application-specific directories,
392 // to ensure that even if applications run with a umask of 0077,
393 // new directories within these directories will allow the GID
394 // specified here to write; this is necessary for apps like
395 // installers and MTP, that require access here.
396 //
397 // See man (5) acl for more details.
Martijn Coenen1129b812020-06-16 14:58:52 +0200398 ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100399 if (ret != 0) {
400 return ret;
401 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100402
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700403 if (!sdcardfsSupport) {
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100404 // Set project ID inheritance, so that future subdirectories inherit the
405 // same project ID
406 ret = SetQuotaInherit(pathToCreate);
407 if (ret != 0) {
408 return ret;
409 }
410 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100411 }
412
413 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100414 }
415
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100416 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100417}
418
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700419status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600420 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700421 const char* cpath = path.c_str();
422
423 char* secontext = nullptr;
424 if (sehandle) {
425 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
426 setfscreatecon(secontext);
427 }
428 }
429
430 int res = fs_prepare_dir(cpath, mode, uid, gid);
431
432 if (secontext) {
433 setfscreatecon(nullptr);
434 freecon(secontext);
435 }
436
437 if (res == 0) {
438 return OK;
439 } else {
440 return -errno;
441 }
442}
443
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800444status_t ForceUnmount(const std::string& path) {
445 const char* cpath = path.c_str();
446 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
447 return OK;
448 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700449 // Apps might still be handling eject request, so wait before
450 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700451 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700452
Jeff Sharkey3472e522017-10-06 18:02:53 -0600453 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700454 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700455 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
456 return OK;
457 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700458
Jeff Sharkey3472e522017-10-06 18:02:53 -0600459 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700460 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800461 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
462 return OK;
463 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700464
Jeff Sharkey3472e522017-10-06 18:02:53 -0600465 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700466 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700467 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
468 return OK;
469 }
Zim3623a212019-07-19 16:46:53 +0100470 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800471 return -errno;
472}
473
Ricky Wai07e64a42020-02-11 14:31:24 +0000474status_t KillProcessesWithMountPrefix(const std::string& path) {
475 if (KillProcessesWithMounts(path, SIGINT) == 0) {
476 return OK;
477 }
478 if (sSleepOnUnmount) sleep(5);
479
480 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
481 return OK;
482 }
483 if (sSleepOnUnmount) sleep(5);
484
485 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
486 return OK;
487 }
488 if (sSleepOnUnmount) sleep(5);
489
490 // Send SIGKILL a second time to determine if we've
491 // actually killed everyone mount
492 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
493 return OK;
494 }
495 PLOG(ERROR) << "Failed to kill processes using " << path;
496 return -EBUSY;
497}
498
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700499status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600500 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700501 return OK;
502 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700503 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700504
Jeff Sharkey3472e522017-10-06 18:02:53 -0600505 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700506 return OK;
507 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700508 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700509
Jeff Sharkey3472e522017-10-06 18:02:53 -0600510 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700511 return OK;
512 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700513 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700514
515 // Send SIGKILL a second time to determine if we've
516 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600517 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700518 return OK;
519 }
520 PLOG(ERROR) << "Failed to kill processes using " << path;
521 return -EBUSY;
522}
523
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700524status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800525 if (UnmountTree(target) < 0) {
526 return -errno;
527 }
528 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700529 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
530 return -errno;
531 }
532 return OK;
533}
534
Sudheer Shanka023b5392019-02-06 12:39:19 -0800535status_t Symlink(const std::string& target, const std::string& linkpath) {
536 if (Unlink(linkpath) < 0) {
537 return -errno;
538 }
539 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
540 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
541 return -errno;
542 }
543 return OK;
544}
545
546status_t Unlink(const std::string& linkpath) {
547 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
548 PLOG(ERROR) << "Failed to unlink " << linkpath;
549 return -errno;
550 }
551 return OK;
552}
553
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000554status_t CreateDir(const std::string& dir, mode_t mode) {
555 struct stat sb;
556 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
557 if (S_ISDIR(sb.st_mode)) {
558 return OK;
559 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
560 PLOG(ERROR) << "Failed to unlink " << dir;
561 return -errno;
562 }
563 } else if (errno != ENOENT) {
564 PLOG(ERROR) << "Failed to stat " << dir;
565 return -errno;
566 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800567 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000568 PLOG(ERROR) << "Failed to mkdir " << dir;
569 return -errno;
570 }
571 return OK;
572}
573
Jeff Sharkey3472e522017-10-06 18:02:53 -0600574bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
575 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800576 size_t start = 0;
577 while (true) {
578 start = raw.find(qual, start);
579 if (start == std::string::npos) return false;
580 if (start == 0 || raw[start - 1] == ' ') {
581 break;
582 }
583 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600584 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600585 start += qual.length();
586
587 auto end = raw.find("\"", start);
588 if (end == std::string::npos) return false;
589
590 *value = raw.substr(start, end - start);
591 return true;
592}
593
Paul Crowley14c8c072018-09-18 13:30:21 -0700594static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
595 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600596 fsType->clear();
597 fsUuid->clear();
598 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700599
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700600 std::vector<std::string> cmd;
601 cmd.push_back(kBlkidPath);
602 cmd.push_back("-c");
603 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700604 cmd.push_back("-s");
605 cmd.push_back("TYPE");
606 cmd.push_back("-s");
607 cmd.push_back("UUID");
608 cmd.push_back("-s");
609 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700610 cmd.push_back(path);
611
612 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800613 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700614 if (res != OK) {
615 LOG(WARNING) << "blkid failed to identify " << path;
616 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700617 }
618
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700619 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700620 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600621 FindValue(line, "TYPE", fsType);
622 FindValue(line, "UUID", fsUuid);
623 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700624 }
625
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700626 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700627}
628
Paul Crowley14c8c072018-09-18 13:30:21 -0700629status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
630 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700631 return readMetadata(path, fsType, fsUuid, fsLabel, false);
632}
633
Paul Crowley14c8c072018-09-18 13:30:21 -0700634status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
635 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700636 return readMetadata(path, fsType, fsUuid, fsLabel, true);
637}
638
Paul Crowleyde2d6202018-11-30 11:43:47 -0800639static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
640 std::vector<const char*> argv;
641 argv.reserve(args.size() + 1);
642 for (const auto& arg : args) {
643 if (argv.empty()) {
644 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700645 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800646 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700647 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800648 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700649 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800650 argv.emplace_back(nullptr);
651 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700652}
653
Paul Crowleyde2d6202018-11-30 11:43:47 -0800654static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
655 android::base::unique_fd ufd) {
656 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700657 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800658 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700659 return -errno;
660 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800661 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700662 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800663 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700664 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800665 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700666 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800667 return OK;
668}
669
670status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
671 security_context_t context) {
672 auto argv = ConvertToArgv(args);
673
Paul Crowleye6d76632018-11-30 11:43:47 -0800674 android::base::unique_fd pipe_read, pipe_write;
675 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
676 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800677 return -errno;
678 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800679
680 pid_t pid = fork();
681 if (pid == 0) {
682 if (context) {
683 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800684 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800685 abort();
686 }
687 }
688 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800689 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
690 PLOG(ERROR) << "dup2 in ForkExecvp";
691 _exit(EXIT_FAILURE);
692 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800693 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800694 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800695 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800696 _exit(EXIT_FAILURE);
697 }
698 if (pid == -1) {
699 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700700 return -errno;
701 }
702
Paul Crowleyde2d6202018-11-30 11:43:47 -0800703 pipe_write.reset();
704 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
705 if (st != 0) return st;
706
707 int status;
708 if (waitpid(pid, &status, 0) == -1) {
709 PLOG(ERROR) << "waitpid in ForkExecvp";
710 return -errno;
711 }
712 if (!WIFEXITED(status)) {
713 LOG(ERROR) << "Process did not exit normally, status: " << status;
714 return -ECHILD;
715 }
716 if (WEXITSTATUS(status)) {
717 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
718 return WEXITSTATUS(status);
719 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700720 return OK;
721}
722
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700723pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800724 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700725
726 pid_t pid = fork();
727 if (pid == 0) {
728 close(STDIN_FILENO);
729 close(STDOUT_FILENO);
730 close(STDERR_FILENO);
731
Paul Crowleyde2d6202018-11-30 11:43:47 -0800732 execvp(argv[0], const_cast<char**>(argv.data()));
733 PLOG(ERROR) << "exec in ForkExecvpAsync";
734 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700735 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700736 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800737 PLOG(ERROR) << "fork in ForkExecvpAsync";
738 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700739 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700740 return pid;
741}
742
Jeff Sharkey9c484982015-03-31 10:35:33 -0700743status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100744 out.resize(bytes);
745 return ReadRandomBytes(bytes, &out[0]);
746}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700747
Pavel Grafove2e2d302017-08-01 17:15:53 +0100748status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700749 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
750 if (fd == -1) {
751 return -errno;
752 }
753
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800754 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100755 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700756 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100757 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700758 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700759 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700760
761 if (bytes == 0) {
762 return OK;
763 } else {
764 return -EIO;
765 }
766}
767
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600768status_t GenerateRandomUuid(std::string& out) {
769 status_t res = ReadRandomBytes(16, out);
770 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700771 out[6] &= 0x0f; /* clear version */
772 out[6] |= 0x40; /* set to version 4 */
773 out[8] &= 0x3f; /* clear variant */
774 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600775 }
776 return res;
777}
778
Jeff Sharkey9c484982015-03-31 10:35:33 -0700779status_t HexToStr(const std::string& hex, std::string& str) {
780 str.clear();
781 bool even = true;
782 char cur = 0;
783 for (size_t i = 0; i < hex.size(); i++) {
784 int val = 0;
785 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700786 // clang-format off
787 case ' ': case '-': case ':': continue;
788 case 'f': case 'F': val = 15; break;
789 case 'e': case 'E': val = 14; break;
790 case 'd': case 'D': val = 13; break;
791 case 'c': case 'C': val = 12; break;
792 case 'b': case 'B': val = 11; break;
793 case 'a': case 'A': val = 10; break;
794 case '9': val = 9; break;
795 case '8': val = 8; break;
796 case '7': val = 7; break;
797 case '6': val = 6; break;
798 case '5': val = 5; break;
799 case '4': val = 4; break;
800 case '3': val = 3; break;
801 case '2': val = 2; break;
802 case '1': val = 1; break;
803 case '0': val = 0; break;
804 default: return -EINVAL;
805 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700806 }
807
808 if (even) {
809 cur = val << 4;
810 } else {
811 cur += val;
812 str.push_back(cur);
813 cur = 0;
814 }
815 even = !even;
816 }
817 return even ? OK : -EINVAL;
818}
819
820static const char* kLookup = "0123456789abcdef";
821
822status_t StrToHex(const std::string& str, std::string& hex) {
823 hex.clear();
824 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700825 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700826 hex.push_back(kLookup[str[i] & 0x0F]);
827 }
828 return OK;
829}
830
Pavel Grafove2e2d302017-08-01 17:15:53 +0100831status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
832 hex.clear();
833 for (size_t i = 0; i < str.size(); i++) {
834 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
835 hex.push_back(kLookup[str.data()[i] & 0x0F]);
836 }
837 return OK;
838}
839
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700840status_t NormalizeHex(const std::string& in, std::string& out) {
841 std::string tmp;
842 if (HexToStr(in, tmp)) {
843 return -EINVAL;
844 }
845 return StrToHex(tmp, out);
846}
847
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200848status_t GetBlockDevSize(int fd, uint64_t* size) {
849 if (ioctl(fd, BLKGETSIZE64, size)) {
850 return -errno;
851 }
852
853 return OK;
854}
855
856status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
857 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
858 status_t res = OK;
859
860 if (fd < 0) {
861 return -errno;
862 }
863
864 res = GetBlockDevSize(fd, size);
865
866 close(fd);
867
868 return res;
869}
870
871status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
872 uint64_t size;
873 status_t res = GetBlockDevSize(path, &size);
874
875 if (res != OK) {
876 return res;
877 }
878
879 *nr_sec = size / 512;
880
881 return OK;
882}
883
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700884uint64_t GetFreeBytes(const std::string& path) {
885 struct statvfs sb;
886 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700887 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700888 } else {
889 return -1;
890 }
891}
892
893// TODO: borrowed from frameworks/native/libs/diskusage/ which should
894// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700895static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700896 int64_t blksize = s->st_blksize;
897 // count actual blocks used instead of nominal file size
898 int64_t size = s->st_blocks * 512;
899
900 if (blksize) {
901 /* round up to filesystem block size */
902 size = (size + blksize - 1) & (~(blksize - 1));
903 }
904
905 return size;
906}
907
908// TODO: borrowed from frameworks/native/libs/diskusage/ which should
909// eventually be migrated into system/
910int64_t calculate_dir_size(int dfd) {
911 int64_t size = 0;
912 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700913 DIR* d;
914 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700915
916 d = fdopendir(dfd);
917 if (d == NULL) {
918 close(dfd);
919 return 0;
920 }
921
922 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700923 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700924 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
925 size += stat_size(&s);
926 }
927 if (de->d_type == DT_DIR) {
928 int subfd;
929
930 /* always skip "." and ".." */
931 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700932 if (name[1] == 0) continue;
933 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700934 }
935
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600936 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700937 if (subfd >= 0) {
938 size += calculate_dir_size(subfd);
939 }
940 }
941 }
942 closedir(d);
943 return size;
944}
945
946uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600947 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700948 if (dirfd < 0) {
949 PLOG(WARNING) << "Failed to open " << path;
950 return -1;
951 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700952 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700953 }
954}
955
Ricky Wai07e64a42020-02-11 14:31:24 +0000956// TODO: Use a better way to determine if it's media provider app.
957bool IsFuseDaemon(const pid_t pid) {
958 auto path = StringPrintf("/proc/%d/mounts", pid);
959 char* tmp;
960 if (lgetfilecon(path.c_str(), &tmp) < 0) {
961 return false;
962 }
963 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
964 || android::base::StartsWith(tmp, kMediaProviderCtx);
965 freecon(tmp);
966 return result;
967}
968
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700969bool IsFilesystemSupported(const std::string& fsType) {
970 std::string supported;
971 if (!ReadFileToString(kProcFilesystems, &supported)) {
972 PLOG(ERROR) << "Failed to read supported filesystems";
973 return false;
974 }
975 return supported.find(fsType + "\n") != std::string::npos;
976}
977
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700978bool IsSdcardfsUsed() {
979 return IsFilesystemSupported("sdcardfs") &&
980 base::GetBoolProperty(kExternalStorageSdcardfs, true);
981}
982
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700983status_t WipeBlockDevice(const std::string& path) {
984 status_t res = -1;
985 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200986 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700987
988 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
989 if (fd == -1) {
990 PLOG(ERROR) << "Failed to open " << path;
991 goto done;
992 }
993
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200994 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700995 PLOG(ERROR) << "Failed to determine size of " << path;
996 goto done;
997 }
998
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700999 LOG(INFO) << "About to discard " << range[1] << " on " << path;
1000 if (ioctl(fd, BLKDISCARD, &range) == 0) {
1001 LOG(INFO) << "Discard success on " << path;
1002 res = 0;
1003 } else {
1004 PLOG(ERROR) << "Discard failure on " << path;
1005 }
1006
1007done:
1008 close(fd);
1009 return res;
1010}
1011
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001012static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001013 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001014 return false;
1015 } else {
1016 return true;
1017 }
1018}
1019
Jeff Sharkeybc40cc82015-06-18 14:25:08 -07001020std::string BuildKeyPath(const std::string& partGuid) {
1021 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1022}
1023
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001024std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001025 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001026}
1027
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001028std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001029 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001030}
1031
1032std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001033 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001034}
1035
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001036std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001037 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001038}
1039
Jeff Sharkey47695b22016-02-01 17:02:29 -07001040std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001041 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001042}
1043
1044std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001045 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001046}
1047
Calin Juravle79f55a42016-02-17 20:14:46 +00001048// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1049std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001050 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001051}
1052
Andreas Huber71cd43f2018-01-22 11:25:29 -08001053std::string BuildDataVendorCePath(userid_t userId) {
1054 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1055}
1056
1057std::string BuildDataVendorDePath(userid_t userId) {
1058 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1059}
1060
Paul Crowley3b71fc52017-10-09 10:55:21 -07001061std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001062 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001063 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001064 return "/data";
1065 } else {
1066 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001067 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001068 }
1069}
1070
Paul Crowley3b71fc52017-10-09 10:55:21 -07001071std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001072 // TODO: unify with installd path generation logic
1073 std::string data(BuildDataPath(volumeUuid));
1074 return StringPrintf("%s/media/%u", data.c_str(), userId);
1075}
1076
Paul Crowley3b71fc52017-10-09 10:55:21 -07001077std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001078 // TODO: unify with installd path generation logic
1079 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001080 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001081 std::string legacy = StringPrintf("%s/data", data.c_str());
1082 struct stat sb;
1083 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1084 /* /data/data is dir, return /data/data for legacy system */
1085 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001086 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001087 }
cjbaoeb501142017-04-12 00:09:00 +08001088 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001089}
1090
Paul Crowley3b71fc52017-10-09 10:55:21 -07001091std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001092 // TODO: unify with installd path generation logic
1093 std::string data(BuildDataPath(volumeUuid));
1094 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1095}
1096
Jeff Sharkey66270a22015-06-24 11:49:24 -07001097dev_t GetDevice(const std::string& path) {
1098 struct stat sb;
1099 if (stat(path.c_str(), &sb)) {
1100 PLOG(WARNING) << "Failed to stat " << path;
1101 return 0;
1102 } else {
1103 return sb.st_dev;
1104 }
1105}
1106
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001107status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001108 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001109
Tom Cherryd6127ef2017-06-15 17:13:56 -07001110 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001111
Tom Cherryd6127ef2017-06-15 17:13:56 -07001112 android::base::SetProperty(kRestoreconString, "");
1113 android::base::SetProperty(kRestoreconString, path);
1114
1115 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001116
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001117 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001118 return OK;
1119}
1120
Jeff Sharkey3472e522017-10-06 18:02:53 -06001121bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1122 // Shamelessly borrowed from android::base::Readlink()
1123 result->clear();
1124
1125 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1126 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1127 // waste memory to just start there. We add 1 so that we can recognize
1128 // whether it actually fit (rather than being truncated to 4095).
1129 std::vector<char> buf(4095 + 1);
1130 while (true) {
1131 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1132 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001133 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001134 // It fit! (If size == buf.size(), it may have been truncated.)
1135 if (static_cast<size_t>(size) < buf.size()) {
1136 result->assign(&buf[0], size);
1137 return true;
1138 }
1139 // Double our buffer and try again.
1140 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001141 }
1142}
1143
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001144static unsigned int GetMajorBlockVirtioBlk() {
1145 std::string devices;
1146 if (!ReadFileToString(kProcDevices, &devices)) {
1147 PLOG(ERROR) << "Unable to open /proc/devices";
1148 return 0;
1149 }
1150
1151 bool blockSection = false;
1152 for (auto line : android::base::Split(devices, "\n")) {
1153 if (line == "Block devices:") {
1154 blockSection = true;
1155 } else if (line == "Character devices:") {
1156 blockSection = false;
1157 } else if (blockSection) {
1158 auto tokens = android::base::Split(line, " ");
1159 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1160 return std::stoul(tokens[0]);
1161 }
1162 }
1163 }
1164
1165 return 0;
1166}
1167
1168bool IsVirtioBlkDevice(unsigned int major) {
1169 // Most virtualized platforms expose block devices with the virtio-blk
1170 // block device driver. Unfortunately, this driver does not use a fixed
1171 // major number, but relies on the kernel to assign one from a specific
1172 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1173 // per Documentation/devices.txt. This is true even for the latest Linux
1174 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1175 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1176 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001177}
1178
Sudheer Shanka295fb242019-01-16 23:04:07 -08001179static status_t findMountPointsWithPrefix(const std::string& prefix,
1180 std::list<std::string>& mountPoints) {
1181 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1182 // when the prefix is /foo/bar
1183 std::string prefixWithSlash(prefix);
1184 if (prefix.back() != '/') {
1185 android::base::StringAppendF(&prefixWithSlash, "/");
1186 }
1187
1188 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1189 if (!mnts) {
1190 PLOG(ERROR) << "Unable to open /proc/mounts";
1191 return -errno;
1192 }
1193
1194 // Some volumes can be stacked on each other, so force unmount in
1195 // reverse order to give us the best chance of success.
1196 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1197 while ((mnt = getmntent(mnts.get())) != nullptr) {
1198 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1199 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1200 mountPoints.push_front(mountPoint);
1201 }
1202 }
1203 return OK;
1204}
1205
1206// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1207status_t UnmountTreeWithPrefix(const std::string& prefix) {
1208 std::list<std::string> toUnmount;
1209 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1210 if (result < 0) {
1211 return result;
1212 }
1213 for (const auto& path : toUnmount) {
1214 if (umount2(path.c_str(), MNT_DETACH)) {
1215 PLOG(ERROR) << "Failed to unmount " << path;
1216 result = -errno;
1217 }
1218 }
1219 return result;
1220}
1221
1222status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001223 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1224 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001225 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001226 return -errno;
1227 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001228 return OK;
1229}
1230
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001231static status_t delete_dir_contents(DIR* dir) {
1232 // Shamelessly borrowed from android::installd
1233 int dfd = dirfd(dir);
1234 if (dfd < 0) {
1235 return -errno;
1236 }
1237
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001238 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001239 struct dirent* de;
1240 while ((de = readdir(dir))) {
1241 const char* name = de->d_name;
1242 if (de->d_type == DT_DIR) {
1243 /* always skip "." and ".." */
1244 if (name[0] == '.') {
1245 if (name[1] == 0) continue;
1246 if ((name[1] == '.') && (name[2] == 0)) continue;
1247 }
1248
1249 android::base::unique_fd subfd(
1250 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1251 if (subfd.get() == -1) {
1252 PLOG(ERROR) << "Couldn't openat " << name;
1253 result = -errno;
1254 continue;
1255 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001256 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1257 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001258 if (!subdirp) {
1259 PLOG(ERROR) << "Couldn't fdopendir " << name;
1260 result = -errno;
1261 continue;
1262 }
1263 result = delete_dir_contents(subdirp.get());
1264 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1265 PLOG(ERROR) << "Couldn't unlinkat " << name;
1266 result = -errno;
1267 }
1268 } else {
1269 if (unlinkat(dfd, name, 0) < 0) {
1270 PLOG(ERROR) << "Couldn't unlinkat " << name;
1271 result = -errno;
1272 }
1273 }
1274 }
1275 return result;
1276}
1277
1278status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001279 status_t res = DeleteDirContents(pathname);
1280 if (res < 0) {
1281 return res;
1282 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001283 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001284 PLOG(ERROR) << "rmdir failed on " << pathname;
1285 return -errno;
1286 }
1287 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1288 return OK;
1289}
1290
1291status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001292 // Shamelessly borrowed from android::installd
1293 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1294 if (!dirp) {
1295 if (errno == ENOENT) {
1296 return OK;
1297 }
1298 PLOG(ERROR) << "Failed to opendir " << pathname;
1299 return -errno;
1300 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001301 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001302}
1303
Paul Crowley298fa322018-10-30 15:59:24 -07001304// TODO(118708649): fix duplication with init/util.h
1305status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1306 android::base::Timer t;
1307 while (t.duration() < timeout) {
1308 struct stat sb;
1309 if (stat(filename, &sb) != -1) {
1310 LOG(INFO) << "wait for '" << filename << "' took " << t;
1311 return 0;
1312 }
1313 std::this_thread::sleep_for(10ms);
1314 }
1315 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1316 return -1;
1317}
1318
Paul Crowley621d9b92018-12-07 15:36:09 -08001319bool FsyncDirectory(const std::string& dirname) {
1320 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1321 if (fd == -1) {
1322 PLOG(ERROR) << "Failed to open " << dirname;
1323 return false;
1324 }
1325 if (fsync(fd) == -1) {
1326 if (errno == EROFS || errno == EINVAL) {
1327 PLOG(WARNING) << "Skip fsync " << dirname
1328 << " on a file system does not support synchronization";
1329 } else {
1330 PLOG(ERROR) << "Failed to fsync " << dirname;
1331 return false;
1332 }
1333 }
1334 return true;
1335}
1336
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001337bool writeStringToFile(const std::string& payload, const std::string& filename) {
1338 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1339 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1340 if (fd == -1) {
1341 PLOG(ERROR) << "Failed to open " << filename;
1342 return false;
1343 }
1344 if (!android::base::WriteStringToFd(payload, fd)) {
1345 PLOG(ERROR) << "Failed to write to " << filename;
1346 unlink(filename.c_str());
1347 return false;
1348 }
1349 // fsync as close won't guarantee flush data
1350 // see close(2), fsync(2) and b/68901441
1351 if (fsync(fd) == -1) {
1352 if (errno == EROFS || errno == EINVAL) {
1353 PLOG(WARNING) << "Skip fsync " << filename
1354 << " on a file system does not support synchronization";
1355 } else {
1356 PLOG(ERROR) << "Failed to fsync " << filename;
1357 unlink(filename.c_str());
1358 return false;
1359 }
1360 }
1361 return true;
1362}
1363
Martijn Coenen23c04452020-04-29 07:49:41 +02001364status_t AbortFuseConnections() {
1365 namespace fs = std::filesystem;
1366
1367 for (const auto& itEntry : fs::directory_iterator("/sys/fs/fuse/connections")) {
1368 std::string abortPath = itEntry.path().string() + "/abort";
1369 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1370 bool ret = writeStringToFile("1", abortPath);
1371 if (!ret) {
1372 LOG(WARNING) << "Failed to write to " << abortPath;
1373 }
1374 }
1375
1376 return OK;
1377}
1378
Ricky Wai07e64a42020-02-11 14:31:24 +00001379status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1380 if (access(path.c_str(), F_OK) != 0) {
1381 PLOG(WARNING) << "Dir does not exist: " << path;
1382 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1383 return -errno;
1384 }
1385 }
1386 return OK;
1387}
1388
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001389// Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1390// writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
1391void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1392 LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1393 << read_ahead_kb << "kb";
1394 // First figure out MAJOR:MINOR of fuse_mount. Simplest way is to stat the path.
1395 struct stat info;
1396 if (stat(fuse_mount.c_str(), &info) != 0) {
1397 PLOG(ERROR) << "Failed to stat " << fuse_mount;
1398 return;
1399 }
1400 unsigned int maj = major(info.st_dev);
1401 unsigned int min = minor(info.st_dev);
1402 LOG(INFO) << fuse_mount << " has major:minor " << maj << ":" << min;
1403 // We found major:minor of our filesystem, time to configure read ahead!
1404 std::string read_ahead_file = StringPrintf("/sys/class/bdi/%u:%u/read_ahead_kb", maj, min);
1405 unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1406 if (fd.get() == -1) {
1407 PLOG(ERROR) << "Failed to open " << read_ahead_file;
1408 return;
1409 }
1410 LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1411 if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1412 PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1413 }
1414}
1415
Zima438b242019-09-25 14:37:38 +01001416status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1417 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1418 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1419 std::string fuse_path(
1420 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1421
1422 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1423 std::string pass_through_path(
1424 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001425
Zim1242be82020-01-22 18:22:29 +00001426 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1427 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001428 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001429 if (result != android::OK) {
1430 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1431 return -1;
1432 }
1433
Zim06b0caf2020-01-05 02:11:47 +00001434 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1435 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1436 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1437 // These bits should be consistent with what is set in zygote in
1438 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001439 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001440 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001441 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001442 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001443 return -1;
1444 }
1445
Zima438b242019-09-25 14:37:38 +01001446 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1447 if (result != android::OK) {
1448 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1449 return -1;
1450 }
1451
Zim26eec702020-01-31 16:00:58 +00001452 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001453 if (result != android::OK) {
1454 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1455 return -1;
1456 }
1457
Zim26eec702020-01-31 16:00:58 +00001458 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001459 if (result != android::OK) {
1460 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1461 return -1;
1462 }
1463
1464 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001465 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1466 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001467 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001468 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001469 return -1;
1470 }
Zime5393d42019-11-15 11:44:12 +00001471 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001472 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001473
1474 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001475 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001476 if (result != android::OK) {
1477 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1478 return -1;
1479 }
1480 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001481 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001482 }
1483
Nandana Dutta914cc72019-08-29 15:22:42 +01001484 // Open fuse fd.
1485 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1486 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001487 PLOG(ERROR) << "Failed to open /dev/fuse";
1488 return -1;
1489 }
1490
1491 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1492 // permission checks before routing to FUSE daemon.
1493 const auto opts = StringPrintf(
1494 "fd=%i,"
1495 "rootmode=40000,"
1496 "allow_other,"
1497 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001498 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001499
Zima438b242019-09-25 14:37:38 +01001500 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1501 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1502 opts.c_str()));
1503 if (result != 0) {
1504 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001505 return -errno;
1506 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001507
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001508 if (IsSdcardfsUsed()) {
Martijn Coenen86f21a22020-01-06 09:48:14 +01001509 std::string sdcardfs_path(
1510 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1511
1512 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1513 return BindMount(sdcardfs_path, pass_through_path);
1514 } else {
1515 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1516 return BindMount(absolute_lower_path, pass_through_path);
1517 }
Zima438b242019-09-25 14:37:38 +01001518}
1519
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001520status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1521 const std::string& relative_upper_path) {
1522 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1523 std::string pass_through_path(
1524 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1525
Zima438b242019-09-25 14:37:38 +01001526 // Best effort unmount pass_through path
1527 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001528 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1529 auto status = ForceUnmount(pass_through_path);
1530 if (status != android::OK) {
1531 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1532 }
Martijn Coenen57002612019-11-28 11:56:13 +01001533 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001534
1535 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001536 android::status_t result = ForceUnmount(fuse_path);
1537 sSleepOnUnmount = true;
1538 if (result != android::OK) {
1539 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1540 // Figure out why we get EBUSY and remove this special casing if possible.
1541 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1542 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1543 errno != ENOENT) {
1544 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1545 return -errno;
1546 }
Martijn Coenen57002612019-11-28 11:56:13 +01001547 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001548 }
Martijn Coenen57002612019-11-28 11:56:13 +01001549 rmdir(fuse_path.c_str());
1550
Zima438b242019-09-25 14:37:38 +01001551 return result;
Zim3623a212019-07-19 16:46:53 +01001552}
1553
Martijn Coenen62a4b272020-01-31 15:23:09 +01001554status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1555 std::string androidDir = volumeRoot + kAndroidDir;
1556 std::string androidDataDir = volumeRoot + kAppDataDir;
1557 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001558 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001559
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001560 bool useSdcardFs = IsSdcardfsUsed();
Martijn Coenen62a4b272020-01-31 15:23:09 +01001561
Martijn Coenen10570c02020-02-18 10:41:37 +01001562 // mode 0771 + sticky bit for inheriting GIDs
1563 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1564 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001565 PLOG(ERROR) << "Failed to create " << androidDir;
1566 return -errno;
1567 }
1568
1569 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001570 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001571 PLOG(ERROR) << "Failed to create " << androidDataDir;
1572 return -errno;
1573 }
1574
1575 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001576 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001577 PLOG(ERROR) << "Failed to create " << androidObbDir;
1578 return -errno;
1579 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001580 // Some other apps, like installers, have write access to the OBB directory
1581 // to pre-download them. To make sure newly created folders in this directory
1582 // have the right permissions, set a default ACL.
Martijn Coenen1129b812020-06-16 14:58:52 +02001583 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
Martijn Coenen62a4b272020-01-31 15:23:09 +01001584
Martijn Coenen10570c02020-02-18 10:41:37 +01001585 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001586 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1587 return -errno;
1588 }
1589
Martijn Coenen62a4b272020-01-31 15:23:09 +01001590 return OK;
1591}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001592} // namespace vold
1593} // namespace android