blob: 15a5e498beaad3e781fba94500a87d387a5b4938 [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;
66
Jeff Sharkeydeb24052015-03-02 21:01:40 -080067namespace android {
68namespace vold {
69
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070070security_context_t sBlkidContext = nullptr;
71security_context_t sBlkidUntrustedContext = nullptr;
72security_context_t sFsckContext = nullptr;
73security_context_t sFsckUntrustedContext = nullptr;
74
Paul Crowley56292ef2017-10-20 08:07:53 -070075bool sSleepOnUnmount = true;
76
Jeff Sharkey9c484982015-03-31 10:35:33 -070077static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070078static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070079
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070080static const char* kProcDevices = "/proc/devices";
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070081static const char* kProcFilesystems = "/proc/filesystems";
82
Martijn Coenen04bb17f2020-02-10 23:48:11 +010083static const char* kAndroidDir = "/Android/";
84static const char* kAppDataDir = "/Android/data/";
85static const char* kAppMediaDir = "/Android/media/";
86static const char* kAppObbDir = "/Android/obb/";
87
Ricky Wai07e64a42020-02-11 14:31:24 +000088static const char* kMediaProviderCtx = "u:r:mediaprovider:";
89static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
90
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060091// Lock used to protect process-level SELinux changes from racing with each
92// other between multiple threads.
93static std::mutex kSecurityLock;
94
Jeff Sharkeydeb24052015-03-02 21:01:40 -080095status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060096 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080097 const char* cpath = path.c_str();
98 status_t res = 0;
99
100 char* secontext = nullptr;
101 if (sehandle) {
102 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
103 setfscreatecon(secontext);
104 }
105 }
106
107 mode_t mode = 0660 | S_IFBLK;
108 if (mknod(cpath, mode, dev) < 0) {
109 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700110 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
111 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800112 res = -errno;
113 }
114 }
115
116 if (secontext) {
117 setfscreatecon(nullptr);
118 freecon(secontext);
119 }
120
121 return res;
122}
123
124status_t DestroyDeviceNode(const std::string& path) {
125 const char* cpath = path.c_str();
126 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
127 return -errno;
128 } else {
129 return OK;
130 }
131}
132
Martijn Coenen442bb832020-02-18 13:44:59 +0100133// Sets a default ACL on the directory.
134int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700135 if (IsSdcardfsUsed()) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100136 // sdcardfs magically takes care of this
137 return OK;
138 }
139
140 static constexpr size_t size =
141 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
142 auto buf = std::make_unique<uint8_t[]>(size);
143
144 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
145 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
146
147 posix_acl_xattr_entry* entry =
148 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
149
150 entry[0].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100151 // The existing mode_t mask has the ACL in the lower 9 bits:
152 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
153 // Use the mode_t masks to get these bits out, and shift them to get the
154 // correct value per entity.
155 //
156 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
157 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100158 entry[0].e_id = uid;
159
160 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100161 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100162 entry[1].e_id = gid;
163
164 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100165 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100166 entry[2].e_id = 0;
167
168 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
169
170 if (ret != 0) {
171 PLOG(ERROR) << "Failed to set default ACL on " << path;
172 }
173
174 return ret;
175}
176
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100177int SetQuotaInherit(const std::string& path) {
178 unsigned long flags;
179
180 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
181 if (fd == -1) {
182 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
183 return -1;
184 }
185
186 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
187 if (ret == -1) {
188 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
189 return ret;
190 }
191
192 flags |= FS_PROJINHERIT_FL;
193
194 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
195 if (ret == -1) {
196 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
197 return ret;
198 }
199
200 return 0;
201}
202
203int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100204 struct fsxattr fsx;
205
206 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
207 if (fd == -1) {
208 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
209 return -1;
210 }
211
212 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
213 if (ret == -1) {
214 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
215 return ret;
216 }
217
218 fsx.fsx_projid = projectId;
219 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
220}
221
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100222int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
223 long projectId) {
224 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
225
226 if (ret != 0) {
227 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100228 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100229
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700230 if (!IsSdcardfsUsed()) {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100231 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100232 }
233
234 return ret;
235}
236
Martijn Coenen816f4d92020-02-18 15:06:37 +0100237static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
238 namespace fs = std::filesystem;
239
240 // Setup the directory itself correctly
241 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
242 if (ret != OK) {
243 return ret;
244 }
245
246 // Fixup all of its file entries
247 for (const auto& itEntry : fs::directory_iterator(path)) {
248 ret = lchown(itEntry.path().c_str(), uid, gid);
249 if (ret != 0) {
250 return ret;
251 }
252
253 ret = chmod(itEntry.path().c_str(), mode);
254 if (ret != 0) {
255 return ret;
256 }
257
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700258 if (!IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +0100259 ret = SetQuotaProjectId(itEntry.path(), projectId);
260 if (ret != 0) {
261 return ret;
262 }
263 }
264 }
265
266 return OK;
267}
268
269int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
270 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100271 long projectId;
272 size_t pos;
273 int ret = 0;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700274 bool sdcardfsSupport = IsSdcardfsUsed();
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100275
276 // Make sure the Android/ directories exist and are setup correctly
277 ret = PrepareAndroidDirs(root);
278 if (ret != 0) {
279 LOG(ERROR) << "Failed to prepare Android/ directories.";
280 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100281 }
282
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100283 // Now create the application-specific subdir(s)
284 // path is something like /data/media/0/Android/data/com.foo/files
285 // First, chop off the volume root, eg /data/media/0
286 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100287
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100288 uid_t uid = appUid;
289 gid_t gid = AID_MEDIA_RW;
290 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100291
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100292 // Check that the next part matches one of the allowed Android/ dirs
293 if (StartsWith(pathFromRoot, kAppDataDir)) {
294 appDir = kAppDataDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700295 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100296 gid = AID_EXT_DATA_RW;
297 }
298 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
299 appDir = kAppMediaDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700300 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100301 gid = AID_MEDIA_RW;
302 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000303 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100304 appDir = kAppObbDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700305 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100306 gid = AID_EXT_OBB_RW;
307 }
308 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100309 LOG(ERROR) << "Invalid application directory: " << path;
310 return -EINVAL;
311 }
312
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100313 // mode = 770, plus sticky bit on directory to inherit GID when apps
314 // create subdirs
315 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100316 // the project ID for application-specific directories is directly
317 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100318
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100319 // Chop off the generic application-specific part, eg /Android/data/
320 // this leaves us with something like com.foo/files/
321 std::string leftToCreate = pathFromRoot.substr(appDir.length());
322 if (!EndsWith(leftToCreate, "/")) {
323 leftToCreate += "/";
324 }
325 std::string pathToCreate = root + appDir;
326 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100327 // Derive initial project ID
328 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
329 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
330 } else if (appDir == kAppObbDir) {
331 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
332 }
333
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100334 while ((pos = leftToCreate.find('/')) != std::string::npos) {
335 std::string component = leftToCreate.substr(0, pos + 1);
336 leftToCreate = leftToCreate.erase(0, pos + 1);
337 pathToCreate = pathToCreate + component;
338
339 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
340 // All dirs use the "app" project ID, except for the cache dirs in
341 // Android/data, eg Android/data/com.foo/cache
342 // Note that this "sticks" - eg subdirs of this dir need the same
343 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100344 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100345 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100346
347 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
348 // Fixup all files in this existing directory with the correct UID/GID
349 // and project ID.
350 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
351 } else {
352 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
353 }
354
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100355 if (ret != 0) {
356 return ret;
357 }
358
359 if (depth == 0) {
360 // Set the default ACL on the top-level application-specific directories,
361 // to ensure that even if applications run with a umask of 0077,
362 // new directories within these directories will allow the GID
363 // specified here to write; this is necessary for apps like
364 // installers and MTP, that require access here.
365 //
366 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100367 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100368 if (ret != 0) {
369 return ret;
370 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100371
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700372 if (!sdcardfsSupport) {
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100373 // Set project ID inheritance, so that future subdirectories inherit the
374 // same project ID
375 ret = SetQuotaInherit(pathToCreate);
376 if (ret != 0) {
377 return ret;
378 }
379 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100380 }
381
382 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100383 }
384
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100385 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100386}
387
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700388status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600389 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700390 const char* cpath = path.c_str();
391
392 char* secontext = nullptr;
393 if (sehandle) {
394 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
395 setfscreatecon(secontext);
396 }
397 }
398
399 int res = fs_prepare_dir(cpath, mode, uid, gid);
400
401 if (secontext) {
402 setfscreatecon(nullptr);
403 freecon(secontext);
404 }
405
406 if (res == 0) {
407 return OK;
408 } else {
409 return -errno;
410 }
411}
412
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800413status_t ForceUnmount(const std::string& path) {
414 const char* cpath = path.c_str();
415 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
416 return OK;
417 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700418 // Apps might still be handling eject request, so wait before
419 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700420 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700421
Jeff Sharkey3472e522017-10-06 18:02:53 -0600422 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700423 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700424 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
425 return OK;
426 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700427
Jeff Sharkey3472e522017-10-06 18:02:53 -0600428 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700429 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800430 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
431 return OK;
432 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700433
Jeff Sharkey3472e522017-10-06 18:02:53 -0600434 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700435 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700436 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
437 return OK;
438 }
Zim3623a212019-07-19 16:46:53 +0100439 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800440 return -errno;
441}
442
Ricky Wai07e64a42020-02-11 14:31:24 +0000443status_t KillProcessesWithMountPrefix(const std::string& path) {
444 if (KillProcessesWithMounts(path, SIGINT) == 0) {
445 return OK;
446 }
447 if (sSleepOnUnmount) sleep(5);
448
449 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
450 return OK;
451 }
452 if (sSleepOnUnmount) sleep(5);
453
454 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
455 return OK;
456 }
457 if (sSleepOnUnmount) sleep(5);
458
459 // Send SIGKILL a second time to determine if we've
460 // actually killed everyone mount
461 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
462 return OK;
463 }
464 PLOG(ERROR) << "Failed to kill processes using " << path;
465 return -EBUSY;
466}
467
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700468status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600469 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700470 return OK;
471 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700472 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700473
Jeff Sharkey3472e522017-10-06 18:02:53 -0600474 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700475 return OK;
476 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700477 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700478
Jeff Sharkey3472e522017-10-06 18:02:53 -0600479 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700480 return OK;
481 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700482 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700483
484 // Send SIGKILL a second time to determine if we've
485 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600486 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700487 return OK;
488 }
489 PLOG(ERROR) << "Failed to kill processes using " << path;
490 return -EBUSY;
491}
492
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700493status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800494 if (UnmountTree(target) < 0) {
495 return -errno;
496 }
497 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700498 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
499 return -errno;
500 }
501 return OK;
502}
503
Sudheer Shanka023b5392019-02-06 12:39:19 -0800504status_t Symlink(const std::string& target, const std::string& linkpath) {
505 if (Unlink(linkpath) < 0) {
506 return -errno;
507 }
508 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
509 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
510 return -errno;
511 }
512 return OK;
513}
514
515status_t Unlink(const std::string& linkpath) {
516 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
517 PLOG(ERROR) << "Failed to unlink " << linkpath;
518 return -errno;
519 }
520 return OK;
521}
522
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000523status_t CreateDir(const std::string& dir, mode_t mode) {
524 struct stat sb;
525 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
526 if (S_ISDIR(sb.st_mode)) {
527 return OK;
528 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
529 PLOG(ERROR) << "Failed to unlink " << dir;
530 return -errno;
531 }
532 } else if (errno != ENOENT) {
533 PLOG(ERROR) << "Failed to stat " << dir;
534 return -errno;
535 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800536 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000537 PLOG(ERROR) << "Failed to mkdir " << dir;
538 return -errno;
539 }
540 return OK;
541}
542
Jeff Sharkey3472e522017-10-06 18:02:53 -0600543bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
544 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800545 size_t start = 0;
546 while (true) {
547 start = raw.find(qual, start);
548 if (start == std::string::npos) return false;
549 if (start == 0 || raw[start - 1] == ' ') {
550 break;
551 }
552 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600553 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600554 start += qual.length();
555
556 auto end = raw.find("\"", start);
557 if (end == std::string::npos) return false;
558
559 *value = raw.substr(start, end - start);
560 return true;
561}
562
Paul Crowley14c8c072018-09-18 13:30:21 -0700563static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
564 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600565 fsType->clear();
566 fsUuid->clear();
567 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700568
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700569 std::vector<std::string> cmd;
570 cmd.push_back(kBlkidPath);
571 cmd.push_back("-c");
572 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700573 cmd.push_back("-s");
574 cmd.push_back("TYPE");
575 cmd.push_back("-s");
576 cmd.push_back("UUID");
577 cmd.push_back("-s");
578 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700579 cmd.push_back(path);
580
581 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800582 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700583 if (res != OK) {
584 LOG(WARNING) << "blkid failed to identify " << path;
585 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700586 }
587
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700588 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700589 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600590 FindValue(line, "TYPE", fsType);
591 FindValue(line, "UUID", fsUuid);
592 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700593 }
594
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700595 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700596}
597
Paul Crowley14c8c072018-09-18 13:30:21 -0700598status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
599 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700600 return readMetadata(path, fsType, fsUuid, fsLabel, false);
601}
602
Paul Crowley14c8c072018-09-18 13:30:21 -0700603status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
604 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700605 return readMetadata(path, fsType, fsUuid, fsLabel, true);
606}
607
Paul Crowleyde2d6202018-11-30 11:43:47 -0800608static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
609 std::vector<const char*> argv;
610 argv.reserve(args.size() + 1);
611 for (const auto& arg : args) {
612 if (argv.empty()) {
613 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700614 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800615 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700616 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800617 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700618 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800619 argv.emplace_back(nullptr);
620 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700621}
622
Paul Crowleyde2d6202018-11-30 11:43:47 -0800623static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
624 android::base::unique_fd ufd) {
625 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700626 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800627 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700628 return -errno;
629 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800630 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700631 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800632 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700633 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800634 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700635 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800636 return OK;
637}
638
639status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
640 security_context_t context) {
641 auto argv = ConvertToArgv(args);
642
Paul Crowleye6d76632018-11-30 11:43:47 -0800643 android::base::unique_fd pipe_read, pipe_write;
644 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
645 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800646 return -errno;
647 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800648
649 pid_t pid = fork();
650 if (pid == 0) {
651 if (context) {
652 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800653 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800654 abort();
655 }
656 }
657 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800658 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
659 PLOG(ERROR) << "dup2 in ForkExecvp";
660 _exit(EXIT_FAILURE);
661 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800662 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800663 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800664 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800665 _exit(EXIT_FAILURE);
666 }
667 if (pid == -1) {
668 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700669 return -errno;
670 }
671
Paul Crowleyde2d6202018-11-30 11:43:47 -0800672 pipe_write.reset();
673 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
674 if (st != 0) return st;
675
676 int status;
677 if (waitpid(pid, &status, 0) == -1) {
678 PLOG(ERROR) << "waitpid in ForkExecvp";
679 return -errno;
680 }
681 if (!WIFEXITED(status)) {
682 LOG(ERROR) << "Process did not exit normally, status: " << status;
683 return -ECHILD;
684 }
685 if (WEXITSTATUS(status)) {
686 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
687 return WEXITSTATUS(status);
688 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700689 return OK;
690}
691
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700692pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800693 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700694
695 pid_t pid = fork();
696 if (pid == 0) {
697 close(STDIN_FILENO);
698 close(STDOUT_FILENO);
699 close(STDERR_FILENO);
700
Paul Crowleyde2d6202018-11-30 11:43:47 -0800701 execvp(argv[0], const_cast<char**>(argv.data()));
702 PLOG(ERROR) << "exec in ForkExecvpAsync";
703 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700704 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700705 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800706 PLOG(ERROR) << "fork in ForkExecvpAsync";
707 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700708 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700709 return pid;
710}
711
Jeff Sharkey9c484982015-03-31 10:35:33 -0700712status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100713 out.resize(bytes);
714 return ReadRandomBytes(bytes, &out[0]);
715}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700716
Pavel Grafove2e2d302017-08-01 17:15:53 +0100717status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700718 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
719 if (fd == -1) {
720 return -errno;
721 }
722
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800723 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100724 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700725 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100726 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700727 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700728 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700729
730 if (bytes == 0) {
731 return OK;
732 } else {
733 return -EIO;
734 }
735}
736
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600737status_t GenerateRandomUuid(std::string& out) {
738 status_t res = ReadRandomBytes(16, out);
739 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700740 out[6] &= 0x0f; /* clear version */
741 out[6] |= 0x40; /* set to version 4 */
742 out[8] &= 0x3f; /* clear variant */
743 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600744 }
745 return res;
746}
747
Jeff Sharkey9c484982015-03-31 10:35:33 -0700748status_t HexToStr(const std::string& hex, std::string& str) {
749 str.clear();
750 bool even = true;
751 char cur = 0;
752 for (size_t i = 0; i < hex.size(); i++) {
753 int val = 0;
754 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700755 // clang-format off
756 case ' ': case '-': case ':': continue;
757 case 'f': case 'F': val = 15; break;
758 case 'e': case 'E': val = 14; break;
759 case 'd': case 'D': val = 13; break;
760 case 'c': case 'C': val = 12; break;
761 case 'b': case 'B': val = 11; break;
762 case 'a': case 'A': val = 10; break;
763 case '9': val = 9; break;
764 case '8': val = 8; break;
765 case '7': val = 7; break;
766 case '6': val = 6; break;
767 case '5': val = 5; break;
768 case '4': val = 4; break;
769 case '3': val = 3; break;
770 case '2': val = 2; break;
771 case '1': val = 1; break;
772 case '0': val = 0; break;
773 default: return -EINVAL;
774 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700775 }
776
777 if (even) {
778 cur = val << 4;
779 } else {
780 cur += val;
781 str.push_back(cur);
782 cur = 0;
783 }
784 even = !even;
785 }
786 return even ? OK : -EINVAL;
787}
788
789static const char* kLookup = "0123456789abcdef";
790
791status_t StrToHex(const std::string& str, std::string& hex) {
792 hex.clear();
793 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700794 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700795 hex.push_back(kLookup[str[i] & 0x0F]);
796 }
797 return OK;
798}
799
Pavel Grafove2e2d302017-08-01 17:15:53 +0100800status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
801 hex.clear();
802 for (size_t i = 0; i < str.size(); i++) {
803 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
804 hex.push_back(kLookup[str.data()[i] & 0x0F]);
805 }
806 return OK;
807}
808
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700809status_t NormalizeHex(const std::string& in, std::string& out) {
810 std::string tmp;
811 if (HexToStr(in, tmp)) {
812 return -EINVAL;
813 }
814 return StrToHex(tmp, out);
815}
816
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200817status_t GetBlockDevSize(int fd, uint64_t* size) {
818 if (ioctl(fd, BLKGETSIZE64, size)) {
819 return -errno;
820 }
821
822 return OK;
823}
824
825status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
826 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
827 status_t res = OK;
828
829 if (fd < 0) {
830 return -errno;
831 }
832
833 res = GetBlockDevSize(fd, size);
834
835 close(fd);
836
837 return res;
838}
839
840status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
841 uint64_t size;
842 status_t res = GetBlockDevSize(path, &size);
843
844 if (res != OK) {
845 return res;
846 }
847
848 *nr_sec = size / 512;
849
850 return OK;
851}
852
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700853uint64_t GetFreeBytes(const std::string& path) {
854 struct statvfs sb;
855 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700856 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700857 } else {
858 return -1;
859 }
860}
861
862// TODO: borrowed from frameworks/native/libs/diskusage/ which should
863// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700864static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700865 int64_t blksize = s->st_blksize;
866 // count actual blocks used instead of nominal file size
867 int64_t size = s->st_blocks * 512;
868
869 if (blksize) {
870 /* round up to filesystem block size */
871 size = (size + blksize - 1) & (~(blksize - 1));
872 }
873
874 return size;
875}
876
877// TODO: borrowed from frameworks/native/libs/diskusage/ which should
878// eventually be migrated into system/
879int64_t calculate_dir_size(int dfd) {
880 int64_t size = 0;
881 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700882 DIR* d;
883 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700884
885 d = fdopendir(dfd);
886 if (d == NULL) {
887 close(dfd);
888 return 0;
889 }
890
891 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700892 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700893 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
894 size += stat_size(&s);
895 }
896 if (de->d_type == DT_DIR) {
897 int subfd;
898
899 /* always skip "." and ".." */
900 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700901 if (name[1] == 0) continue;
902 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700903 }
904
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600905 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700906 if (subfd >= 0) {
907 size += calculate_dir_size(subfd);
908 }
909 }
910 }
911 closedir(d);
912 return size;
913}
914
915uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600916 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700917 if (dirfd < 0) {
918 PLOG(WARNING) << "Failed to open " << path;
919 return -1;
920 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700921 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700922 }
923}
924
Ricky Wai07e64a42020-02-11 14:31:24 +0000925// TODO: Use a better way to determine if it's media provider app.
926bool IsFuseDaemon(const pid_t pid) {
927 auto path = StringPrintf("/proc/%d/mounts", pid);
928 char* tmp;
929 if (lgetfilecon(path.c_str(), &tmp) < 0) {
930 return false;
931 }
932 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
933 || android::base::StartsWith(tmp, kMediaProviderCtx);
934 freecon(tmp);
935 return result;
936}
937
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700938bool IsFilesystemSupported(const std::string& fsType) {
939 std::string supported;
940 if (!ReadFileToString(kProcFilesystems, &supported)) {
941 PLOG(ERROR) << "Failed to read supported filesystems";
942 return false;
943 }
944 return supported.find(fsType + "\n") != std::string::npos;
945}
946
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700947bool IsSdcardfsUsed() {
948 return IsFilesystemSupported("sdcardfs") &&
949 base::GetBoolProperty(kExternalStorageSdcardfs, true);
950}
951
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700952status_t WipeBlockDevice(const std::string& path) {
953 status_t res = -1;
954 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200955 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700956
957 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
958 if (fd == -1) {
959 PLOG(ERROR) << "Failed to open " << path;
960 goto done;
961 }
962
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200963 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700964 PLOG(ERROR) << "Failed to determine size of " << path;
965 goto done;
966 }
967
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700968 LOG(INFO) << "About to discard " << range[1] << " on " << path;
969 if (ioctl(fd, BLKDISCARD, &range) == 0) {
970 LOG(INFO) << "Discard success on " << path;
971 res = 0;
972 } else {
973 PLOG(ERROR) << "Discard failure on " << path;
974 }
975
976done:
977 close(fd);
978 return res;
979}
980
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800981static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700982 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800983 return false;
984 } else {
985 return true;
986 }
987}
988
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700989std::string BuildKeyPath(const std::string& partGuid) {
990 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
991}
992
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600993std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700994 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600995}
996
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800997std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700998 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700999}
1000
1001std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001002 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001003}
1004
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001005std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001006 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001007}
1008
Jeff Sharkey47695b22016-02-01 17:02:29 -07001009std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001010 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001011}
1012
1013std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001014 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001015}
1016
Calin Juravle79f55a42016-02-17 20:14:46 +00001017// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1018std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001019 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001020}
1021
Andreas Huber71cd43f2018-01-22 11:25:29 -08001022std::string BuildDataVendorCePath(userid_t userId) {
1023 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1024}
1025
1026std::string BuildDataVendorDePath(userid_t userId) {
1027 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1028}
1029
Paul Crowley3b71fc52017-10-09 10:55:21 -07001030std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001031 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001032 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001033 return "/data";
1034 } else {
1035 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001036 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001037 }
1038}
1039
Paul Crowley3b71fc52017-10-09 10:55:21 -07001040std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001041 // TODO: unify with installd path generation logic
1042 std::string data(BuildDataPath(volumeUuid));
1043 return StringPrintf("%s/media/%u", data.c_str(), userId);
1044}
1045
Paul Crowley3b71fc52017-10-09 10:55:21 -07001046std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001047 // TODO: unify with installd path generation logic
1048 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001049 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001050 std::string legacy = StringPrintf("%s/data", data.c_str());
1051 struct stat sb;
1052 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1053 /* /data/data is dir, return /data/data for legacy system */
1054 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001055 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001056 }
cjbaoeb501142017-04-12 00:09:00 +08001057 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001058}
1059
Paul Crowley3b71fc52017-10-09 10:55:21 -07001060std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001061 // TODO: unify with installd path generation logic
1062 std::string data(BuildDataPath(volumeUuid));
1063 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1064}
1065
Jeff Sharkey66270a22015-06-24 11:49:24 -07001066dev_t GetDevice(const std::string& path) {
1067 struct stat sb;
1068 if (stat(path.c_str(), &sb)) {
1069 PLOG(WARNING) << "Failed to stat " << path;
1070 return 0;
1071 } else {
1072 return sb.st_dev;
1073 }
1074}
1075
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001076status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001077 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001078
Tom Cherryd6127ef2017-06-15 17:13:56 -07001079 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001080
Tom Cherryd6127ef2017-06-15 17:13:56 -07001081 android::base::SetProperty(kRestoreconString, "");
1082 android::base::SetProperty(kRestoreconString, path);
1083
1084 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001085
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001086 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001087 return OK;
1088}
1089
Jeff Sharkey3472e522017-10-06 18:02:53 -06001090bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1091 // Shamelessly borrowed from android::base::Readlink()
1092 result->clear();
1093
1094 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1095 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1096 // waste memory to just start there. We add 1 so that we can recognize
1097 // whether it actually fit (rather than being truncated to 4095).
1098 std::vector<char> buf(4095 + 1);
1099 while (true) {
1100 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1101 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001102 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001103 // It fit! (If size == buf.size(), it may have been truncated.)
1104 if (static_cast<size_t>(size) < buf.size()) {
1105 result->assign(&buf[0], size);
1106 return true;
1107 }
1108 // Double our buffer and try again.
1109 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001110 }
1111}
1112
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001113static unsigned int GetMajorBlockVirtioBlk() {
1114 std::string devices;
1115 if (!ReadFileToString(kProcDevices, &devices)) {
1116 PLOG(ERROR) << "Unable to open /proc/devices";
1117 return 0;
1118 }
1119
1120 bool blockSection = false;
1121 for (auto line : android::base::Split(devices, "\n")) {
1122 if (line == "Block devices:") {
1123 blockSection = true;
1124 } else if (line == "Character devices:") {
1125 blockSection = false;
1126 } else if (blockSection) {
1127 auto tokens = android::base::Split(line, " ");
1128 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1129 return std::stoul(tokens[0]);
1130 }
1131 }
1132 }
1133
1134 return 0;
1135}
1136
1137bool IsVirtioBlkDevice(unsigned int major) {
1138 // Most virtualized platforms expose block devices with the virtio-blk
1139 // block device driver. Unfortunately, this driver does not use a fixed
1140 // major number, but relies on the kernel to assign one from a specific
1141 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1142 // per Documentation/devices.txt. This is true even for the latest Linux
1143 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1144 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1145 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001146}
1147
Sudheer Shanka295fb242019-01-16 23:04:07 -08001148static status_t findMountPointsWithPrefix(const std::string& prefix,
1149 std::list<std::string>& mountPoints) {
1150 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1151 // when the prefix is /foo/bar
1152 std::string prefixWithSlash(prefix);
1153 if (prefix.back() != '/') {
1154 android::base::StringAppendF(&prefixWithSlash, "/");
1155 }
1156
1157 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1158 if (!mnts) {
1159 PLOG(ERROR) << "Unable to open /proc/mounts";
1160 return -errno;
1161 }
1162
1163 // Some volumes can be stacked on each other, so force unmount in
1164 // reverse order to give us the best chance of success.
1165 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1166 while ((mnt = getmntent(mnts.get())) != nullptr) {
1167 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1168 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1169 mountPoints.push_front(mountPoint);
1170 }
1171 }
1172 return OK;
1173}
1174
1175// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1176status_t UnmountTreeWithPrefix(const std::string& prefix) {
1177 std::list<std::string> toUnmount;
1178 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1179 if (result < 0) {
1180 return result;
1181 }
1182 for (const auto& path : toUnmount) {
1183 if (umount2(path.c_str(), MNT_DETACH)) {
1184 PLOG(ERROR) << "Failed to unmount " << path;
1185 result = -errno;
1186 }
1187 }
1188 return result;
1189}
1190
1191status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001192 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1193 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001194 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001195 return -errno;
1196 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001197 return OK;
1198}
1199
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001200static status_t delete_dir_contents(DIR* dir) {
1201 // Shamelessly borrowed from android::installd
1202 int dfd = dirfd(dir);
1203 if (dfd < 0) {
1204 return -errno;
1205 }
1206
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001207 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001208 struct dirent* de;
1209 while ((de = readdir(dir))) {
1210 const char* name = de->d_name;
1211 if (de->d_type == DT_DIR) {
1212 /* always skip "." and ".." */
1213 if (name[0] == '.') {
1214 if (name[1] == 0) continue;
1215 if ((name[1] == '.') && (name[2] == 0)) continue;
1216 }
1217
1218 android::base::unique_fd subfd(
1219 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1220 if (subfd.get() == -1) {
1221 PLOG(ERROR) << "Couldn't openat " << name;
1222 result = -errno;
1223 continue;
1224 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001225 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1226 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001227 if (!subdirp) {
1228 PLOG(ERROR) << "Couldn't fdopendir " << name;
1229 result = -errno;
1230 continue;
1231 }
1232 result = delete_dir_contents(subdirp.get());
1233 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1234 PLOG(ERROR) << "Couldn't unlinkat " << name;
1235 result = -errno;
1236 }
1237 } else {
1238 if (unlinkat(dfd, name, 0) < 0) {
1239 PLOG(ERROR) << "Couldn't unlinkat " << name;
1240 result = -errno;
1241 }
1242 }
1243 }
1244 return result;
1245}
1246
1247status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001248 status_t res = DeleteDirContents(pathname);
1249 if (res < 0) {
1250 return res;
1251 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001252 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001253 PLOG(ERROR) << "rmdir failed on " << pathname;
1254 return -errno;
1255 }
1256 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1257 return OK;
1258}
1259
1260status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001261 // Shamelessly borrowed from android::installd
1262 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1263 if (!dirp) {
1264 if (errno == ENOENT) {
1265 return OK;
1266 }
1267 PLOG(ERROR) << "Failed to opendir " << pathname;
1268 return -errno;
1269 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001270 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001271}
1272
Paul Crowley298fa322018-10-30 15:59:24 -07001273// TODO(118708649): fix duplication with init/util.h
1274status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1275 android::base::Timer t;
1276 while (t.duration() < timeout) {
1277 struct stat sb;
1278 if (stat(filename, &sb) != -1) {
1279 LOG(INFO) << "wait for '" << filename << "' took " << t;
1280 return 0;
1281 }
1282 std::this_thread::sleep_for(10ms);
1283 }
1284 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1285 return -1;
1286}
1287
Paul Crowley621d9b92018-12-07 15:36:09 -08001288bool FsyncDirectory(const std::string& dirname) {
1289 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1290 if (fd == -1) {
1291 PLOG(ERROR) << "Failed to open " << dirname;
1292 return false;
1293 }
1294 if (fsync(fd) == -1) {
1295 if (errno == EROFS || errno == EINVAL) {
1296 PLOG(WARNING) << "Skip fsync " << dirname
1297 << " on a file system does not support synchronization";
1298 } else {
1299 PLOG(ERROR) << "Failed to fsync " << dirname;
1300 return false;
1301 }
1302 }
1303 return true;
1304}
1305
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001306bool writeStringToFile(const std::string& payload, const std::string& filename) {
1307 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1308 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1309 if (fd == -1) {
1310 PLOG(ERROR) << "Failed to open " << filename;
1311 return false;
1312 }
1313 if (!android::base::WriteStringToFd(payload, fd)) {
1314 PLOG(ERROR) << "Failed to write to " << filename;
1315 unlink(filename.c_str());
1316 return false;
1317 }
1318 // fsync as close won't guarantee flush data
1319 // see close(2), fsync(2) and b/68901441
1320 if (fsync(fd) == -1) {
1321 if (errno == EROFS || errno == EINVAL) {
1322 PLOG(WARNING) << "Skip fsync " << filename
1323 << " on a file system does not support synchronization";
1324 } else {
1325 PLOG(ERROR) << "Failed to fsync " << filename;
1326 unlink(filename.c_str());
1327 return false;
1328 }
1329 }
1330 return true;
1331}
1332
Ricky Wai07e64a42020-02-11 14:31:24 +00001333status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1334 if (access(path.c_str(), F_OK) != 0) {
1335 PLOG(WARNING) << "Dir does not exist: " << path;
1336 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1337 return -errno;
1338 }
1339 }
1340 return OK;
1341}
1342
Zima438b242019-09-25 14:37:38 +01001343status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1344 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1345 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1346 std::string fuse_path(
1347 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1348
1349 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1350 std::string pass_through_path(
1351 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001352
Zim1242be82020-01-22 18:22:29 +00001353 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1354 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001355 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001356 if (result != android::OK) {
1357 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1358 return -1;
1359 }
1360
Zim06b0caf2020-01-05 02:11:47 +00001361 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1362 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1363 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1364 // These bits should be consistent with what is set in zygote in
1365 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001366 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001367 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001368 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001369 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001370 return -1;
1371 }
1372
Zima438b242019-09-25 14:37:38 +01001373 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1374 if (result != android::OK) {
1375 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1376 return -1;
1377 }
1378
Zim26eec702020-01-31 16:00:58 +00001379 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001380 if (result != android::OK) {
1381 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1382 return -1;
1383 }
1384
Zim26eec702020-01-31 16:00:58 +00001385 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001386 if (result != android::OK) {
1387 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1388 return -1;
1389 }
1390
1391 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001392 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1393 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001394 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001395 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001396 return -1;
1397 }
Zime5393d42019-11-15 11:44:12 +00001398 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001399 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001400
1401 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001402 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001403 if (result != android::OK) {
1404 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1405 return -1;
1406 }
1407 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001408 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001409 }
1410
Nandana Dutta914cc72019-08-29 15:22:42 +01001411 // Open fuse fd.
1412 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1413 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001414 PLOG(ERROR) << "Failed to open /dev/fuse";
1415 return -1;
1416 }
1417
1418 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1419 // permission checks before routing to FUSE daemon.
1420 const auto opts = StringPrintf(
1421 "fd=%i,"
1422 "rootmode=40000,"
1423 "allow_other,"
1424 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001425 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001426
Zima438b242019-09-25 14:37:38 +01001427 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1428 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1429 opts.c_str()));
1430 if (result != 0) {
1431 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001432 return -errno;
1433 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001434
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001435 if (IsSdcardfsUsed()) {
Martijn Coenen86f21a22020-01-06 09:48:14 +01001436 std::string sdcardfs_path(
1437 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1438
1439 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1440 return BindMount(sdcardfs_path, pass_through_path);
1441 } else {
1442 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1443 return BindMount(absolute_lower_path, pass_through_path);
1444 }
Zima438b242019-09-25 14:37:38 +01001445}
1446
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001447status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1448 const std::string& relative_upper_path) {
1449 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1450 std::string pass_through_path(
1451 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1452
Zima438b242019-09-25 14:37:38 +01001453 // Best effort unmount pass_through path
1454 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001455 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1456 auto status = ForceUnmount(pass_through_path);
1457 if (status != android::OK) {
1458 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1459 }
Martijn Coenen57002612019-11-28 11:56:13 +01001460 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001461
1462 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001463 android::status_t result = ForceUnmount(fuse_path);
1464 sSleepOnUnmount = true;
1465 if (result != android::OK) {
1466 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1467 // Figure out why we get EBUSY and remove this special casing if possible.
1468 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1469 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1470 errno != ENOENT) {
1471 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1472 return -errno;
1473 }
Martijn Coenen57002612019-11-28 11:56:13 +01001474 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001475 }
Martijn Coenen57002612019-11-28 11:56:13 +01001476 rmdir(fuse_path.c_str());
1477
Zima438b242019-09-25 14:37:38 +01001478 return result;
Zim3623a212019-07-19 16:46:53 +01001479}
1480
Martijn Coenen62a4b272020-01-31 15:23:09 +01001481status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1482 std::string androidDir = volumeRoot + kAndroidDir;
1483 std::string androidDataDir = volumeRoot + kAppDataDir;
1484 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001485 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001486
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001487 bool useSdcardFs = IsSdcardfsUsed();
Martijn Coenen62a4b272020-01-31 15:23:09 +01001488
Martijn Coenen10570c02020-02-18 10:41:37 +01001489 // mode 0771 + sticky bit for inheriting GIDs
1490 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1491 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001492 PLOG(ERROR) << "Failed to create " << androidDir;
1493 return -errno;
1494 }
1495
1496 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001497 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001498 PLOG(ERROR) << "Failed to create " << androidDataDir;
1499 return -errno;
1500 }
1501
1502 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001503 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001504 PLOG(ERROR) << "Failed to create " << androidObbDir;
1505 return -errno;
1506 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001507 // Some other apps, like installers, have write access to the OBB directory
1508 // to pre-download them. To make sure newly created folders in this directory
1509 // have the right permissions, set a default ACL.
1510 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001511
Martijn Coenen10570c02020-02-18 10:41:37 +01001512 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001513 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1514 return -errno;
1515 }
1516
Martijn Coenen62a4b272020-01-31 15:23:09 +01001517 return OK;
1518}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001519} // namespace vold
1520} // namespace android