blob: 35839aceb88377e128fcde024d26644949b430a9 [file] [log] [blame]
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkeydeb24052015-03-02 21:01:40 -080017#include "Utils.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070018
Jeff Sharkeydeb24052015-03-02 21:01:40 -080019#include "Process.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070020#include "sehandle.h"
Jeff Sharkeydeb24052015-03-02 21:01:40 -080021
Paul Crowley298fa322018-10-30 15:59:24 -070022#include <android-base/chrono_utils.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080023#include <android-base/file.h>
24#include <android-base/logging.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070025#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080026#include <android-base/stringprintf.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070027#include <android-base/strings.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070028#include <android-base/unique_fd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080029#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070030#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070031#include <private/android_filesystem_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080032
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070033#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080034#include <fcntl.h>
35#include <linux/fs.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010036#include <linux/posix_acl.h>
37#include <linux/posix_acl_xattr.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070038#include <mntent.h>
39#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080040#include <stdlib.h>
41#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080042#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070043#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070044#include <sys/sysmacros.h>
45#include <sys/types.h>
46#include <sys/wait.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010047#include <sys/xattr.h>
Paul Crowley747b4212019-04-05 04:09:57 -070048#include <unistd.h>
Paul Crowley298fa322018-10-30 15:59:24 -070049
Sudheer Shanka89ddf992018-09-25 14:22:07 -070050#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070051#include <mutex>
Martijn Coenen04bb17f2020-02-10 23:48:11 +010052#include <regex>
Paul Crowley298fa322018-10-30 15:59:24 -070053#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080054
55#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070056#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080057#endif
58
Paul Crowley298fa322018-10-30 15:59:24 -070059using namespace std::chrono_literals;
Martijn Coenenba9868b2020-01-31 15:49:24 +010060using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070061using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010062using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070063using android::base::StringPrintf;
64
Jeff Sharkeydeb24052015-03-02 21:01:40 -080065namespace android {
66namespace vold {
67
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070068security_context_t sBlkidContext = nullptr;
69security_context_t sBlkidUntrustedContext = nullptr;
70security_context_t sFsckContext = nullptr;
71security_context_t sFsckUntrustedContext = nullptr;
72
Paul Crowley56292ef2017-10-20 08:07:53 -070073bool sSleepOnUnmount = true;
74
Jeff Sharkey9c484982015-03-31 10:35:33 -070075static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070076static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070077
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070078static const char* kProcFilesystems = "/proc/filesystems";
79
Martijn Coenen04bb17f2020-02-10 23:48:11 +010080static const char* kAndroidDir = "/Android/";
81static const char* kAppDataDir = "/Android/data/";
82static const char* kAppMediaDir = "/Android/media/";
83static const char* kAppObbDir = "/Android/obb/";
84
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060085// Lock used to protect process-level SELinux changes from racing with each
86// other between multiple threads.
87static std::mutex kSecurityLock;
88
Jeff Sharkeydeb24052015-03-02 21:01:40 -080089status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060090 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080091 const char* cpath = path.c_str();
92 status_t res = 0;
93
94 char* secontext = nullptr;
95 if (sehandle) {
96 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
97 setfscreatecon(secontext);
98 }
99 }
100
101 mode_t mode = 0660 | S_IFBLK;
102 if (mknod(cpath, mode, dev) < 0) {
103 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700104 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
105 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800106 res = -errno;
107 }
108 }
109
110 if (secontext) {
111 setfscreatecon(nullptr);
112 freecon(secontext);
113 }
114
115 return res;
116}
117
118status_t DestroyDeviceNode(const std::string& path) {
119 const char* cpath = path.c_str();
120 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
121 return -errno;
122 } else {
123 return OK;
124 }
125}
126
Martijn Coenen442bb832020-02-18 13:44:59 +0100127// Sets a default ACL on the directory.
128int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100129 if (IsFilesystemSupported("sdcardfs")) {
130 // sdcardfs magically takes care of this
131 return OK;
132 }
133
134 static constexpr size_t size =
135 sizeof(posix_acl_xattr_header) + 3 * sizeof(posix_acl_xattr_entry);
136 auto buf = std::make_unique<uint8_t[]>(size);
137
138 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
139 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
140
141 posix_acl_xattr_entry* entry =
142 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
143
144 entry[0].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100145 // The existing mode_t mask has the ACL in the lower 9 bits:
146 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
147 // Use the mode_t masks to get these bits out, and shift them to get the
148 // correct value per entity.
149 //
150 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
151 entry[0].e_perm = (mode & S_IRWXU) >> 6;
Martijn Coenen879fa802020-02-11 12:37:25 +0100152 entry[0].e_id = uid;
153
154 entry[1].e_tag = ACL_GROUP_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100155 entry[1].e_perm = (mode & S_IRWXG) >> 3;
Martijn Coenen879fa802020-02-11 12:37:25 +0100156 entry[1].e_id = gid;
157
158 entry[2].e_tag = ACL_OTHER;
Martijn Coenen442bb832020-02-18 13:44:59 +0100159 entry[2].e_perm = mode & S_IRWXO;
Martijn Coenen879fa802020-02-11 12:37:25 +0100160 entry[2].e_id = 0;
161
162 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
163
164 if (ret != 0) {
165 PLOG(ERROR) << "Failed to set default ACL on " << path;
166 }
167
168 return ret;
169}
170
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100171int SetQuotaInherit(const std::string& path) {
172 unsigned long flags;
173
174 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
175 if (fd == -1) {
176 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
177 return -1;
178 }
179
180 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
181 if (ret == -1) {
182 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
183 return ret;
184 }
185
186 flags |= FS_PROJINHERIT_FL;
187
188 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
189 if (ret == -1) {
190 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
191 return ret;
192 }
193
194 return 0;
195}
196
197int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100198 struct fsxattr fsx;
199
200 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
201 if (fd == -1) {
202 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
203 return -1;
204 }
205
206 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
207 if (ret == -1) {
208 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
209 return ret;
210 }
211
212 fsx.fsx_projid = projectId;
213 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
214}
215
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100216int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
217 long projectId) {
218 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
219
220 if (ret != 0) {
221 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100222 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100223
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100224 if (!IsFilesystemSupported("sdcardfs")) {
225 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100226 }
227
228 return ret;
229}
230
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100231int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid) {
232 long projectId;
233 size_t pos;
234 int ret = 0;
235
236 // Make sure the Android/ directories exist and are setup correctly
237 ret = PrepareAndroidDirs(root);
238 if (ret != 0) {
239 LOG(ERROR) << "Failed to prepare Android/ directories.";
240 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100241 }
242
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100243 // Now create the application-specific subdir(s)
244 // path is something like /data/media/0/Android/data/com.foo/files
245 // First, chop off the volume root, eg /data/media/0
246 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100247
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100248 uid_t uid = appUid;
249 gid_t gid = AID_MEDIA_RW;
250 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100251
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100252 // Check that the next part matches one of the allowed Android/ dirs
253 if (StartsWith(pathFromRoot, kAppDataDir)) {
254 appDir = kAppDataDir;
255 if (!IsFilesystemSupported("sdcardfs")) {
256 gid = AID_EXT_DATA_RW;
257 }
258 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
259 appDir = kAppMediaDir;
260 if (!IsFilesystemSupported("sdcardfs")) {
261 gid = AID_MEDIA_RW;
262 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000263 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100264 appDir = kAppObbDir;
265 if (!IsFilesystemSupported("sdcardfs")) {
266 gid = AID_EXT_OBB_RW;
267 }
268 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100269 LOG(ERROR) << "Invalid application directory: " << path;
270 return -EINVAL;
271 }
272
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100273 // mode = 770, plus sticky bit on directory to inherit GID when apps
274 // create subdirs
275 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100276 // the project ID for application-specific directories is directly
277 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100278
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100279 // Chop off the generic application-specific part, eg /Android/data/
280 // this leaves us with something like com.foo/files/
281 std::string leftToCreate = pathFromRoot.substr(appDir.length());
282 if (!EndsWith(leftToCreate, "/")) {
283 leftToCreate += "/";
284 }
285 std::string pathToCreate = root + appDir;
286 int depth = 0;
287 bool withinCache = false;
288 while ((pos = leftToCreate.find('/')) != std::string::npos) {
289 std::string component = leftToCreate.substr(0, pos + 1);
290 leftToCreate = leftToCreate.erase(0, pos + 1);
291 pathToCreate = pathToCreate + component;
292
293 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
294 // All dirs use the "app" project ID, except for the cache dirs in
295 // Android/data, eg Android/data/com.foo/cache
296 // Note that this "sticks" - eg subdirs of this dir need the same
297 // project ID.
298 withinCache = true;
299 }
300 if (withinCache) {
301 projectId = uid - AID_APP_START + AID_CACHE_GID_START;
302 } else {
303 projectId = uid - AID_APP_START + AID_EXT_GID_START;
304 }
305 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
306 if (ret != 0) {
307 return ret;
308 }
309
310 if (depth == 0) {
311 // Set the default ACL on the top-level application-specific directories,
312 // to ensure that even if applications run with a umask of 0077,
313 // new directories within these directories will allow the GID
314 // specified here to write; this is necessary for apps like
315 // installers and MTP, that require access here.
316 //
317 // See man (5) acl for more details.
Martijn Coenen442bb832020-02-18 13:44:59 +0100318 ret = SetDefaultAcl(pathToCreate, mode, uid, gid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100319 if (ret != 0) {
320 return ret;
321 }
322 }
323
324 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100325 }
326
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100327 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100328}
329
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700330status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600331 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700332 const char* cpath = path.c_str();
333
334 char* secontext = nullptr;
335 if (sehandle) {
336 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
337 setfscreatecon(secontext);
338 }
339 }
340
341 int res = fs_prepare_dir(cpath, mode, uid, gid);
342
343 if (secontext) {
344 setfscreatecon(nullptr);
345 freecon(secontext);
346 }
347
348 if (res == 0) {
349 return OK;
350 } else {
351 return -errno;
352 }
353}
354
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800355status_t ForceUnmount(const std::string& path) {
356 const char* cpath = path.c_str();
357 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
358 return OK;
359 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700360 // Apps might still be handling eject request, so wait before
361 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700362 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700363
Jeff Sharkey3472e522017-10-06 18:02:53 -0600364 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700365 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700366 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
367 return OK;
368 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700369
Jeff Sharkey3472e522017-10-06 18:02:53 -0600370 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700371 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800372 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
373 return OK;
374 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700375
Jeff Sharkey3472e522017-10-06 18:02:53 -0600376 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700377 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700378 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
379 return OK;
380 }
Zim3623a212019-07-19 16:46:53 +0100381 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800382 return -errno;
383}
384
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700385status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600386 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700387 return OK;
388 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700389 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700390
Jeff Sharkey3472e522017-10-06 18:02:53 -0600391 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700392 return OK;
393 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700394 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700395
Jeff Sharkey3472e522017-10-06 18:02:53 -0600396 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700397 return OK;
398 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700399 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700400
401 // Send SIGKILL a second time to determine if we've
402 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600403 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700404 return OK;
405 }
406 PLOG(ERROR) << "Failed to kill processes using " << path;
407 return -EBUSY;
408}
409
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700410status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800411 if (UnmountTree(target) < 0) {
412 return -errno;
413 }
414 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700415 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
416 return -errno;
417 }
418 return OK;
419}
420
Sudheer Shanka023b5392019-02-06 12:39:19 -0800421status_t Symlink(const std::string& target, const std::string& linkpath) {
422 if (Unlink(linkpath) < 0) {
423 return -errno;
424 }
425 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
426 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
427 return -errno;
428 }
429 return OK;
430}
431
432status_t Unlink(const std::string& linkpath) {
433 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
434 PLOG(ERROR) << "Failed to unlink " << linkpath;
435 return -errno;
436 }
437 return OK;
438}
439
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000440status_t CreateDir(const std::string& dir, mode_t mode) {
441 struct stat sb;
442 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
443 if (S_ISDIR(sb.st_mode)) {
444 return OK;
445 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
446 PLOG(ERROR) << "Failed to unlink " << dir;
447 return -errno;
448 }
449 } else if (errno != ENOENT) {
450 PLOG(ERROR) << "Failed to stat " << dir;
451 return -errno;
452 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800453 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000454 PLOG(ERROR) << "Failed to mkdir " << dir;
455 return -errno;
456 }
457 return OK;
458}
459
Jeff Sharkey3472e522017-10-06 18:02:53 -0600460bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
461 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800462 size_t start = 0;
463 while (true) {
464 start = raw.find(qual, start);
465 if (start == std::string::npos) return false;
466 if (start == 0 || raw[start - 1] == ' ') {
467 break;
468 }
469 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600470 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600471 start += qual.length();
472
473 auto end = raw.find("\"", start);
474 if (end == std::string::npos) return false;
475
476 *value = raw.substr(start, end - start);
477 return true;
478}
479
Paul Crowley14c8c072018-09-18 13:30:21 -0700480static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
481 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600482 fsType->clear();
483 fsUuid->clear();
484 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700485
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700486 std::vector<std::string> cmd;
487 cmd.push_back(kBlkidPath);
488 cmd.push_back("-c");
489 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700490 cmd.push_back("-s");
491 cmd.push_back("TYPE");
492 cmd.push_back("-s");
493 cmd.push_back("UUID");
494 cmd.push_back("-s");
495 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700496 cmd.push_back(path);
497
498 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800499 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700500 if (res != OK) {
501 LOG(WARNING) << "blkid failed to identify " << path;
502 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700503 }
504
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700505 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700506 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600507 FindValue(line, "TYPE", fsType);
508 FindValue(line, "UUID", fsUuid);
509 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700510 }
511
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700512 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700513}
514
Paul Crowley14c8c072018-09-18 13:30:21 -0700515status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
516 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700517 return readMetadata(path, fsType, fsUuid, fsLabel, false);
518}
519
Paul Crowley14c8c072018-09-18 13:30:21 -0700520status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
521 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700522 return readMetadata(path, fsType, fsUuid, fsLabel, true);
523}
524
Paul Crowleyde2d6202018-11-30 11:43:47 -0800525static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
526 std::vector<const char*> argv;
527 argv.reserve(args.size() + 1);
528 for (const auto& arg : args) {
529 if (argv.empty()) {
530 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700531 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800532 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700533 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800534 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700535 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800536 argv.emplace_back(nullptr);
537 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700538}
539
Paul Crowleyde2d6202018-11-30 11:43:47 -0800540static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
541 android::base::unique_fd ufd) {
542 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700543 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800544 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700545 return -errno;
546 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800547 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700548 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800549 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700550 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800551 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700552 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800553 return OK;
554}
555
556status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
557 security_context_t context) {
558 auto argv = ConvertToArgv(args);
559
Paul Crowleye6d76632018-11-30 11:43:47 -0800560 android::base::unique_fd pipe_read, pipe_write;
561 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
562 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800563 return -errno;
564 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800565
566 pid_t pid = fork();
567 if (pid == 0) {
568 if (context) {
569 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800570 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800571 abort();
572 }
573 }
574 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800575 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
576 PLOG(ERROR) << "dup2 in ForkExecvp";
577 _exit(EXIT_FAILURE);
578 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800579 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800580 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800581 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800582 _exit(EXIT_FAILURE);
583 }
584 if (pid == -1) {
585 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700586 return -errno;
587 }
588
Paul Crowleyde2d6202018-11-30 11:43:47 -0800589 pipe_write.reset();
590 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
591 if (st != 0) return st;
592
593 int status;
594 if (waitpid(pid, &status, 0) == -1) {
595 PLOG(ERROR) << "waitpid in ForkExecvp";
596 return -errno;
597 }
598 if (!WIFEXITED(status)) {
599 LOG(ERROR) << "Process did not exit normally, status: " << status;
600 return -ECHILD;
601 }
602 if (WEXITSTATUS(status)) {
603 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
604 return WEXITSTATUS(status);
605 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700606 return OK;
607}
608
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700609pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800610 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700611
612 pid_t pid = fork();
613 if (pid == 0) {
614 close(STDIN_FILENO);
615 close(STDOUT_FILENO);
616 close(STDERR_FILENO);
617
Paul Crowleyde2d6202018-11-30 11:43:47 -0800618 execvp(argv[0], const_cast<char**>(argv.data()));
619 PLOG(ERROR) << "exec in ForkExecvpAsync";
620 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700621 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700622 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800623 PLOG(ERROR) << "fork in ForkExecvpAsync";
624 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700625 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700626 return pid;
627}
628
Jeff Sharkey9c484982015-03-31 10:35:33 -0700629status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100630 out.resize(bytes);
631 return ReadRandomBytes(bytes, &out[0]);
632}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700633
Pavel Grafove2e2d302017-08-01 17:15:53 +0100634status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700635 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
636 if (fd == -1) {
637 return -errno;
638 }
639
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800640 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100641 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700642 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100643 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700644 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700645 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700646
647 if (bytes == 0) {
648 return OK;
649 } else {
650 return -EIO;
651 }
652}
653
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600654status_t GenerateRandomUuid(std::string& out) {
655 status_t res = ReadRandomBytes(16, out);
656 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700657 out[6] &= 0x0f; /* clear version */
658 out[6] |= 0x40; /* set to version 4 */
659 out[8] &= 0x3f; /* clear variant */
660 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600661 }
662 return res;
663}
664
Jeff Sharkey9c484982015-03-31 10:35:33 -0700665status_t HexToStr(const std::string& hex, std::string& str) {
666 str.clear();
667 bool even = true;
668 char cur = 0;
669 for (size_t i = 0; i < hex.size(); i++) {
670 int val = 0;
671 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700672 // clang-format off
673 case ' ': case '-': case ':': continue;
674 case 'f': case 'F': val = 15; break;
675 case 'e': case 'E': val = 14; break;
676 case 'd': case 'D': val = 13; break;
677 case 'c': case 'C': val = 12; break;
678 case 'b': case 'B': val = 11; break;
679 case 'a': case 'A': val = 10; break;
680 case '9': val = 9; break;
681 case '8': val = 8; break;
682 case '7': val = 7; break;
683 case '6': val = 6; break;
684 case '5': val = 5; break;
685 case '4': val = 4; break;
686 case '3': val = 3; break;
687 case '2': val = 2; break;
688 case '1': val = 1; break;
689 case '0': val = 0; break;
690 default: return -EINVAL;
691 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700692 }
693
694 if (even) {
695 cur = val << 4;
696 } else {
697 cur += val;
698 str.push_back(cur);
699 cur = 0;
700 }
701 even = !even;
702 }
703 return even ? OK : -EINVAL;
704}
705
706static const char* kLookup = "0123456789abcdef";
707
708status_t StrToHex(const std::string& str, std::string& hex) {
709 hex.clear();
710 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700711 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700712 hex.push_back(kLookup[str[i] & 0x0F]);
713 }
714 return OK;
715}
716
Pavel Grafove2e2d302017-08-01 17:15:53 +0100717status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
718 hex.clear();
719 for (size_t i = 0; i < str.size(); i++) {
720 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
721 hex.push_back(kLookup[str.data()[i] & 0x0F]);
722 }
723 return OK;
724}
725
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700726status_t NormalizeHex(const std::string& in, std::string& out) {
727 std::string tmp;
728 if (HexToStr(in, tmp)) {
729 return -EINVAL;
730 }
731 return StrToHex(tmp, out);
732}
733
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200734status_t GetBlockDevSize(int fd, uint64_t* size) {
735 if (ioctl(fd, BLKGETSIZE64, size)) {
736 return -errno;
737 }
738
739 return OK;
740}
741
742status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
743 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
744 status_t res = OK;
745
746 if (fd < 0) {
747 return -errno;
748 }
749
750 res = GetBlockDevSize(fd, size);
751
752 close(fd);
753
754 return res;
755}
756
757status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
758 uint64_t size;
759 status_t res = GetBlockDevSize(path, &size);
760
761 if (res != OK) {
762 return res;
763 }
764
765 *nr_sec = size / 512;
766
767 return OK;
768}
769
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700770uint64_t GetFreeBytes(const std::string& path) {
771 struct statvfs sb;
772 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700773 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700774 } else {
775 return -1;
776 }
777}
778
779// TODO: borrowed from frameworks/native/libs/diskusage/ which should
780// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700781static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700782 int64_t blksize = s->st_blksize;
783 // count actual blocks used instead of nominal file size
784 int64_t size = s->st_blocks * 512;
785
786 if (blksize) {
787 /* round up to filesystem block size */
788 size = (size + blksize - 1) & (~(blksize - 1));
789 }
790
791 return size;
792}
793
794// TODO: borrowed from frameworks/native/libs/diskusage/ which should
795// eventually be migrated into system/
796int64_t calculate_dir_size(int dfd) {
797 int64_t size = 0;
798 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700799 DIR* d;
800 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700801
802 d = fdopendir(dfd);
803 if (d == NULL) {
804 close(dfd);
805 return 0;
806 }
807
808 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700809 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700810 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
811 size += stat_size(&s);
812 }
813 if (de->d_type == DT_DIR) {
814 int subfd;
815
816 /* always skip "." and ".." */
817 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700818 if (name[1] == 0) continue;
819 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700820 }
821
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600822 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700823 if (subfd >= 0) {
824 size += calculate_dir_size(subfd);
825 }
826 }
827 }
828 closedir(d);
829 return size;
830}
831
832uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600833 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700834 if (dirfd < 0) {
835 PLOG(WARNING) << "Failed to open " << path;
836 return -1;
837 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700838 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700839 }
840}
841
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700842bool IsFilesystemSupported(const std::string& fsType) {
843 std::string supported;
844 if (!ReadFileToString(kProcFilesystems, &supported)) {
845 PLOG(ERROR) << "Failed to read supported filesystems";
846 return false;
847 }
848 return supported.find(fsType + "\n") != std::string::npos;
849}
850
851status_t WipeBlockDevice(const std::string& path) {
852 status_t res = -1;
853 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200854 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700855
856 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
857 if (fd == -1) {
858 PLOG(ERROR) << "Failed to open " << path;
859 goto done;
860 }
861
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200862 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700863 PLOG(ERROR) << "Failed to determine size of " << path;
864 goto done;
865 }
866
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700867 LOG(INFO) << "About to discard " << range[1] << " on " << path;
868 if (ioctl(fd, BLKDISCARD, &range) == 0) {
869 LOG(INFO) << "Discard success on " << path;
870 res = 0;
871 } else {
872 PLOG(ERROR) << "Discard failure on " << path;
873 }
874
875done:
876 close(fd);
877 return res;
878}
879
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800880static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700881 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800882 return false;
883 } else {
884 return true;
885 }
886}
887
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700888std::string BuildKeyPath(const std::string& partGuid) {
889 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
890}
891
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600892std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700893 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600894}
895
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800896std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700897 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700898}
899
900std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700901 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700902}
903
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600904std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700905 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600906}
907
Jeff Sharkey47695b22016-02-01 17:02:29 -0700908std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700909 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700910}
911
912std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700913 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800914}
915
Calin Juravle79f55a42016-02-17 20:14:46 +0000916// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
917std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700918 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000919}
920
Andreas Huber71cd43f2018-01-22 11:25:29 -0800921std::string BuildDataVendorCePath(userid_t userId) {
922 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
923}
924
925std::string BuildDataVendorDePath(userid_t userId) {
926 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
927}
928
Paul Crowley3b71fc52017-10-09 10:55:21 -0700929std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800930 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700931 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800932 return "/data";
933 } else {
934 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700935 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800936 }
937}
938
Paul Crowley3b71fc52017-10-09 10:55:21 -0700939std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700940 // TODO: unify with installd path generation logic
941 std::string data(BuildDataPath(volumeUuid));
942 return StringPrintf("%s/media/%u", data.c_str(), userId);
943}
944
Paul Crowley3b71fc52017-10-09 10:55:21 -0700945std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800946 // TODO: unify with installd path generation logic
947 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700948 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800949 std::string legacy = StringPrintf("%s/data", data.c_str());
950 struct stat sb;
951 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
952 /* /data/data is dir, return /data/data for legacy system */
953 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800954 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800955 }
cjbaoeb501142017-04-12 00:09:00 +0800956 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800957}
958
Paul Crowley3b71fc52017-10-09 10:55:21 -0700959std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800960 // TODO: unify with installd path generation logic
961 std::string data(BuildDataPath(volumeUuid));
962 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
963}
964
Jeff Sharkey66270a22015-06-24 11:49:24 -0700965dev_t GetDevice(const std::string& path) {
966 struct stat sb;
967 if (stat(path.c_str(), &sb)) {
968 PLOG(WARNING) << "Failed to stat " << path;
969 return 0;
970 } else {
971 return sb.st_dev;
972 }
973}
974
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600975status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700976 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600977
Tom Cherryd6127ef2017-06-15 17:13:56 -0700978 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600979
Tom Cherryd6127ef2017-06-15 17:13:56 -0700980 android::base::SetProperty(kRestoreconString, "");
981 android::base::SetProperty(kRestoreconString, path);
982
983 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600984
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700985 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600986 return OK;
987}
988
Jeff Sharkey3472e522017-10-06 18:02:53 -0600989bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
990 // Shamelessly borrowed from android::base::Readlink()
991 result->clear();
992
993 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
994 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
995 // waste memory to just start there. We add 1 so that we can recognize
996 // whether it actually fit (rather than being truncated to 4095).
997 std::vector<char> buf(4095 + 1);
998 while (true) {
999 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1000 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001001 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001002 // It fit! (If size == buf.size(), it may have been truncated.)
1003 if (static_cast<size_t>(size) < buf.size()) {
1004 result->assign(&buf[0], size);
1005 return true;
1006 }
1007 // Double our buffer and try again.
1008 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001009 }
1010}
1011
Yu Ning942d4e82016-01-08 17:36:47 +08001012bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -07001013 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +08001014}
1015
Sudheer Shanka295fb242019-01-16 23:04:07 -08001016static status_t findMountPointsWithPrefix(const std::string& prefix,
1017 std::list<std::string>& mountPoints) {
1018 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1019 // when the prefix is /foo/bar
1020 std::string prefixWithSlash(prefix);
1021 if (prefix.back() != '/') {
1022 android::base::StringAppendF(&prefixWithSlash, "/");
1023 }
1024
1025 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1026 if (!mnts) {
1027 PLOG(ERROR) << "Unable to open /proc/mounts";
1028 return -errno;
1029 }
1030
1031 // Some volumes can be stacked on each other, so force unmount in
1032 // reverse order to give us the best chance of success.
1033 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1034 while ((mnt = getmntent(mnts.get())) != nullptr) {
1035 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1036 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1037 mountPoints.push_front(mountPoint);
1038 }
1039 }
1040 return OK;
1041}
1042
1043// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1044status_t UnmountTreeWithPrefix(const std::string& prefix) {
1045 std::list<std::string> toUnmount;
1046 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1047 if (result < 0) {
1048 return result;
1049 }
1050 for (const auto& path : toUnmount) {
1051 if (umount2(path.c_str(), MNT_DETACH)) {
1052 PLOG(ERROR) << "Failed to unmount " << path;
1053 result = -errno;
1054 }
1055 }
1056 return result;
1057}
1058
1059status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001060 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1061 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001062 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001063 return -errno;
1064 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001065 return OK;
1066}
1067
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001068static status_t delete_dir_contents(DIR* dir) {
1069 // Shamelessly borrowed from android::installd
1070 int dfd = dirfd(dir);
1071 if (dfd < 0) {
1072 return -errno;
1073 }
1074
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001075 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001076 struct dirent* de;
1077 while ((de = readdir(dir))) {
1078 const char* name = de->d_name;
1079 if (de->d_type == DT_DIR) {
1080 /* always skip "." and ".." */
1081 if (name[0] == '.') {
1082 if (name[1] == 0) continue;
1083 if ((name[1] == '.') && (name[2] == 0)) continue;
1084 }
1085
1086 android::base::unique_fd subfd(
1087 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1088 if (subfd.get() == -1) {
1089 PLOG(ERROR) << "Couldn't openat " << name;
1090 result = -errno;
1091 continue;
1092 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001093 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1094 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001095 if (!subdirp) {
1096 PLOG(ERROR) << "Couldn't fdopendir " << name;
1097 result = -errno;
1098 continue;
1099 }
1100 result = delete_dir_contents(subdirp.get());
1101 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1102 PLOG(ERROR) << "Couldn't unlinkat " << name;
1103 result = -errno;
1104 }
1105 } else {
1106 if (unlinkat(dfd, name, 0) < 0) {
1107 PLOG(ERROR) << "Couldn't unlinkat " << name;
1108 result = -errno;
1109 }
1110 }
1111 }
1112 return result;
1113}
1114
1115status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001116 status_t res = DeleteDirContents(pathname);
1117 if (res < 0) {
1118 return res;
1119 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001120 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001121 PLOG(ERROR) << "rmdir failed on " << pathname;
1122 return -errno;
1123 }
1124 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1125 return OK;
1126}
1127
1128status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001129 // Shamelessly borrowed from android::installd
1130 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1131 if (!dirp) {
1132 if (errno == ENOENT) {
1133 return OK;
1134 }
1135 PLOG(ERROR) << "Failed to opendir " << pathname;
1136 return -errno;
1137 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001138 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001139}
1140
Paul Crowley298fa322018-10-30 15:59:24 -07001141// TODO(118708649): fix duplication with init/util.h
1142status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1143 android::base::Timer t;
1144 while (t.duration() < timeout) {
1145 struct stat sb;
1146 if (stat(filename, &sb) != -1) {
1147 LOG(INFO) << "wait for '" << filename << "' took " << t;
1148 return 0;
1149 }
1150 std::this_thread::sleep_for(10ms);
1151 }
1152 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1153 return -1;
1154}
1155
Paul Crowley621d9b92018-12-07 15:36:09 -08001156bool FsyncDirectory(const std::string& dirname) {
1157 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1158 if (fd == -1) {
1159 PLOG(ERROR) << "Failed to open " << dirname;
1160 return false;
1161 }
1162 if (fsync(fd) == -1) {
1163 if (errno == EROFS || errno == EINVAL) {
1164 PLOG(WARNING) << "Skip fsync " << dirname
1165 << " on a file system does not support synchronization";
1166 } else {
1167 PLOG(ERROR) << "Failed to fsync " << dirname;
1168 return false;
1169 }
1170 }
1171 return true;
1172}
1173
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001174bool writeStringToFile(const std::string& payload, const std::string& filename) {
1175 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1176 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1177 if (fd == -1) {
1178 PLOG(ERROR) << "Failed to open " << filename;
1179 return false;
1180 }
1181 if (!android::base::WriteStringToFd(payload, fd)) {
1182 PLOG(ERROR) << "Failed to write to " << filename;
1183 unlink(filename.c_str());
1184 return false;
1185 }
1186 // fsync as close won't guarantee flush data
1187 // see close(2), fsync(2) and b/68901441
1188 if (fsync(fd) == -1) {
1189 if (errno == EROFS || errno == EINVAL) {
1190 PLOG(WARNING) << "Skip fsync " << filename
1191 << " on a file system does not support synchronization";
1192 } else {
1193 PLOG(ERROR) << "Failed to fsync " << filename;
1194 unlink(filename.c_str());
1195 return false;
1196 }
1197 }
1198 return true;
1199}
1200
Zima438b242019-09-25 14:37:38 +01001201status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1202 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1203 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1204 std::string fuse_path(
1205 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1206
1207 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1208 std::string pass_through_path(
1209 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001210
Zim1242be82020-01-22 18:22:29 +00001211 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1212 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001213 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001214 if (result != android::OK) {
1215 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1216 return -1;
1217 }
1218
Zim06b0caf2020-01-05 02:11:47 +00001219 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1220 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1221 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1222 // These bits should be consistent with what is set in zygote in
1223 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001224 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001225 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001226 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001227 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001228 return -1;
1229 }
1230
Zima438b242019-09-25 14:37:38 +01001231 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1232 if (result != android::OK) {
1233 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1234 return -1;
1235 }
1236
Zim26eec702020-01-31 16:00:58 +00001237 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001238 if (result != android::OK) {
1239 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1240 return -1;
1241 }
1242
Zim26eec702020-01-31 16:00:58 +00001243 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001244 if (result != android::OK) {
1245 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1246 return -1;
1247 }
1248
1249 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001250 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1251 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001252 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001253 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001254 return -1;
1255 }
Zime5393d42019-11-15 11:44:12 +00001256 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001257 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001258
1259 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001260 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001261 if (result != android::OK) {
1262 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1263 return -1;
1264 }
1265 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001266 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001267 }
1268
Nandana Dutta914cc72019-08-29 15:22:42 +01001269 // Open fuse fd.
1270 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1271 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001272 PLOG(ERROR) << "Failed to open /dev/fuse";
1273 return -1;
1274 }
1275
1276 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1277 // permission checks before routing to FUSE daemon.
1278 const auto opts = StringPrintf(
1279 "fd=%i,"
1280 "rootmode=40000,"
1281 "allow_other,"
1282 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001283 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001284
Zima438b242019-09-25 14:37:38 +01001285 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1286 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1287 opts.c_str()));
1288 if (result != 0) {
1289 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001290 return -errno;
1291 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001292
Martijn Coenen86f21a22020-01-06 09:48:14 +01001293 if (IsFilesystemSupported("sdcardfs")) {
1294 std::string sdcardfs_path(
1295 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1296
1297 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1298 return BindMount(sdcardfs_path, pass_through_path);
1299 } else {
1300 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1301 return BindMount(absolute_lower_path, pass_through_path);
1302 }
Zima438b242019-09-25 14:37:38 +01001303}
1304
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001305status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1306 const std::string& relative_upper_path) {
1307 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1308 std::string pass_through_path(
1309 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1310
Zima438b242019-09-25 14:37:38 +01001311 // Best effort unmount pass_through path
1312 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001313 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1314 auto status = ForceUnmount(pass_through_path);
1315 if (status != android::OK) {
1316 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1317 }
Martijn Coenen57002612019-11-28 11:56:13 +01001318 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001319
1320 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001321 android::status_t result = ForceUnmount(fuse_path);
1322 sSleepOnUnmount = true;
1323 if (result != android::OK) {
1324 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1325 // Figure out why we get EBUSY and remove this special casing if possible.
1326 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1327 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1328 errno != ENOENT) {
1329 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1330 return -errno;
1331 }
Martijn Coenen57002612019-11-28 11:56:13 +01001332 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001333 }
Martijn Coenen57002612019-11-28 11:56:13 +01001334 rmdir(fuse_path.c_str());
1335
Zima438b242019-09-25 14:37:38 +01001336 return result;
Zim3623a212019-07-19 16:46:53 +01001337}
1338
Martijn Coenen62a4b272020-01-31 15:23:09 +01001339status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1340 std::string androidDir = volumeRoot + kAndroidDir;
1341 std::string androidDataDir = volumeRoot + kAppDataDir;
1342 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001343 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001344
1345 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1346
Martijn Coenen10570c02020-02-18 10:41:37 +01001347 // mode 0771 + sticky bit for inheriting GIDs
1348 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1349 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001350 PLOG(ERROR) << "Failed to create " << androidDir;
1351 return -errno;
1352 }
1353
1354 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001355 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001356 PLOG(ERROR) << "Failed to create " << androidDataDir;
1357 return -errno;
1358 }
1359
1360 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001361 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001362 PLOG(ERROR) << "Failed to create " << androidObbDir;
1363 return -errno;
1364 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001365 // Some other apps, like installers, have write access to the OBB directory
1366 // to pre-download them. To make sure newly created folders in this directory
1367 // have the right permissions, set a default ACL.
1368 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid);
Martijn Coenen62a4b272020-01-31 15:23:09 +01001369
Martijn Coenen10570c02020-02-18 10:41:37 +01001370 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001371 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1372 return -errno;
1373 }
1374
Martijn Coenen62a4b272020-01-31 15:23:09 +01001375 return OK;
1376}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001377} // namespace vold
1378} // namespace android