blob: ac28a475184fa32cb4786088b7a51fd5a541aad4 [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
Daniel Rosenberg14a4b972020-08-12 18:31:43 -0700419int SetAttrs(const std::string& path, unsigned int attrs) {
420 unsigned long flags;
421 android::base::unique_fd fd(
422 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
423
424 if (fd == -1) {
425 PLOG(ERROR) << "Failed to open " << path;
426 return -1;
427 }
428
429 if (ioctl(fd, FS_IOC_GETFLAGS, (void*)&flags)) {
430 PLOG(ERROR) << "Failed to get flags for " << path;
431 return -1;
432 }
433
434 if ((flags & attrs) == attrs) return 0;
435 flags |= attrs;
436 if (ioctl(fd, FS_IOC_SETFLAGS, (void*)&flags)) {
437 PLOG(ERROR) << "Failed to set flags for " << path << "(0x" << std::hex << attrs << ")";
438 return -1;
439 }
440 return 0;
441}
442
443status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
444 unsigned int attrs) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600445 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700446 const char* cpath = path.c_str();
447
448 char* secontext = nullptr;
449 if (sehandle) {
450 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
451 setfscreatecon(secontext);
452 }
453 }
454
455 int res = fs_prepare_dir(cpath, mode, uid, gid);
456
457 if (secontext) {
458 setfscreatecon(nullptr);
459 freecon(secontext);
460 }
461
Daniel Rosenberg14a4b972020-08-12 18:31:43 -0700462 if (res) return -errno;
463 if (attrs) res = SetAttrs(path, attrs);
464
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700465 if (res == 0) {
466 return OK;
467 } else {
468 return -errno;
469 }
470}
471
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800472status_t ForceUnmount(const std::string& path) {
473 const char* cpath = path.c_str();
474 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
475 return OK;
476 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700477 // Apps might still be handling eject request, so wait before
478 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700479 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700480
Jeff Sharkey3472e522017-10-06 18:02:53 -0600481 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700482 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700483 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
484 return OK;
485 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700486
Jeff Sharkey3472e522017-10-06 18:02:53 -0600487 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700488 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800489 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
490 return OK;
491 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700492
Jeff Sharkey3472e522017-10-06 18:02:53 -0600493 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700494 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700495 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
496 return OK;
497 }
Zim3623a212019-07-19 16:46:53 +0100498 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800499 return -errno;
500}
501
Ricky Wai07e64a42020-02-11 14:31:24 +0000502status_t KillProcessesWithMountPrefix(const std::string& path) {
503 if (KillProcessesWithMounts(path, SIGINT) == 0) {
504 return OK;
505 }
506 if (sSleepOnUnmount) sleep(5);
507
508 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
509 return OK;
510 }
511 if (sSleepOnUnmount) sleep(5);
512
513 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
514 return OK;
515 }
516 if (sSleepOnUnmount) sleep(5);
517
518 // Send SIGKILL a second time to determine if we've
519 // actually killed everyone mount
520 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
521 return OK;
522 }
523 PLOG(ERROR) << "Failed to kill processes using " << path;
524 return -EBUSY;
525}
526
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700527status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600528 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700529 return OK;
530 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700531 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700532
Jeff Sharkey3472e522017-10-06 18:02:53 -0600533 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700534 return OK;
535 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700536 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700537
Jeff Sharkey3472e522017-10-06 18:02:53 -0600538 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700539 return OK;
540 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700541 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700542
543 // Send SIGKILL a second time to determine if we've
544 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600545 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700546 return OK;
547 }
548 PLOG(ERROR) << "Failed to kill processes using " << path;
549 return -EBUSY;
550}
551
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700552status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800553 if (UnmountTree(target) < 0) {
554 return -errno;
555 }
556 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700557 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
558 return -errno;
559 }
560 return OK;
561}
562
Sudheer Shanka023b5392019-02-06 12:39:19 -0800563status_t Symlink(const std::string& target, const std::string& linkpath) {
564 if (Unlink(linkpath) < 0) {
565 return -errno;
566 }
567 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
568 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
569 return -errno;
570 }
571 return OK;
572}
573
574status_t Unlink(const std::string& linkpath) {
575 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
576 PLOG(ERROR) << "Failed to unlink " << linkpath;
577 return -errno;
578 }
579 return OK;
580}
581
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000582status_t CreateDir(const std::string& dir, mode_t mode) {
583 struct stat sb;
584 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
585 if (S_ISDIR(sb.st_mode)) {
586 return OK;
587 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
588 PLOG(ERROR) << "Failed to unlink " << dir;
589 return -errno;
590 }
591 } else if (errno != ENOENT) {
592 PLOG(ERROR) << "Failed to stat " << dir;
593 return -errno;
594 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800595 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000596 PLOG(ERROR) << "Failed to mkdir " << dir;
597 return -errno;
598 }
599 return OK;
600}
601
Jeff Sharkey3472e522017-10-06 18:02:53 -0600602bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
603 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800604 size_t start = 0;
605 while (true) {
606 start = raw.find(qual, start);
607 if (start == std::string::npos) return false;
608 if (start == 0 || raw[start - 1] == ' ') {
609 break;
610 }
611 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600612 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600613 start += qual.length();
614
615 auto end = raw.find("\"", start);
616 if (end == std::string::npos) return false;
617
618 *value = raw.substr(start, end - start);
619 return true;
620}
621
Paul Crowley14c8c072018-09-18 13:30:21 -0700622static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
623 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600624 fsType->clear();
625 fsUuid->clear();
626 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700627
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700628 std::vector<std::string> cmd;
629 cmd.push_back(kBlkidPath);
630 cmd.push_back("-c");
631 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700632 cmd.push_back("-s");
633 cmd.push_back("TYPE");
634 cmd.push_back("-s");
635 cmd.push_back("UUID");
636 cmd.push_back("-s");
637 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700638 cmd.push_back(path);
639
640 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800641 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
louisliu67b084a2021-04-01 16:34:46 +0800642
643 int count = 0;
644
645 while(res != OK && count < 5){
646 LOG(WARNING) << "blkid failed. retry " << path << " count = " << count;
647 res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
648 count++;
649 }
650
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700651 if (res != OK) {
652 LOG(WARNING) << "blkid failed to identify " << path;
653 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700654 }
655
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700656 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700657 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600658 FindValue(line, "TYPE", fsType);
659 FindValue(line, "UUID", fsUuid);
660 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700661 }
662
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700663 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700664}
665
Paul Crowley14c8c072018-09-18 13:30:21 -0700666status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
667 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700668 return readMetadata(path, fsType, fsUuid, fsLabel, false);
669}
670
Paul Crowley14c8c072018-09-18 13:30:21 -0700671status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
672 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700673 return readMetadata(path, fsType, fsUuid, fsLabel, true);
674}
675
Paul Crowleyde2d6202018-11-30 11:43:47 -0800676static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
677 std::vector<const char*> argv;
678 argv.reserve(args.size() + 1);
679 for (const auto& arg : args) {
680 if (argv.empty()) {
681 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700682 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800683 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700684 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800685 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700686 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800687 argv.emplace_back(nullptr);
688 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700689}
690
Paul Crowleyde2d6202018-11-30 11:43:47 -0800691static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
692 android::base::unique_fd ufd) {
693 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700694 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800695 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700696 return -errno;
697 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800698 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700699 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800700 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700701 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800702 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700703 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800704 return OK;
705}
706
707status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
708 security_context_t context) {
709 auto argv = ConvertToArgv(args);
710
Paul Crowleye6d76632018-11-30 11:43:47 -0800711 android::base::unique_fd pipe_read, pipe_write;
712 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
713 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800714 return -errno;
715 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800716
717 pid_t pid = fork();
718 if (pid == 0) {
719 if (context) {
720 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800721 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800722 abort();
723 }
724 }
725 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800726 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
727 PLOG(ERROR) << "dup2 in ForkExecvp";
728 _exit(EXIT_FAILURE);
729 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800730 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800731 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800732 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800733 _exit(EXIT_FAILURE);
734 }
735 if (pid == -1) {
736 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700737 return -errno;
738 }
739
Paul Crowleyde2d6202018-11-30 11:43:47 -0800740 pipe_write.reset();
741 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
742 if (st != 0) return st;
743
744 int status;
745 if (waitpid(pid, &status, 0) == -1) {
746 PLOG(ERROR) << "waitpid in ForkExecvp";
747 return -errno;
748 }
749 if (!WIFEXITED(status)) {
750 LOG(ERROR) << "Process did not exit normally, status: " << status;
751 return -ECHILD;
752 }
753 if (WEXITSTATUS(status)) {
754 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
755 return WEXITSTATUS(status);
756 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700757 return OK;
758}
759
louisliua916d3f2021-04-01 09:49:55 +0800760status_t ForkExecvpTimeout(const std::vector<std::string>& args, std::vector<std::string>* output,
761 security_context_t context) {
762 auto argv = ConvertToArgv(args);
763
764 android::base::unique_fd pipe_read, pipe_write;
765 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
766 PLOG(ERROR) << "Pipe in ForkExecvp";
767 return -errno;
768 }
769
770 pid_t pid = fork();
771 if (pid == 0) {
772 if (context) {
773 if (setexeccon(context)) {
774 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
775 abort();
776 }
777 }
778 pipe_read.reset();
779 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
780 PLOG(ERROR) << "dup2 in ForkExecvp";
781 _exit(EXIT_FAILURE);
782 }
783 pipe_write.reset();
784 // Timeout 60s
785 alarm(60);
786 execvp(argv[0], const_cast<char**>(argv.data()));
787 PLOG(ERROR) << "exec in ForkExecvp";
788 _exit(EXIT_FAILURE);
789 }
790 if (pid == -1) {
791 PLOG(ERROR) << "fork in ForkExecvp";
792 return -errno;
793 }
794
795 pipe_write.reset();
796 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
797 if (st != 0) return st;
798
799 int status;
800 if (waitpid(pid, &status, 0) == -1) {
801 PLOG(ERROR) << "waitpid in ForkExecvp";
802 return -errno;
803 }
804 if (!WIFEXITED(status)) {
805 LOG(ERROR) << "Process did not exit normally, status: " << status;
806 return -ECHILD;
807 }
808
809 if (WEXITSTATUS(status)) {
810 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
811 return WEXITSTATUS(status);
812 }
813 return OK;
814}
815
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700816pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800817 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700818
819 pid_t pid = fork();
820 if (pid == 0) {
821 close(STDIN_FILENO);
822 close(STDOUT_FILENO);
823 close(STDERR_FILENO);
824
Paul Crowleyde2d6202018-11-30 11:43:47 -0800825 execvp(argv[0], const_cast<char**>(argv.data()));
826 PLOG(ERROR) << "exec in ForkExecvpAsync";
827 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700828 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700829 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800830 PLOG(ERROR) << "fork in ForkExecvpAsync";
831 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700832 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700833 return pid;
834}
835
Jeff Sharkey9c484982015-03-31 10:35:33 -0700836status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100837 out.resize(bytes);
838 return ReadRandomBytes(bytes, &out[0]);
839}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700840
Pavel Grafove2e2d302017-08-01 17:15:53 +0100841status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700842 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
843 if (fd == -1) {
844 return -errno;
845 }
846
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800847 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100848 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700849 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100850 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700851 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700852 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700853
854 if (bytes == 0) {
855 return OK;
856 } else {
857 return -EIO;
858 }
859}
860
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600861status_t GenerateRandomUuid(std::string& out) {
862 status_t res = ReadRandomBytes(16, out);
863 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700864 out[6] &= 0x0f; /* clear version */
865 out[6] |= 0x40; /* set to version 4 */
866 out[8] &= 0x3f; /* clear variant */
867 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600868 }
869 return res;
870}
871
Jeff Sharkey9c484982015-03-31 10:35:33 -0700872status_t HexToStr(const std::string& hex, std::string& str) {
873 str.clear();
874 bool even = true;
875 char cur = 0;
876 for (size_t i = 0; i < hex.size(); i++) {
877 int val = 0;
878 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700879 // clang-format off
880 case ' ': case '-': case ':': continue;
881 case 'f': case 'F': val = 15; break;
882 case 'e': case 'E': val = 14; break;
883 case 'd': case 'D': val = 13; break;
884 case 'c': case 'C': val = 12; break;
885 case 'b': case 'B': val = 11; break;
886 case 'a': case 'A': val = 10; break;
887 case '9': val = 9; break;
888 case '8': val = 8; break;
889 case '7': val = 7; break;
890 case '6': val = 6; break;
891 case '5': val = 5; break;
892 case '4': val = 4; break;
893 case '3': val = 3; break;
894 case '2': val = 2; break;
895 case '1': val = 1; break;
896 case '0': val = 0; break;
897 default: return -EINVAL;
898 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700899 }
900
901 if (even) {
902 cur = val << 4;
903 } else {
904 cur += val;
905 str.push_back(cur);
906 cur = 0;
907 }
908 even = !even;
909 }
910 return even ? OK : -EINVAL;
911}
912
913static const char* kLookup = "0123456789abcdef";
914
915status_t StrToHex(const std::string& str, std::string& hex) {
916 hex.clear();
917 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700918 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700919 hex.push_back(kLookup[str[i] & 0x0F]);
920 }
921 return OK;
922}
923
Pavel Grafove2e2d302017-08-01 17:15:53 +0100924status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
925 hex.clear();
926 for (size_t i = 0; i < str.size(); i++) {
927 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
928 hex.push_back(kLookup[str.data()[i] & 0x0F]);
929 }
930 return OK;
931}
932
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700933status_t NormalizeHex(const std::string& in, std::string& out) {
934 std::string tmp;
935 if (HexToStr(in, tmp)) {
936 return -EINVAL;
937 }
938 return StrToHex(tmp, out);
939}
940
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200941status_t GetBlockDevSize(int fd, uint64_t* size) {
942 if (ioctl(fd, BLKGETSIZE64, size)) {
943 return -errno;
944 }
945
946 return OK;
947}
948
949status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
950 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
951 status_t res = OK;
952
953 if (fd < 0) {
954 return -errno;
955 }
956
957 res = GetBlockDevSize(fd, size);
958
959 close(fd);
960
961 return res;
962}
963
964status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
965 uint64_t size;
966 status_t res = GetBlockDevSize(path, &size);
967
968 if (res != OK) {
969 return res;
970 }
971
972 *nr_sec = size / 512;
973
974 return OK;
975}
976
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700977uint64_t GetFreeBytes(const std::string& path) {
978 struct statvfs sb;
979 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700980 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700981 } else {
982 return -1;
983 }
984}
985
986// TODO: borrowed from frameworks/native/libs/diskusage/ which should
987// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700988static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700989 int64_t blksize = s->st_blksize;
990 // count actual blocks used instead of nominal file size
991 int64_t size = s->st_blocks * 512;
992
993 if (blksize) {
994 /* round up to filesystem block size */
995 size = (size + blksize - 1) & (~(blksize - 1));
996 }
997
998 return size;
999}
1000
1001// TODO: borrowed from frameworks/native/libs/diskusage/ which should
1002// eventually be migrated into system/
1003int64_t calculate_dir_size(int dfd) {
1004 int64_t size = 0;
1005 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -07001006 DIR* d;
1007 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001008
1009 d = fdopendir(dfd);
1010 if (d == NULL) {
1011 close(dfd);
1012 return 0;
1013 }
1014
1015 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001016 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001017 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
1018 size += stat_size(&s);
1019 }
1020 if (de->d_type == DT_DIR) {
1021 int subfd;
1022
1023 /* always skip "." and ".." */
1024 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -07001025 if (name[1] == 0) continue;
1026 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001027 }
1028
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -06001029 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001030 if (subfd >= 0) {
1031 size += calculate_dir_size(subfd);
1032 }
1033 }
1034 }
1035 closedir(d);
1036 return size;
1037}
1038
1039uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -06001040 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001041 if (dirfd < 0) {
1042 PLOG(WARNING) << "Failed to open " << path;
1043 return -1;
1044 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -07001045 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -07001046 }
1047}
1048
Ricky Wai07e64a42020-02-11 14:31:24 +00001049// TODO: Use a better way to determine if it's media provider app.
1050bool IsFuseDaemon(const pid_t pid) {
1051 auto path = StringPrintf("/proc/%d/mounts", pid);
1052 char* tmp;
1053 if (lgetfilecon(path.c_str(), &tmp) < 0) {
1054 return false;
1055 }
1056 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
1057 || android::base::StartsWith(tmp, kMediaProviderCtx);
1058 freecon(tmp);
1059 return result;
1060}
1061
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001062bool IsFilesystemSupported(const std::string& fsType) {
1063 std::string supported;
1064 if (!ReadFileToString(kProcFilesystems, &supported)) {
1065 PLOG(ERROR) << "Failed to read supported filesystems";
1066 return false;
1067 }
1068 return supported.find(fsType + "\n") != std::string::npos;
1069}
1070
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001071bool IsSdcardfsUsed() {
1072 return IsFilesystemSupported("sdcardfs") &&
1073 base::GetBoolProperty(kExternalStorageSdcardfs, true);
1074}
1075
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001076status_t WipeBlockDevice(const std::string& path) {
1077 status_t res = -1;
1078 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001079 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001080
1081 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
1082 if (fd == -1) {
1083 PLOG(ERROR) << "Failed to open " << path;
1084 goto done;
1085 }
1086
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001087 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001088 PLOG(ERROR) << "Failed to determine size of " << path;
1089 goto done;
1090 }
1091
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001092 LOG(INFO) << "About to discard " << range[1] << " on " << path;
1093 if (ioctl(fd, BLKDISCARD, &range) == 0) {
1094 LOG(INFO) << "Discard success on " << path;
1095 res = 0;
1096 } else {
1097 PLOG(ERROR) << "Discard failure on " << path;
1098 }
1099
1100done:
1101 close(fd);
1102 return res;
1103}
1104
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001105static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001106 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001107 return false;
1108 } else {
1109 return true;
1110 }
1111}
1112
Jeff Sharkeybc40cc82015-06-18 14:25:08 -07001113std::string BuildKeyPath(const std::string& partGuid) {
1114 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1115}
1116
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001117std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001118 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001119}
1120
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001121std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001122 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001123}
1124
1125std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001126 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001127}
1128
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001129std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001130 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001131}
1132
Jeff Sharkey47695b22016-02-01 17:02:29 -07001133std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001134 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001135}
1136
1137std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001138 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001139}
1140
Calin Juravle79f55a42016-02-17 20:14:46 +00001141// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1142std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001143 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001144}
1145
Andreas Huber71cd43f2018-01-22 11:25:29 -08001146std::string BuildDataVendorCePath(userid_t userId) {
1147 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1148}
1149
1150std::string BuildDataVendorDePath(userid_t userId) {
1151 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1152}
1153
Paul Crowley3b71fc52017-10-09 10:55:21 -07001154std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001155 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001156 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001157 return "/data";
1158 } else {
1159 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001160 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001161 }
1162}
1163
Paul Crowley3b71fc52017-10-09 10:55:21 -07001164std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001165 // TODO: unify with installd path generation logic
1166 std::string data(BuildDataPath(volumeUuid));
1167 return StringPrintf("%s/media/%u", data.c_str(), userId);
1168}
1169
Paul Crowley3b71fc52017-10-09 10:55:21 -07001170std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001171 // TODO: unify with installd path generation logic
1172 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001173 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001174 std::string legacy = StringPrintf("%s/data", data.c_str());
1175 struct stat sb;
1176 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1177 /* /data/data is dir, return /data/data for legacy system */
1178 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001179 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001180 }
cjbaoeb501142017-04-12 00:09:00 +08001181 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001182}
1183
Paul Crowley3b71fc52017-10-09 10:55:21 -07001184std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001185 // TODO: unify with installd path generation logic
1186 std::string data(BuildDataPath(volumeUuid));
1187 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1188}
1189
Jeff Sharkey66270a22015-06-24 11:49:24 -07001190dev_t GetDevice(const std::string& path) {
1191 struct stat sb;
1192 if (stat(path.c_str(), &sb)) {
1193 PLOG(WARNING) << "Failed to stat " << path;
1194 return 0;
1195 } else {
1196 return sb.st_dev;
1197 }
1198}
1199
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001200status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001201 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001202
Tom Cherryd6127ef2017-06-15 17:13:56 -07001203 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001204
Tom Cherryd6127ef2017-06-15 17:13:56 -07001205 android::base::SetProperty(kRestoreconString, "");
1206 android::base::SetProperty(kRestoreconString, path);
1207
1208 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001209
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001210 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001211 return OK;
1212}
1213
Jeff Sharkey3472e522017-10-06 18:02:53 -06001214bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1215 // Shamelessly borrowed from android::base::Readlink()
1216 result->clear();
1217
1218 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1219 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1220 // waste memory to just start there. We add 1 so that we can recognize
1221 // whether it actually fit (rather than being truncated to 4095).
1222 std::vector<char> buf(4095 + 1);
1223 while (true) {
1224 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1225 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001226 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001227 // It fit! (If size == buf.size(), it may have been truncated.)
1228 if (static_cast<size_t>(size) < buf.size()) {
1229 result->assign(&buf[0], size);
1230 return true;
1231 }
1232 // Double our buffer and try again.
1233 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001234 }
1235}
1236
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001237static unsigned int GetMajorBlockVirtioBlk() {
1238 std::string devices;
1239 if (!ReadFileToString(kProcDevices, &devices)) {
1240 PLOG(ERROR) << "Unable to open /proc/devices";
1241 return 0;
1242 }
1243
1244 bool blockSection = false;
1245 for (auto line : android::base::Split(devices, "\n")) {
1246 if (line == "Block devices:") {
1247 blockSection = true;
1248 } else if (line == "Character devices:") {
1249 blockSection = false;
1250 } else if (blockSection) {
1251 auto tokens = android::base::Split(line, " ");
1252 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1253 return std::stoul(tokens[0]);
1254 }
1255 }
1256 }
1257
1258 return 0;
1259}
1260
1261bool IsVirtioBlkDevice(unsigned int major) {
1262 // Most virtualized platforms expose block devices with the virtio-blk
1263 // block device driver. Unfortunately, this driver does not use a fixed
1264 // major number, but relies on the kernel to assign one from a specific
1265 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1266 // per Documentation/devices.txt. This is true even for the latest Linux
1267 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1268 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1269 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001270}
1271
Sudheer Shanka295fb242019-01-16 23:04:07 -08001272static status_t findMountPointsWithPrefix(const std::string& prefix,
1273 std::list<std::string>& mountPoints) {
1274 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1275 // when the prefix is /foo/bar
1276 std::string prefixWithSlash(prefix);
1277 if (prefix.back() != '/') {
1278 android::base::StringAppendF(&prefixWithSlash, "/");
1279 }
1280
1281 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1282 if (!mnts) {
1283 PLOG(ERROR) << "Unable to open /proc/mounts";
1284 return -errno;
1285 }
1286
1287 // Some volumes can be stacked on each other, so force unmount in
1288 // reverse order to give us the best chance of success.
1289 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1290 while ((mnt = getmntent(mnts.get())) != nullptr) {
1291 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1292 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1293 mountPoints.push_front(mountPoint);
1294 }
1295 }
1296 return OK;
1297}
1298
1299// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1300status_t UnmountTreeWithPrefix(const std::string& prefix) {
1301 std::list<std::string> toUnmount;
1302 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1303 if (result < 0) {
1304 return result;
1305 }
1306 for (const auto& path : toUnmount) {
1307 if (umount2(path.c_str(), MNT_DETACH)) {
1308 PLOG(ERROR) << "Failed to unmount " << path;
1309 result = -errno;
1310 }
1311 }
1312 return result;
1313}
1314
1315status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001316 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1317 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001318 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001319 return -errno;
1320 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001321 return OK;
1322}
1323
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001324static status_t delete_dir_contents(DIR* dir) {
1325 // Shamelessly borrowed from android::installd
1326 int dfd = dirfd(dir);
1327 if (dfd < 0) {
1328 return -errno;
1329 }
1330
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001331 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001332 struct dirent* de;
1333 while ((de = readdir(dir))) {
1334 const char* name = de->d_name;
1335 if (de->d_type == DT_DIR) {
1336 /* always skip "." and ".." */
1337 if (name[0] == '.') {
1338 if (name[1] == 0) continue;
1339 if ((name[1] == '.') && (name[2] == 0)) continue;
1340 }
1341
1342 android::base::unique_fd subfd(
1343 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1344 if (subfd.get() == -1) {
1345 PLOG(ERROR) << "Couldn't openat " << name;
1346 result = -errno;
1347 continue;
1348 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001349 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1350 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001351 if (!subdirp) {
1352 PLOG(ERROR) << "Couldn't fdopendir " << name;
1353 result = -errno;
1354 continue;
1355 }
1356 result = delete_dir_contents(subdirp.get());
1357 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1358 PLOG(ERROR) << "Couldn't unlinkat " << name;
1359 result = -errno;
1360 }
1361 } else {
1362 if (unlinkat(dfd, name, 0) < 0) {
1363 PLOG(ERROR) << "Couldn't unlinkat " << name;
1364 result = -errno;
1365 }
1366 }
1367 }
1368 return result;
1369}
1370
1371status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001372 status_t res = DeleteDirContents(pathname);
1373 if (res < 0) {
1374 return res;
1375 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001376 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001377 PLOG(ERROR) << "rmdir failed on " << pathname;
1378 return -errno;
1379 }
1380 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1381 return OK;
1382}
1383
1384status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001385 // Shamelessly borrowed from android::installd
1386 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1387 if (!dirp) {
1388 if (errno == ENOENT) {
1389 return OK;
1390 }
1391 PLOG(ERROR) << "Failed to opendir " << pathname;
1392 return -errno;
1393 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001394 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001395}
1396
Paul Crowley298fa322018-10-30 15:59:24 -07001397// TODO(118708649): fix duplication with init/util.h
1398status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1399 android::base::Timer t;
1400 while (t.duration() < timeout) {
1401 struct stat sb;
1402 if (stat(filename, &sb) != -1) {
1403 LOG(INFO) << "wait for '" << filename << "' took " << t;
1404 return 0;
1405 }
1406 std::this_thread::sleep_for(10ms);
1407 }
1408 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1409 return -1;
1410}
1411
Paul Crowley621d9b92018-12-07 15:36:09 -08001412bool FsyncDirectory(const std::string& dirname) {
1413 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1414 if (fd == -1) {
1415 PLOG(ERROR) << "Failed to open " << dirname;
1416 return false;
1417 }
1418 if (fsync(fd) == -1) {
1419 if (errno == EROFS || errno == EINVAL) {
1420 PLOG(WARNING) << "Skip fsync " << dirname
1421 << " on a file system does not support synchronization";
1422 } else {
1423 PLOG(ERROR) << "Failed to fsync " << dirname;
1424 return false;
1425 }
1426 }
1427 return true;
1428}
1429
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001430bool writeStringToFile(const std::string& payload, const std::string& filename) {
1431 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1432 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1433 if (fd == -1) {
1434 PLOG(ERROR) << "Failed to open " << filename;
1435 return false;
1436 }
1437 if (!android::base::WriteStringToFd(payload, fd)) {
1438 PLOG(ERROR) << "Failed to write to " << filename;
1439 unlink(filename.c_str());
1440 return false;
1441 }
1442 // fsync as close won't guarantee flush data
1443 // see close(2), fsync(2) and b/68901441
1444 if (fsync(fd) == -1) {
1445 if (errno == EROFS || errno == EINVAL) {
1446 PLOG(WARNING) << "Skip fsync " << filename
1447 << " on a file system does not support synchronization";
1448 } else {
1449 PLOG(ERROR) << "Failed to fsync " << filename;
1450 unlink(filename.c_str());
1451 return false;
1452 }
1453 }
1454 return true;
1455}
1456
Martijn Coenen23c04452020-04-29 07:49:41 +02001457status_t AbortFuseConnections() {
1458 namespace fs = std::filesystem;
1459
1460 for (const auto& itEntry : fs::directory_iterator("/sys/fs/fuse/connections")) {
1461 std::string abortPath = itEntry.path().string() + "/abort";
1462 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1463 bool ret = writeStringToFile("1", abortPath);
1464 if (!ret) {
1465 LOG(WARNING) << "Failed to write to " << abortPath;
1466 }
1467 }
1468
1469 return OK;
1470}
1471
Ricky Wai07e64a42020-02-11 14:31:24 +00001472status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1473 if (access(path.c_str(), F_OK) != 0) {
1474 PLOG(WARNING) << "Dir does not exist: " << path;
1475 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1476 return -errno;
1477 }
1478 }
1479 return OK;
1480}
1481
Martijn Coenena4850062020-06-29 11:53:34 +02001482// Gets the sysfs path for parameters of the backing device info (bdi)
1483static std::string getBdiPathForMount(const std::string& mount) {
1484 // First figure out MAJOR:MINOR of mount. Simplest way is to stat the path.
1485 struct stat info;
1486 if (stat(mount.c_str(), &info) != 0) {
1487 PLOG(ERROR) << "Failed to stat " << mount;
1488 return "";
1489 }
1490 unsigned int maj = major(info.st_dev);
1491 unsigned int min = minor(info.st_dev);
1492
1493 return StringPrintf("/sys/class/bdi/%u:%u", maj, min);
1494}
1495
1496// Configures max_ratio for the FUSE filesystem.
1497void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio) {
1498 LOG(INFO) << "Configuring max_ratio of " << fuse_mount << " fuse filesystem to " << max_ratio;
1499 if (max_ratio > 100) {
1500 LOG(ERROR) << "Invalid max_ratio: " << max_ratio;
1501 return;
1502 }
1503 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1504 if (fuseBdiPath == "") {
1505 return;
1506 }
1507 std::string max_ratio_file = StringPrintf("%s/max_ratio", fuseBdiPath.c_str());
1508 unique_fd fd(TEMP_FAILURE_RETRY(open(max_ratio_file.c_str(), O_WRONLY | O_CLOEXEC)));
1509 if (fd.get() == -1) {
1510 PLOG(ERROR) << "Failed to open " << max_ratio_file;
1511 return;
1512 }
1513 LOG(INFO) << "Writing " << max_ratio << " to " << max_ratio_file;
1514 if (!WriteStringToFd(std::to_string(max_ratio), fd)) {
1515 PLOG(ERROR) << "Failed to write to " << max_ratio_file;
1516 }
1517}
1518
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001519// Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1520// writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
1521void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1522 LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1523 << read_ahead_kb << "kb";
Martijn Coenena4850062020-06-29 11:53:34 +02001524 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1525 if (fuseBdiPath == "") {
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001526 return;
1527 }
Martijn Coenena4850062020-06-29 11:53:34 +02001528 // We found the bdi path for our filesystem, time to configure read ahead!
1529 std::string read_ahead_file = StringPrintf("%s/read_ahead_kb", fuseBdiPath.c_str());
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001530 unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1531 if (fd.get() == -1) {
1532 PLOG(ERROR) << "Failed to open " << read_ahead_file;
1533 return;
1534 }
1535 LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1536 if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1537 PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1538 }
1539}
1540
Zima438b242019-09-25 14:37:38 +01001541status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1542 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1543 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1544 std::string fuse_path(
1545 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1546
1547 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1548 std::string pass_through_path(
1549 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001550
Zim1242be82020-01-22 18:22:29 +00001551 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1552 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001553 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001554 if (result != android::OK) {
1555 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1556 return -1;
1557 }
1558
Zim06b0caf2020-01-05 02:11:47 +00001559 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1560 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1561 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1562 // These bits should be consistent with what is set in zygote in
1563 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001564 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001565 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001566 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001567 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001568 return -1;
1569 }
1570
Zima438b242019-09-25 14:37:38 +01001571 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1572 if (result != android::OK) {
1573 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1574 return -1;
1575 }
1576
Zim26eec702020-01-31 16:00:58 +00001577 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001578 if (result != android::OK) {
1579 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1580 return -1;
1581 }
1582
Zim26eec702020-01-31 16:00:58 +00001583 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001584 if (result != android::OK) {
1585 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1586 return -1;
1587 }
1588
1589 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001590 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1591 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001592 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001593 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001594 return -1;
1595 }
Zime5393d42019-11-15 11:44:12 +00001596 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001597 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001598
1599 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001600 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001601 if (result != android::OK) {
1602 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1603 return -1;
1604 }
1605 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001606 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001607 }
1608
Nandana Dutta914cc72019-08-29 15:22:42 +01001609 // Open fuse fd.
1610 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1611 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001612 PLOG(ERROR) << "Failed to open /dev/fuse";
1613 return -1;
1614 }
1615
1616 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1617 // permission checks before routing to FUSE daemon.
1618 const auto opts = StringPrintf(
1619 "fd=%i,"
1620 "rootmode=40000,"
1621 "allow_other,"
1622 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001623 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001624
Zima438b242019-09-25 14:37:38 +01001625 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1626 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1627 opts.c_str()));
1628 if (result != 0) {
1629 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001630 return -errno;
1631 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001632
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001633 if (IsSdcardfsUsed()) {
Martijn Coenen86f21a22020-01-06 09:48:14 +01001634 std::string sdcardfs_path(
1635 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1636
1637 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1638 return BindMount(sdcardfs_path, pass_through_path);
1639 } else {
1640 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1641 return BindMount(absolute_lower_path, pass_through_path);
1642 }
Zima438b242019-09-25 14:37:38 +01001643}
1644
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001645status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1646 const std::string& relative_upper_path) {
1647 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1648 std::string pass_through_path(
1649 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1650
Zima438b242019-09-25 14:37:38 +01001651 // Best effort unmount pass_through path
1652 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001653 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1654 auto status = ForceUnmount(pass_through_path);
1655 if (status != android::OK) {
1656 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1657 }
Martijn Coenen57002612019-11-28 11:56:13 +01001658 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001659
1660 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001661 android::status_t result = ForceUnmount(fuse_path);
1662 sSleepOnUnmount = true;
1663 if (result != android::OK) {
1664 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1665 // Figure out why we get EBUSY and remove this special casing if possible.
1666 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1667 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1668 errno != ENOENT) {
1669 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1670 return -errno;
1671 }
Martijn Coenen57002612019-11-28 11:56:13 +01001672 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001673 }
Martijn Coenen57002612019-11-28 11:56:13 +01001674 rmdir(fuse_path.c_str());
1675
Zima438b242019-09-25 14:37:38 +01001676 return result;
Zim3623a212019-07-19 16:46:53 +01001677}
1678
Martijn Coenen62a4b272020-01-31 15:23:09 +01001679status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1680 std::string androidDir = volumeRoot + kAndroidDir;
1681 std::string androidDataDir = volumeRoot + kAppDataDir;
1682 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001683 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001684
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001685 bool useSdcardFs = IsSdcardfsUsed();
Martijn Coenen62a4b272020-01-31 15:23:09 +01001686
Martijn Coenen10570c02020-02-18 10:41:37 +01001687 // mode 0771 + sticky bit for inheriting GIDs
1688 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1689 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001690 PLOG(ERROR) << "Failed to create " << androidDir;
1691 return -errno;
1692 }
1693
1694 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001695 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001696 PLOG(ERROR) << "Failed to create " << androidDataDir;
1697 return -errno;
1698 }
1699
1700 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001701 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001702 PLOG(ERROR) << "Failed to create " << androidObbDir;
1703 return -errno;
1704 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001705 // Some other apps, like installers, have write access to the OBB directory
1706 // to pre-download them. To make sure newly created folders in this directory
1707 // have the right permissions, set a default ACL.
Martijn Coenen1129b812020-06-16 14:58:52 +02001708 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
Martijn Coenen62a4b272020-01-31 15:23:09 +01001709
Martijn Coenen10570c02020-02-18 10:41:37 +01001710 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001711 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1712 return -errno;
1713 }
1714
Martijn Coenen62a4b272020-01-31 15:23:09 +01001715 return OK;
1716}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001717} // namespace vold
1718} // namespace android