blob: cc6cb78199bb62c9a2c59e3d54819f0a2de9d5a1 [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.
Martijn Coenen1129b812020-06-16 14:58:52 +0200134int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
135 std::vector<gid_t> additionalGids) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700136 if (IsSdcardfsUsed()) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100137 // sdcardfs magically takes care of this
138 return OK;
139 }
140
Martijn Coenen1129b812020-06-16 14:58:52 +0200141 size_t num_entries = 3 + (additionalGids.size() > 0 ? additionalGids.size() + 1 : 0);
142 size_t size = sizeof(posix_acl_xattr_header) + num_entries * sizeof(posix_acl_xattr_entry);
Martijn Coenen879fa802020-02-11 12:37:25 +0100143 auto buf = std::make_unique<uint8_t[]>(size);
144
145 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
146 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
147
148 posix_acl_xattr_entry* entry =
149 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
150
Martijn Coenen1129b812020-06-16 14:58:52 +0200151 int tag_index = 0;
152
153 entry[tag_index].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100154 // The existing mode_t mask has the ACL in the lower 9 bits:
155 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
156 // Use the mode_t masks to get these bits out, and shift them to get the
157 // correct value per entity.
158 //
159 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
Martijn Coenen1129b812020-06-16 14:58:52 +0200160 entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
161 entry[tag_index].e_id = uid;
162 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100163
Martijn Coenen1129b812020-06-16 14:58:52 +0200164 entry[tag_index].e_tag = ACL_GROUP_OBJ;
165 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
166 entry[tag_index].e_id = gid;
167 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100168
Martijn Coenen1129b812020-06-16 14:58:52 +0200169 if (additionalGids.size() > 0) {
170 for (gid_t additional_gid : additionalGids) {
171 entry[tag_index].e_tag = ACL_GROUP;
172 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
173 entry[tag_index].e_id = additional_gid;
174 tag_index++;
175 }
176
177 entry[tag_index].e_tag = ACL_MASK;
178 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
179 entry[tag_index].e_id = 0;
180 tag_index++;
181 }
182
183 entry[tag_index].e_tag = ACL_OTHER;
184 entry[tag_index].e_perm = mode & S_IRWXO;
185 entry[tag_index].e_id = 0;
Martijn Coenen879fa802020-02-11 12:37:25 +0100186
187 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
188
189 if (ret != 0) {
190 PLOG(ERROR) << "Failed to set default ACL on " << path;
191 }
192
193 return ret;
194}
195
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100196int SetQuotaInherit(const std::string& path) {
197 unsigned long flags;
198
199 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
200 if (fd == -1) {
201 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
202 return -1;
203 }
204
205 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
206 if (ret == -1) {
207 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
208 return ret;
209 }
210
211 flags |= FS_PROJINHERIT_FL;
212
213 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
214 if (ret == -1) {
215 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
216 return ret;
217 }
218
219 return 0;
220}
221
222int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100223 struct fsxattr fsx;
224
225 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
226 if (fd == -1) {
227 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
228 return -1;
229 }
230
231 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
232 if (ret == -1) {
233 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
234 return ret;
235 }
236
237 fsx.fsx_projid = projectId;
238 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
239}
240
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100241int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
242 long projectId) {
243 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
244
245 if (ret != 0) {
246 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100247 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100248
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700249 if (!IsSdcardfsUsed()) {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100250 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100251 }
252
253 return ret;
254}
255
Martijn Coenen816f4d92020-02-18 15:06:37 +0100256static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
257 namespace fs = std::filesystem;
258
259 // Setup the directory itself correctly
260 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
261 if (ret != OK) {
262 return ret;
263 }
264
265 // Fixup all of its file entries
266 for (const auto& itEntry : fs::directory_iterator(path)) {
267 ret = lchown(itEntry.path().c_str(), uid, gid);
268 if (ret != 0) {
269 return ret;
270 }
271
272 ret = chmod(itEntry.path().c_str(), mode);
273 if (ret != 0) {
274 return ret;
275 }
276
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700277 if (!IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +0100278 ret = SetQuotaProjectId(itEntry.path(), projectId);
279 if (ret != 0) {
280 return ret;
281 }
282 }
283 }
284
285 return OK;
286}
287
288int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
289 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100290 long projectId;
291 size_t pos;
292 int ret = 0;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700293 bool sdcardfsSupport = IsSdcardfsUsed();
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100294
295 // Make sure the Android/ directories exist and are setup correctly
296 ret = PrepareAndroidDirs(root);
297 if (ret != 0) {
298 LOG(ERROR) << "Failed to prepare Android/ directories.";
299 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100300 }
301
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100302 // Now create the application-specific subdir(s)
303 // path is something like /data/media/0/Android/data/com.foo/files
304 // First, chop off the volume root, eg /data/media/0
305 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100306
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100307 uid_t uid = appUid;
308 gid_t gid = AID_MEDIA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200309 std::vector<gid_t> additionalGids;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100310 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100311
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100312 // Check that the next part matches one of the allowed Android/ dirs
313 if (StartsWith(pathFromRoot, kAppDataDir)) {
314 appDir = kAppDataDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700315 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100316 gid = AID_EXT_DATA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200317 // Also add the app's own UID as a group; since apps belong to a group
318 // that matches their UID, this ensures that they will always have access to
319 // the files created in these dirs, even if they are created by other processes
320 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100321 }
322 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
323 appDir = kAppMediaDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700324 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100325 gid = AID_MEDIA_RW;
326 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000327 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100328 appDir = kAppObbDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700329 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100330 gid = AID_EXT_OBB_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200331 // See comments for kAppDataDir above
332 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100333 }
334 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100335 LOG(ERROR) << "Invalid application directory: " << path;
336 return -EINVAL;
337 }
338
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100339 // mode = 770, plus sticky bit on directory to inherit GID when apps
340 // create subdirs
341 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100342 // the project ID for application-specific directories is directly
343 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100344
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100345 // Chop off the generic application-specific part, eg /Android/data/
346 // this leaves us with something like com.foo/files/
347 std::string leftToCreate = pathFromRoot.substr(appDir.length());
348 if (!EndsWith(leftToCreate, "/")) {
349 leftToCreate += "/";
350 }
351 std::string pathToCreate = root + appDir;
352 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100353 // Derive initial project ID
354 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
355 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
356 } else if (appDir == kAppObbDir) {
357 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
358 }
359
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100360 while ((pos = leftToCreate.find('/')) != std::string::npos) {
361 std::string component = leftToCreate.substr(0, pos + 1);
362 leftToCreate = leftToCreate.erase(0, pos + 1);
363 pathToCreate = pathToCreate + component;
364
365 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
366 // All dirs use the "app" project ID, except for the cache dirs in
367 // Android/data, eg Android/data/com.foo/cache
368 // Note that this "sticks" - eg subdirs of this dir need the same
369 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100370 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100371 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100372
373 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
374 // Fixup all files in this existing directory with the correct UID/GID
375 // and project ID.
376 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
377 } else {
378 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
379 }
380
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100381 if (ret != 0) {
382 return ret;
383 }
384
385 if (depth == 0) {
386 // Set the default ACL on the top-level application-specific directories,
387 // to ensure that even if applications run with a umask of 0077,
388 // new directories within these directories will allow the GID
389 // specified here to write; this is necessary for apps like
390 // installers and MTP, that require access here.
391 //
392 // See man (5) acl for more details.
Martijn Coenen1129b812020-06-16 14:58:52 +0200393 ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100394 if (ret != 0) {
395 return ret;
396 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100397
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700398 if (!sdcardfsSupport) {
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100399 // Set project ID inheritance, so that future subdirectories inherit the
400 // same project ID
401 ret = SetQuotaInherit(pathToCreate);
402 if (ret != 0) {
403 return ret;
404 }
405 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100406 }
407
408 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100409 }
410
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100411 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100412}
413
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700414status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600415 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700416 const char* cpath = path.c_str();
417
418 char* secontext = nullptr;
419 if (sehandle) {
420 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
421 setfscreatecon(secontext);
422 }
423 }
424
425 int res = fs_prepare_dir(cpath, mode, uid, gid);
426
427 if (secontext) {
428 setfscreatecon(nullptr);
429 freecon(secontext);
430 }
431
432 if (res == 0) {
433 return OK;
434 } else {
435 return -errno;
436 }
437}
438
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800439status_t ForceUnmount(const std::string& path) {
440 const char* cpath = path.c_str();
441 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
442 return OK;
443 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700444 // Apps might still be handling eject request, so wait before
445 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700446 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700447
Jeff Sharkey3472e522017-10-06 18:02:53 -0600448 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700449 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700450 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
451 return OK;
452 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700453
Jeff Sharkey3472e522017-10-06 18:02:53 -0600454 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700455 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800456 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
457 return OK;
458 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700459
Jeff Sharkey3472e522017-10-06 18:02:53 -0600460 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700461 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700462 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
463 return OK;
464 }
Zim3623a212019-07-19 16:46:53 +0100465 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800466 return -errno;
467}
468
Ricky Wai07e64a42020-02-11 14:31:24 +0000469status_t KillProcessesWithMountPrefix(const std::string& path) {
470 if (KillProcessesWithMounts(path, SIGINT) == 0) {
471 return OK;
472 }
473 if (sSleepOnUnmount) sleep(5);
474
475 if (KillProcessesWithMounts(path, SIGTERM) == 0) {
476 return OK;
477 }
478 if (sSleepOnUnmount) sleep(5);
479
480 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
481 return OK;
482 }
483 if (sSleepOnUnmount) sleep(5);
484
485 // Send SIGKILL a second time to determine if we've
486 // actually killed everyone mount
487 if (KillProcessesWithMounts(path, SIGKILL) == 0) {
488 return OK;
489 }
490 PLOG(ERROR) << "Failed to kill processes using " << path;
491 return -EBUSY;
492}
493
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700494status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600495 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700496 return OK;
497 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700498 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700499
Jeff Sharkey3472e522017-10-06 18:02:53 -0600500 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700501 return OK;
502 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700503 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700504
Jeff Sharkey3472e522017-10-06 18:02:53 -0600505 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700506 return OK;
507 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700508 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700509
510 // Send SIGKILL a second time to determine if we've
511 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600512 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700513 return OK;
514 }
515 PLOG(ERROR) << "Failed to kill processes using " << path;
516 return -EBUSY;
517}
518
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700519status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800520 if (UnmountTree(target) < 0) {
521 return -errno;
522 }
523 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700524 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
525 return -errno;
526 }
527 return OK;
528}
529
Sudheer Shanka023b5392019-02-06 12:39:19 -0800530status_t Symlink(const std::string& target, const std::string& linkpath) {
531 if (Unlink(linkpath) < 0) {
532 return -errno;
533 }
534 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
535 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
536 return -errno;
537 }
538 return OK;
539}
540
541status_t Unlink(const std::string& linkpath) {
542 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
543 PLOG(ERROR) << "Failed to unlink " << linkpath;
544 return -errno;
545 }
546 return OK;
547}
548
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000549status_t CreateDir(const std::string& dir, mode_t mode) {
550 struct stat sb;
551 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
552 if (S_ISDIR(sb.st_mode)) {
553 return OK;
554 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
555 PLOG(ERROR) << "Failed to unlink " << dir;
556 return -errno;
557 }
558 } else if (errno != ENOENT) {
559 PLOG(ERROR) << "Failed to stat " << dir;
560 return -errno;
561 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800562 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000563 PLOG(ERROR) << "Failed to mkdir " << dir;
564 return -errno;
565 }
566 return OK;
567}
568
Jeff Sharkey3472e522017-10-06 18:02:53 -0600569bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
570 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800571 size_t start = 0;
572 while (true) {
573 start = raw.find(qual, start);
574 if (start == std::string::npos) return false;
575 if (start == 0 || raw[start - 1] == ' ') {
576 break;
577 }
578 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600579 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600580 start += qual.length();
581
582 auto end = raw.find("\"", start);
583 if (end == std::string::npos) return false;
584
585 *value = raw.substr(start, end - start);
586 return true;
587}
588
Paul Crowley14c8c072018-09-18 13:30:21 -0700589static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
590 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600591 fsType->clear();
592 fsUuid->clear();
593 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700594
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700595 std::vector<std::string> cmd;
596 cmd.push_back(kBlkidPath);
597 cmd.push_back("-c");
598 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700599 cmd.push_back("-s");
600 cmd.push_back("TYPE");
601 cmd.push_back("-s");
602 cmd.push_back("UUID");
603 cmd.push_back("-s");
604 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700605 cmd.push_back(path);
606
607 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800608 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700609 if (res != OK) {
610 LOG(WARNING) << "blkid failed to identify " << path;
611 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700612 }
613
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700614 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700615 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600616 FindValue(line, "TYPE", fsType);
617 FindValue(line, "UUID", fsUuid);
618 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700619 }
620
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700621 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700622}
623
Paul Crowley14c8c072018-09-18 13:30:21 -0700624status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
625 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700626 return readMetadata(path, fsType, fsUuid, fsLabel, false);
627}
628
Paul Crowley14c8c072018-09-18 13:30:21 -0700629status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
630 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700631 return readMetadata(path, fsType, fsUuid, fsLabel, true);
632}
633
Paul Crowleyde2d6202018-11-30 11:43:47 -0800634static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
635 std::vector<const char*> argv;
636 argv.reserve(args.size() + 1);
637 for (const auto& arg : args) {
638 if (argv.empty()) {
639 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700640 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800641 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700642 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800643 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700644 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800645 argv.emplace_back(nullptr);
646 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700647}
648
Paul Crowleyde2d6202018-11-30 11:43:47 -0800649static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
650 android::base::unique_fd ufd) {
651 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700652 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800653 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700654 return -errno;
655 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800656 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700657 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800658 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700659 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800660 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700661 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800662 return OK;
663}
664
665status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
666 security_context_t context) {
667 auto argv = ConvertToArgv(args);
668
Paul Crowleye6d76632018-11-30 11:43:47 -0800669 android::base::unique_fd pipe_read, pipe_write;
670 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
671 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800672 return -errno;
673 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800674
675 pid_t pid = fork();
676 if (pid == 0) {
677 if (context) {
678 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800679 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800680 abort();
681 }
682 }
683 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800684 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
685 PLOG(ERROR) << "dup2 in ForkExecvp";
686 _exit(EXIT_FAILURE);
687 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800688 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800689 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800690 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800691 _exit(EXIT_FAILURE);
692 }
693 if (pid == -1) {
694 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700695 return -errno;
696 }
697
Paul Crowleyde2d6202018-11-30 11:43:47 -0800698 pipe_write.reset();
699 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
700 if (st != 0) return st;
701
702 int status;
703 if (waitpid(pid, &status, 0) == -1) {
704 PLOG(ERROR) << "waitpid in ForkExecvp";
705 return -errno;
706 }
707 if (!WIFEXITED(status)) {
708 LOG(ERROR) << "Process did not exit normally, status: " << status;
709 return -ECHILD;
710 }
711 if (WEXITSTATUS(status)) {
712 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
713 return WEXITSTATUS(status);
714 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700715 return OK;
716}
717
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700718pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800719 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700720
721 pid_t pid = fork();
722 if (pid == 0) {
723 close(STDIN_FILENO);
724 close(STDOUT_FILENO);
725 close(STDERR_FILENO);
726
Paul Crowleyde2d6202018-11-30 11:43:47 -0800727 execvp(argv[0], const_cast<char**>(argv.data()));
728 PLOG(ERROR) << "exec in ForkExecvpAsync";
729 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700730 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700731 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800732 PLOG(ERROR) << "fork in ForkExecvpAsync";
733 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700734 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700735 return pid;
736}
737
Jeff Sharkey9c484982015-03-31 10:35:33 -0700738status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100739 out.resize(bytes);
740 return ReadRandomBytes(bytes, &out[0]);
741}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700742
Pavel Grafove2e2d302017-08-01 17:15:53 +0100743status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700744 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
745 if (fd == -1) {
746 return -errno;
747 }
748
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800749 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100750 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700751 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100752 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700753 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700754 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700755
756 if (bytes == 0) {
757 return OK;
758 } else {
759 return -EIO;
760 }
761}
762
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600763status_t GenerateRandomUuid(std::string& out) {
764 status_t res = ReadRandomBytes(16, out);
765 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700766 out[6] &= 0x0f; /* clear version */
767 out[6] |= 0x40; /* set to version 4 */
768 out[8] &= 0x3f; /* clear variant */
769 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600770 }
771 return res;
772}
773
Jeff Sharkey9c484982015-03-31 10:35:33 -0700774status_t HexToStr(const std::string& hex, std::string& str) {
775 str.clear();
776 bool even = true;
777 char cur = 0;
778 for (size_t i = 0; i < hex.size(); i++) {
779 int val = 0;
780 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700781 // clang-format off
782 case ' ': case '-': case ':': continue;
783 case 'f': case 'F': val = 15; break;
784 case 'e': case 'E': val = 14; break;
785 case 'd': case 'D': val = 13; break;
786 case 'c': case 'C': val = 12; break;
787 case 'b': case 'B': val = 11; break;
788 case 'a': case 'A': val = 10; break;
789 case '9': val = 9; break;
790 case '8': val = 8; break;
791 case '7': val = 7; break;
792 case '6': val = 6; break;
793 case '5': val = 5; break;
794 case '4': val = 4; break;
795 case '3': val = 3; break;
796 case '2': val = 2; break;
797 case '1': val = 1; break;
798 case '0': val = 0; break;
799 default: return -EINVAL;
800 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700801 }
802
803 if (even) {
804 cur = val << 4;
805 } else {
806 cur += val;
807 str.push_back(cur);
808 cur = 0;
809 }
810 even = !even;
811 }
812 return even ? OK : -EINVAL;
813}
814
815static const char* kLookup = "0123456789abcdef";
816
817status_t StrToHex(const std::string& str, std::string& hex) {
818 hex.clear();
819 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700820 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700821 hex.push_back(kLookup[str[i] & 0x0F]);
822 }
823 return OK;
824}
825
Pavel Grafove2e2d302017-08-01 17:15:53 +0100826status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
827 hex.clear();
828 for (size_t i = 0; i < str.size(); i++) {
829 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
830 hex.push_back(kLookup[str.data()[i] & 0x0F]);
831 }
832 return OK;
833}
834
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700835status_t NormalizeHex(const std::string& in, std::string& out) {
836 std::string tmp;
837 if (HexToStr(in, tmp)) {
838 return -EINVAL;
839 }
840 return StrToHex(tmp, out);
841}
842
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200843status_t GetBlockDevSize(int fd, uint64_t* size) {
844 if (ioctl(fd, BLKGETSIZE64, size)) {
845 return -errno;
846 }
847
848 return OK;
849}
850
851status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
852 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
853 status_t res = OK;
854
855 if (fd < 0) {
856 return -errno;
857 }
858
859 res = GetBlockDevSize(fd, size);
860
861 close(fd);
862
863 return res;
864}
865
866status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
867 uint64_t size;
868 status_t res = GetBlockDevSize(path, &size);
869
870 if (res != OK) {
871 return res;
872 }
873
874 *nr_sec = size / 512;
875
876 return OK;
877}
878
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700879uint64_t GetFreeBytes(const std::string& path) {
880 struct statvfs sb;
881 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700882 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700883 } else {
884 return -1;
885 }
886}
887
888// TODO: borrowed from frameworks/native/libs/diskusage/ which should
889// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700890static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700891 int64_t blksize = s->st_blksize;
892 // count actual blocks used instead of nominal file size
893 int64_t size = s->st_blocks * 512;
894
895 if (blksize) {
896 /* round up to filesystem block size */
897 size = (size + blksize - 1) & (~(blksize - 1));
898 }
899
900 return size;
901}
902
903// TODO: borrowed from frameworks/native/libs/diskusage/ which should
904// eventually be migrated into system/
905int64_t calculate_dir_size(int dfd) {
906 int64_t size = 0;
907 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700908 DIR* d;
909 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700910
911 d = fdopendir(dfd);
912 if (d == NULL) {
913 close(dfd);
914 return 0;
915 }
916
917 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700918 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700919 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
920 size += stat_size(&s);
921 }
922 if (de->d_type == DT_DIR) {
923 int subfd;
924
925 /* always skip "." and ".." */
926 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700927 if (name[1] == 0) continue;
928 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700929 }
930
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600931 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700932 if (subfd >= 0) {
933 size += calculate_dir_size(subfd);
934 }
935 }
936 }
937 closedir(d);
938 return size;
939}
940
941uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600942 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700943 if (dirfd < 0) {
944 PLOG(WARNING) << "Failed to open " << path;
945 return -1;
946 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700947 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700948 }
949}
950
Ricky Wai07e64a42020-02-11 14:31:24 +0000951// TODO: Use a better way to determine if it's media provider app.
952bool IsFuseDaemon(const pid_t pid) {
953 auto path = StringPrintf("/proc/%d/mounts", pid);
954 char* tmp;
955 if (lgetfilecon(path.c_str(), &tmp) < 0) {
956 return false;
957 }
958 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
959 || android::base::StartsWith(tmp, kMediaProviderCtx);
960 freecon(tmp);
961 return result;
962}
963
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700964bool IsFilesystemSupported(const std::string& fsType) {
965 std::string supported;
966 if (!ReadFileToString(kProcFilesystems, &supported)) {
967 PLOG(ERROR) << "Failed to read supported filesystems";
968 return false;
969 }
970 return supported.find(fsType + "\n") != std::string::npos;
971}
972
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700973bool IsSdcardfsUsed() {
974 return IsFilesystemSupported("sdcardfs") &&
975 base::GetBoolProperty(kExternalStorageSdcardfs, true);
976}
977
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700978status_t WipeBlockDevice(const std::string& path) {
979 status_t res = -1;
980 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200981 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700982
983 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
984 if (fd == -1) {
985 PLOG(ERROR) << "Failed to open " << path;
986 goto done;
987 }
988
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200989 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700990 PLOG(ERROR) << "Failed to determine size of " << path;
991 goto done;
992 }
993
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700994 LOG(INFO) << "About to discard " << range[1] << " on " << path;
995 if (ioctl(fd, BLKDISCARD, &range) == 0) {
996 LOG(INFO) << "Discard success on " << path;
997 res = 0;
998 } else {
999 PLOG(ERROR) << "Discard failure on " << path;
1000 }
1001
1002done:
1003 close(fd);
1004 return res;
1005}
1006
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001007static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001008 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001009 return false;
1010 } else {
1011 return true;
1012 }
1013}
1014
Jeff Sharkeybc40cc82015-06-18 14:25:08 -07001015std::string BuildKeyPath(const std::string& partGuid) {
1016 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1017}
1018
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001019std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001020 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001021}
1022
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001023std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001024 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001025}
1026
1027std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001028 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001029}
1030
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001031std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001032 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001033}
1034
Jeff Sharkey47695b22016-02-01 17:02:29 -07001035std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001036 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001037}
1038
1039std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001040 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001041}
1042
Calin Juravle79f55a42016-02-17 20:14:46 +00001043// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1044std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001045 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001046}
1047
Andreas Huber71cd43f2018-01-22 11:25:29 -08001048std::string BuildDataVendorCePath(userid_t userId) {
1049 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1050}
1051
1052std::string BuildDataVendorDePath(userid_t userId) {
1053 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1054}
1055
Paul Crowley3b71fc52017-10-09 10:55:21 -07001056std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001057 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001058 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001059 return "/data";
1060 } else {
1061 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001062 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001063 }
1064}
1065
Paul Crowley3b71fc52017-10-09 10:55:21 -07001066std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001067 // TODO: unify with installd path generation logic
1068 std::string data(BuildDataPath(volumeUuid));
1069 return StringPrintf("%s/media/%u", data.c_str(), userId);
1070}
1071
Paul Crowley3b71fc52017-10-09 10:55:21 -07001072std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001073 // TODO: unify with installd path generation logic
1074 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001075 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001076 std::string legacy = StringPrintf("%s/data", data.c_str());
1077 struct stat sb;
1078 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1079 /* /data/data is dir, return /data/data for legacy system */
1080 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001081 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001082 }
cjbaoeb501142017-04-12 00:09:00 +08001083 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001084}
1085
Paul Crowley3b71fc52017-10-09 10:55:21 -07001086std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001087 // TODO: unify with installd path generation logic
1088 std::string data(BuildDataPath(volumeUuid));
1089 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1090}
1091
Jeff Sharkey66270a22015-06-24 11:49:24 -07001092dev_t GetDevice(const std::string& path) {
1093 struct stat sb;
1094 if (stat(path.c_str(), &sb)) {
1095 PLOG(WARNING) << "Failed to stat " << path;
1096 return 0;
1097 } else {
1098 return sb.st_dev;
1099 }
1100}
1101
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001102status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001103 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001104
Tom Cherryd6127ef2017-06-15 17:13:56 -07001105 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001106
Tom Cherryd6127ef2017-06-15 17:13:56 -07001107 android::base::SetProperty(kRestoreconString, "");
1108 android::base::SetProperty(kRestoreconString, path);
1109
1110 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001111
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001112 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001113 return OK;
1114}
1115
Jeff Sharkey3472e522017-10-06 18:02:53 -06001116bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1117 // Shamelessly borrowed from android::base::Readlink()
1118 result->clear();
1119
1120 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1121 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1122 // waste memory to just start there. We add 1 so that we can recognize
1123 // whether it actually fit (rather than being truncated to 4095).
1124 std::vector<char> buf(4095 + 1);
1125 while (true) {
1126 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1127 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001128 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001129 // It fit! (If size == buf.size(), it may have been truncated.)
1130 if (static_cast<size_t>(size) < buf.size()) {
1131 result->assign(&buf[0], size);
1132 return true;
1133 }
1134 // Double our buffer and try again.
1135 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001136 }
1137}
1138
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001139static unsigned int GetMajorBlockVirtioBlk() {
1140 std::string devices;
1141 if (!ReadFileToString(kProcDevices, &devices)) {
1142 PLOG(ERROR) << "Unable to open /proc/devices";
1143 return 0;
1144 }
1145
1146 bool blockSection = false;
1147 for (auto line : android::base::Split(devices, "\n")) {
1148 if (line == "Block devices:") {
1149 blockSection = true;
1150 } else if (line == "Character devices:") {
1151 blockSection = false;
1152 } else if (blockSection) {
1153 auto tokens = android::base::Split(line, " ");
1154 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1155 return std::stoul(tokens[0]);
1156 }
1157 }
1158 }
1159
1160 return 0;
1161}
1162
1163bool IsVirtioBlkDevice(unsigned int major) {
1164 // Most virtualized platforms expose block devices with the virtio-blk
1165 // block device driver. Unfortunately, this driver does not use a fixed
1166 // major number, but relies on the kernel to assign one from a specific
1167 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1168 // per Documentation/devices.txt. This is true even for the latest Linux
1169 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1170 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1171 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001172}
1173
Sudheer Shanka295fb242019-01-16 23:04:07 -08001174static status_t findMountPointsWithPrefix(const std::string& prefix,
1175 std::list<std::string>& mountPoints) {
1176 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1177 // when the prefix is /foo/bar
1178 std::string prefixWithSlash(prefix);
1179 if (prefix.back() != '/') {
1180 android::base::StringAppendF(&prefixWithSlash, "/");
1181 }
1182
1183 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1184 if (!mnts) {
1185 PLOG(ERROR) << "Unable to open /proc/mounts";
1186 return -errno;
1187 }
1188
1189 // Some volumes can be stacked on each other, so force unmount in
1190 // reverse order to give us the best chance of success.
1191 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1192 while ((mnt = getmntent(mnts.get())) != nullptr) {
1193 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1194 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1195 mountPoints.push_front(mountPoint);
1196 }
1197 }
1198 return OK;
1199}
1200
1201// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1202status_t UnmountTreeWithPrefix(const std::string& prefix) {
1203 std::list<std::string> toUnmount;
1204 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1205 if (result < 0) {
1206 return result;
1207 }
1208 for (const auto& path : toUnmount) {
1209 if (umount2(path.c_str(), MNT_DETACH)) {
1210 PLOG(ERROR) << "Failed to unmount " << path;
1211 result = -errno;
1212 }
1213 }
1214 return result;
1215}
1216
1217status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001218 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1219 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001220 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001221 return -errno;
1222 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001223 return OK;
1224}
1225
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001226static status_t delete_dir_contents(DIR* dir) {
1227 // Shamelessly borrowed from android::installd
1228 int dfd = dirfd(dir);
1229 if (dfd < 0) {
1230 return -errno;
1231 }
1232
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001233 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001234 struct dirent* de;
1235 while ((de = readdir(dir))) {
1236 const char* name = de->d_name;
1237 if (de->d_type == DT_DIR) {
1238 /* always skip "." and ".." */
1239 if (name[0] == '.') {
1240 if (name[1] == 0) continue;
1241 if ((name[1] == '.') && (name[2] == 0)) continue;
1242 }
1243
1244 android::base::unique_fd subfd(
1245 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1246 if (subfd.get() == -1) {
1247 PLOG(ERROR) << "Couldn't openat " << name;
1248 result = -errno;
1249 continue;
1250 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001251 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1252 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001253 if (!subdirp) {
1254 PLOG(ERROR) << "Couldn't fdopendir " << name;
1255 result = -errno;
1256 continue;
1257 }
1258 result = delete_dir_contents(subdirp.get());
1259 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1260 PLOG(ERROR) << "Couldn't unlinkat " << name;
1261 result = -errno;
1262 }
1263 } else {
1264 if (unlinkat(dfd, name, 0) < 0) {
1265 PLOG(ERROR) << "Couldn't unlinkat " << name;
1266 result = -errno;
1267 }
1268 }
1269 }
1270 return result;
1271}
1272
1273status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001274 status_t res = DeleteDirContents(pathname);
1275 if (res < 0) {
1276 return res;
1277 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001278 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001279 PLOG(ERROR) << "rmdir failed on " << pathname;
1280 return -errno;
1281 }
1282 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1283 return OK;
1284}
1285
1286status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001287 // Shamelessly borrowed from android::installd
1288 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1289 if (!dirp) {
1290 if (errno == ENOENT) {
1291 return OK;
1292 }
1293 PLOG(ERROR) << "Failed to opendir " << pathname;
1294 return -errno;
1295 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001296 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001297}
1298
Paul Crowley298fa322018-10-30 15:59:24 -07001299// TODO(118708649): fix duplication with init/util.h
1300status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1301 android::base::Timer t;
1302 while (t.duration() < timeout) {
1303 struct stat sb;
1304 if (stat(filename, &sb) != -1) {
1305 LOG(INFO) << "wait for '" << filename << "' took " << t;
1306 return 0;
1307 }
1308 std::this_thread::sleep_for(10ms);
1309 }
1310 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1311 return -1;
1312}
1313
Paul Crowley621d9b92018-12-07 15:36:09 -08001314bool FsyncDirectory(const std::string& dirname) {
1315 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1316 if (fd == -1) {
1317 PLOG(ERROR) << "Failed to open " << dirname;
1318 return false;
1319 }
1320 if (fsync(fd) == -1) {
1321 if (errno == EROFS || errno == EINVAL) {
1322 PLOG(WARNING) << "Skip fsync " << dirname
1323 << " on a file system does not support synchronization";
1324 } else {
1325 PLOG(ERROR) << "Failed to fsync " << dirname;
1326 return false;
1327 }
1328 }
1329 return true;
1330}
1331
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001332bool writeStringToFile(const std::string& payload, const std::string& filename) {
1333 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1334 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1335 if (fd == -1) {
1336 PLOG(ERROR) << "Failed to open " << filename;
1337 return false;
1338 }
1339 if (!android::base::WriteStringToFd(payload, fd)) {
1340 PLOG(ERROR) << "Failed to write to " << filename;
1341 unlink(filename.c_str());
1342 return false;
1343 }
1344 // fsync as close won't guarantee flush data
1345 // see close(2), fsync(2) and b/68901441
1346 if (fsync(fd) == -1) {
1347 if (errno == EROFS || errno == EINVAL) {
1348 PLOG(WARNING) << "Skip fsync " << filename
1349 << " on a file system does not support synchronization";
1350 } else {
1351 PLOG(ERROR) << "Failed to fsync " << filename;
1352 unlink(filename.c_str());
1353 return false;
1354 }
1355 }
1356 return true;
1357}
1358
Martijn Coenen23c04452020-04-29 07:49:41 +02001359status_t AbortFuseConnections() {
1360 namespace fs = std::filesystem;
1361
1362 for (const auto& itEntry : fs::directory_iterator("/sys/fs/fuse/connections")) {
1363 std::string abortPath = itEntry.path().string() + "/abort";
1364 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1365 bool ret = writeStringToFile("1", abortPath);
1366 if (!ret) {
1367 LOG(WARNING) << "Failed to write to " << abortPath;
1368 }
1369 }
1370
1371 return OK;
1372}
1373
Ricky Wai07e64a42020-02-11 14:31:24 +00001374status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1375 if (access(path.c_str(), F_OK) != 0) {
1376 PLOG(WARNING) << "Dir does not exist: " << path;
1377 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1378 return -errno;
1379 }
1380 }
1381 return OK;
1382}
1383
Zima438b242019-09-25 14:37:38 +01001384status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1385 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1386 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1387 std::string fuse_path(
1388 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1389
1390 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1391 std::string pass_through_path(
1392 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001393
Zim1242be82020-01-22 18:22:29 +00001394 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1395 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001396 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001397 if (result != android::OK) {
1398 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1399 return -1;
1400 }
1401
Zim06b0caf2020-01-05 02:11:47 +00001402 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1403 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1404 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1405 // These bits should be consistent with what is set in zygote in
1406 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001407 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001408 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001409 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001410 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001411 return -1;
1412 }
1413
Zima438b242019-09-25 14:37:38 +01001414 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1415 if (result != android::OK) {
1416 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1417 return -1;
1418 }
1419
Zim26eec702020-01-31 16:00:58 +00001420 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001421 if (result != android::OK) {
1422 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1423 return -1;
1424 }
1425
Zim26eec702020-01-31 16:00:58 +00001426 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001427 if (result != android::OK) {
1428 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1429 return -1;
1430 }
1431
1432 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001433 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1434 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001435 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001436 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001437 return -1;
1438 }
Zime5393d42019-11-15 11:44:12 +00001439 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001440 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001441
1442 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001443 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001444 if (result != android::OK) {
1445 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1446 return -1;
1447 }
1448 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001449 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001450 }
1451
Nandana Dutta914cc72019-08-29 15:22:42 +01001452 // Open fuse fd.
1453 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1454 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001455 PLOG(ERROR) << "Failed to open /dev/fuse";
1456 return -1;
1457 }
1458
1459 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1460 // permission checks before routing to FUSE daemon.
1461 const auto opts = StringPrintf(
1462 "fd=%i,"
1463 "rootmode=40000,"
1464 "allow_other,"
1465 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001466 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001467
Zima438b242019-09-25 14:37:38 +01001468 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1469 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1470 opts.c_str()));
1471 if (result != 0) {
1472 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001473 return -errno;
1474 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001475
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001476 if (IsSdcardfsUsed()) {
Martijn Coenen86f21a22020-01-06 09:48:14 +01001477 std::string sdcardfs_path(
1478 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1479
1480 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1481 return BindMount(sdcardfs_path, pass_through_path);
1482 } else {
1483 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1484 return BindMount(absolute_lower_path, pass_through_path);
1485 }
Zima438b242019-09-25 14:37:38 +01001486}
1487
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001488status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1489 const std::string& relative_upper_path) {
1490 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1491 std::string pass_through_path(
1492 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1493
Zima438b242019-09-25 14:37:38 +01001494 // Best effort unmount pass_through path
1495 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001496 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1497 auto status = ForceUnmount(pass_through_path);
1498 if (status != android::OK) {
1499 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1500 }
Martijn Coenen57002612019-11-28 11:56:13 +01001501 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001502
1503 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001504 android::status_t result = ForceUnmount(fuse_path);
1505 sSleepOnUnmount = true;
1506 if (result != android::OK) {
1507 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1508 // Figure out why we get EBUSY and remove this special casing if possible.
1509 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1510 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1511 errno != ENOENT) {
1512 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1513 return -errno;
1514 }
Martijn Coenen57002612019-11-28 11:56:13 +01001515 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001516 }
Martijn Coenen57002612019-11-28 11:56:13 +01001517 rmdir(fuse_path.c_str());
1518
Zima438b242019-09-25 14:37:38 +01001519 return result;
Zim3623a212019-07-19 16:46:53 +01001520}
1521
Martijn Coenen62a4b272020-01-31 15:23:09 +01001522status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1523 std::string androidDir = volumeRoot + kAndroidDir;
1524 std::string androidDataDir = volumeRoot + kAppDataDir;
1525 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001526 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001527
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001528 bool useSdcardFs = IsSdcardfsUsed();
Martijn Coenen62a4b272020-01-31 15:23:09 +01001529
Martijn Coenen10570c02020-02-18 10:41:37 +01001530 // mode 0771 + sticky bit for inheriting GIDs
1531 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1532 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001533 PLOG(ERROR) << "Failed to create " << androidDir;
1534 return -errno;
1535 }
1536
1537 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001538 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001539 PLOG(ERROR) << "Failed to create " << androidDataDir;
1540 return -errno;
1541 }
1542
1543 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001544 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001545 PLOG(ERROR) << "Failed to create " << androidObbDir;
1546 return -errno;
1547 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001548 // Some other apps, like installers, have write access to the OBB directory
1549 // to pre-download them. To make sure newly created folders in this directory
1550 // have the right permissions, set a default ACL.
Martijn Coenen1129b812020-06-16 14:58:52 +02001551 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
Martijn Coenen62a4b272020-01-31 15:23:09 +01001552
Martijn Coenen10570c02020-02-18 10:41:37 +01001553 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001554 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1555 return -errno;
1556 }
1557
Martijn Coenen62a4b272020-01-31 15:23:09 +01001558 return OK;
1559}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001560} // namespace vold
1561} // namespace android