blob: 4635975a5c5fafe213b62851a684f20b5ef432bf [file] [log] [blame]
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkeydeb24052015-03-02 21:01:40 -080017#include "Utils.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070018
Jeff Sharkeydeb24052015-03-02 21:01:40 -080019#include "Process.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070020#include "sehandle.h"
Jeff Sharkeydeb24052015-03-02 21:01:40 -080021
Paul Crowley298fa322018-10-30 15:59:24 -070022#include <android-base/chrono_utils.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080023#include <android-base/file.h>
24#include <android-base/logging.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070025#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080026#include <android-base/stringprintf.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070027#include <android-base/strings.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070028#include <android-base/unique_fd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080029#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070030#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070031#include <private/android_filesystem_config.h>
Martijn Coenenaee40512020-02-18 16:29:25 +010032#include <private/android_projectid_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080033
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070034#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080035#include <fcntl.h>
36#include <linux/fs.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010037#include <linux/posix_acl.h>
38#include <linux/posix_acl_xattr.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070039#include <mntent.h>
40#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080041#include <stdlib.h>
42#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080043#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070044#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070045#include <sys/sysmacros.h>
46#include <sys/types.h>
47#include <sys/wait.h>
Martijn Coenen879fa802020-02-11 12:37:25 +010048#include <sys/xattr.h>
Paul Crowley747b4212019-04-05 04:09:57 -070049#include <unistd.h>
Paul Crowley298fa322018-10-30 15:59:24 -070050
Martijn Coenen816f4d92020-02-18 15:06:37 +010051#include <filesystem>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070052#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070053#include <mutex>
Martijn Coenen04bb17f2020-02-10 23:48:11 +010054#include <regex>
Paul Crowley298fa322018-10-30 15:59:24 -070055#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080056
57#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070058#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080059#endif
60
Paul Crowley298fa322018-10-30 15:59:24 -070061using namespace std::chrono_literals;
Martijn Coenenba9868b2020-01-31 15:49:24 +010062using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070063using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010064using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070065using android::base::StringPrintf;
Nikita Ioffedcee5c12020-06-12 12:59:45 +010066using android::base::unique_fd;
Jeff Sharkey9c484982015-03-31 10:35:33 -070067
Jeff Sharkeydeb24052015-03-02 21:01:40 -080068namespace android {
69namespace vold {
70
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070071security_context_t sBlkidContext = nullptr;
72security_context_t sBlkidUntrustedContext = nullptr;
73security_context_t sFsckContext = nullptr;
74security_context_t sFsckUntrustedContext = nullptr;
75
Paul Crowley56292ef2017-10-20 08:07:53 -070076bool sSleepOnUnmount = true;
77
Jeff Sharkey9c484982015-03-31 10:35:33 -070078static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070079static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070080
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070081static const char* kProcDevices = "/proc/devices";
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070082static const char* kProcFilesystems = "/proc/filesystems";
83
Martijn Coenen04bb17f2020-02-10 23:48:11 +010084static const char* kAndroidDir = "/Android/";
85static const char* kAppDataDir = "/Android/data/";
86static const char* kAppMediaDir = "/Android/media/";
87static const char* kAppObbDir = "/Android/obb/";
88
Ricky Wai07e64a42020-02-11 14:31:24 +000089static const char* kMediaProviderCtx = "u:r:mediaprovider:";
90static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
91
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060092// Lock used to protect process-level SELinux changes from racing with each
93// other between multiple threads.
94static std::mutex kSecurityLock;
95
Nikita Ioffedcee5c12020-06-12 12:59:45 +010096std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path) {
97 return StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str());
98}
99
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800100status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600101 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800102 const char* cpath = path.c_str();
103 status_t res = 0;
104
105 char* secontext = nullptr;
106 if (sehandle) {
107 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
108 setfscreatecon(secontext);
109 }
110 }
111
112 mode_t mode = 0660 | S_IFBLK;
113 if (mknod(cpath, mode, dev) < 0) {
114 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700115 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
116 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800117 res = -errno;
118 }
119 }
120
121 if (secontext) {
122 setfscreatecon(nullptr);
123 freecon(secontext);
124 }
125
126 return res;
127}
128
129status_t DestroyDeviceNode(const std::string& path) {
130 const char* cpath = path.c_str();
131 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
132 return -errno;
133 } else {
134 return OK;
135 }
136}
137
Martijn Coenen442bb832020-02-18 13:44:59 +0100138// Sets a default ACL on the directory.
Martijn Coenen5adf92a2021-02-01 07:57:02 +0000139status_t SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
140 std::vector<gid_t> additionalGids) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700141 if (IsSdcardfsUsed()) {
Martijn Coenen879fa802020-02-11 12:37:25 +0100142 // sdcardfs magically takes care of this
143 return OK;
144 }
145
Martijn Coenen1129b812020-06-16 14:58:52 +0200146 size_t num_entries = 3 + (additionalGids.size() > 0 ? additionalGids.size() + 1 : 0);
147 size_t size = sizeof(posix_acl_xattr_header) + num_entries * sizeof(posix_acl_xattr_entry);
Martijn Coenen879fa802020-02-11 12:37:25 +0100148 auto buf = std::make_unique<uint8_t[]>(size);
149
150 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
151 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
152
153 posix_acl_xattr_entry* entry =
154 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
155
Martijn Coenen1129b812020-06-16 14:58:52 +0200156 int tag_index = 0;
157
158 entry[tag_index].e_tag = ACL_USER_OBJ;
Martijn Coenen442bb832020-02-18 13:44:59 +0100159 // The existing mode_t mask has the ACL in the lower 9 bits:
160 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
161 // Use the mode_t masks to get these bits out, and shift them to get the
162 // correct value per entity.
163 //
164 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
Martijn Coenen1129b812020-06-16 14:58:52 +0200165 entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
166 entry[tag_index].e_id = uid;
167 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100168
Martijn Coenen1129b812020-06-16 14:58:52 +0200169 entry[tag_index].e_tag = ACL_GROUP_OBJ;
170 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
171 entry[tag_index].e_id = gid;
172 tag_index++;
Martijn Coenen879fa802020-02-11 12:37:25 +0100173
Martijn Coenen1129b812020-06-16 14:58:52 +0200174 if (additionalGids.size() > 0) {
175 for (gid_t additional_gid : additionalGids) {
176 entry[tag_index].e_tag = ACL_GROUP;
177 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
178 entry[tag_index].e_id = additional_gid;
179 tag_index++;
180 }
181
182 entry[tag_index].e_tag = ACL_MASK;
183 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
184 entry[tag_index].e_id = 0;
185 tag_index++;
186 }
187
188 entry[tag_index].e_tag = ACL_OTHER;
189 entry[tag_index].e_perm = mode & S_IRWXO;
190 entry[tag_index].e_id = 0;
Martijn Coenen879fa802020-02-11 12:37:25 +0100191
192 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
193
194 if (ret != 0) {
195 PLOG(ERROR) << "Failed to set default ACL on " << path;
196 }
197
198 return ret;
199}
200
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100201int SetQuotaInherit(const std::string& path) {
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700202 unsigned int flags;
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100203
204 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
205 if (fd == -1) {
206 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
207 return -1;
208 }
209
210 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
211 if (ret == -1) {
212 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
213 return ret;
214 }
215
216 flags |= FS_PROJINHERIT_FL;
217
218 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
219 if (ret == -1) {
220 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
221 return ret;
222 }
223
224 return 0;
225}
226
227int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100228 struct fsxattr fsx;
229
230 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
231 if (fd == -1) {
232 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
233 return -1;
234 }
235
236 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
237 if (ret == -1) {
238 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
239 return ret;
240 }
241
242 fsx.fsx_projid = projectId;
Eric Biggers39aa9582021-05-03 12:29:40 -0700243 ret = ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
244 if (ret == -1) {
245 PLOG(ERROR) << "Failed to set project id on " << path;
246 return ret;
247 }
248 return 0;
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100249}
250
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100251int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
252 long projectId) {
253 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
254
255 if (ret != 0) {
256 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100257 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100258
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700259 if (!IsSdcardfsUsed()) {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100260 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100261 }
262
263 return ret;
264}
265
Martijn Coenen816f4d92020-02-18 15:06:37 +0100266static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
267 namespace fs = std::filesystem;
268
269 // Setup the directory itself correctly
270 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
271 if (ret != OK) {
272 return ret;
273 }
274
275 // Fixup all of its file entries
276 for (const auto& itEntry : fs::directory_iterator(path)) {
277 ret = lchown(itEntry.path().c_str(), uid, gid);
278 if (ret != 0) {
279 return ret;
280 }
281
282 ret = chmod(itEntry.path().c_str(), mode);
283 if (ret != 0) {
284 return ret;
285 }
286
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700287 if (!IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +0100288 ret = SetQuotaProjectId(itEntry.path(), projectId);
289 if (ret != 0) {
290 return ret;
291 }
292 }
293 }
294
295 return OK;
296}
297
298int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
299 bool fixupExisting) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100300 long projectId;
301 size_t pos;
302 int ret = 0;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700303 bool sdcardfsSupport = IsSdcardfsUsed();
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100304
305 // Make sure the Android/ directories exist and are setup correctly
306 ret = PrepareAndroidDirs(root);
307 if (ret != 0) {
308 LOG(ERROR) << "Failed to prepare Android/ directories.";
309 return ret;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100310 }
311
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100312 // Now create the application-specific subdir(s)
313 // path is something like /data/media/0/Android/data/com.foo/files
314 // First, chop off the volume root, eg /data/media/0
315 std::string pathFromRoot = path.substr(root.length());
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100316
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100317 uid_t uid = appUid;
318 gid_t gid = AID_MEDIA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200319 std::vector<gid_t> additionalGids;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100320 std::string appDir;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100321
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100322 // Check that the next part matches one of the allowed Android/ dirs
323 if (StartsWith(pathFromRoot, kAppDataDir)) {
324 appDir = kAppDataDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700325 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100326 gid = AID_EXT_DATA_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200327 // Also add the app's own UID as a group; since apps belong to a group
328 // that matches their UID, this ensures that they will always have access to
329 // the files created in these dirs, even if they are created by other processes
330 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100331 }
332 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
333 appDir = kAppMediaDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700334 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100335 gid = AID_MEDIA_RW;
336 }
Ricky Waie50ddb72020-02-17 18:57:01 +0000337 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100338 appDir = kAppObbDir;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700339 if (!sdcardfsSupport) {
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100340 gid = AID_EXT_OBB_RW;
Martijn Coenen1129b812020-06-16 14:58:52 +0200341 // See comments for kAppDataDir above
342 additionalGids.push_back(uid);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100343 }
344 } else {
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100345 LOG(ERROR) << "Invalid application directory: " << path;
346 return -EINVAL;
347 }
348
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100349 // mode = 770, plus sticky bit on directory to inherit GID when apps
350 // create subdirs
351 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100352 // the project ID for application-specific directories is directly
353 // derived from their uid
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100354
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100355 // Chop off the generic application-specific part, eg /Android/data/
356 // this leaves us with something like com.foo/files/
357 std::string leftToCreate = pathFromRoot.substr(appDir.length());
358 if (!EndsWith(leftToCreate, "/")) {
359 leftToCreate += "/";
360 }
361 std::string pathToCreate = root + appDir;
362 int depth = 0;
Martijn Coenenaee40512020-02-18 16:29:25 +0100363 // Derive initial project ID
364 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
365 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
366 } else if (appDir == kAppObbDir) {
367 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
368 }
369
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100370 while ((pos = leftToCreate.find('/')) != std::string::npos) {
371 std::string component = leftToCreate.substr(0, pos + 1);
372 leftToCreate = leftToCreate.erase(0, pos + 1);
373 pathToCreate = pathToCreate + component;
374
375 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
376 // All dirs use the "app" project ID, except for the cache dirs in
377 // Android/data, eg Android/data/com.foo/cache
378 // Note that this "sticks" - eg subdirs of this dir need the same
379 // project ID.
Martijn Coenenaee40512020-02-18 16:29:25 +0100380 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100381 }
Martijn Coenen816f4d92020-02-18 15:06:37 +0100382
383 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
384 // Fixup all files in this existing directory with the correct UID/GID
385 // and project ID.
386 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
387 } else {
388 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
389 }
390
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100391 if (ret != 0) {
392 return ret;
393 }
394
395 if (depth == 0) {
396 // Set the default ACL on the top-level application-specific directories,
397 // to ensure that even if applications run with a umask of 0077,
398 // new directories within these directories will allow the GID
399 // specified here to write; this is necessary for apps like
400 // installers and MTP, that require access here.
401 //
402 // See man (5) acl for more details.
Martijn Coenen1129b812020-06-16 14:58:52 +0200403 ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100404 if (ret != 0) {
405 return ret;
406 }
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100407
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700408 if (!sdcardfsSupport) {
Martijn Coenen9171fcc2020-03-11 11:51:45 +0100409 // Set project ID inheritance, so that future subdirectories inherit the
410 // same project ID
411 ret = SetQuotaInherit(pathToCreate);
412 if (ret != 0) {
413 return ret;
414 }
415 }
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100416 }
417
418 depth++;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100419 }
420
Martijn Coenenb5a31c92020-02-13 23:30:38 +0100421 return OK;
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100422}
423
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700424int SetAttrs(const std::string& path, unsigned int attrs) {
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700425 unsigned int flags;
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700426 android::base::unique_fd fd(
427 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
428
429 if (fd == -1) {
430 PLOG(ERROR) << "Failed to open " << path;
431 return -1;
432 }
433
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700434 if (ioctl(fd, FS_IOC_GETFLAGS, &flags)) {
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700435 PLOG(ERROR) << "Failed to get flags for " << path;
436 return -1;
437 }
438
439 if ((flags & attrs) == attrs) return 0;
440 flags |= attrs;
Eric Biggersf9d9ac22020-10-23 16:32:58 -0700441 if (ioctl(fd, FS_IOC_SETFLAGS, &flags)) {
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700442 PLOG(ERROR) << "Failed to set flags for " << path << "(0x" << std::hex << attrs << ")";
443 return -1;
444 }
445 return 0;
446}
447
448status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
449 unsigned int attrs) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600450 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700451 const char* cpath = path.c_str();
452
453 char* secontext = nullptr;
454 if (sehandle) {
455 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
456 setfscreatecon(secontext);
457 }
458 }
459
460 int res = fs_prepare_dir(cpath, mode, uid, gid);
461
462 if (secontext) {
463 setfscreatecon(nullptr);
464 freecon(secontext);
465 }
466
Daniel Rosenbergcc874802020-08-12 18:31:43 -0700467 if (res) return -errno;
468 if (attrs) res = SetAttrs(path, attrs);
469
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700470 if (res == 0) {
471 return OK;
472 } else {
473 return -errno;
474 }
475}
476
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800477status_t ForceUnmount(const std::string& path) {
478 const char* cpath = path.c_str();
479 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
480 return OK;
481 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700482 // Apps might still be handling eject request, so wait before
483 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700484 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700485
Jeff Sharkey3472e522017-10-06 18:02:53 -0600486 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700487 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700488 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
489 return OK;
490 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700491
Jeff Sharkey3472e522017-10-06 18:02:53 -0600492 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700493 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800494 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
495 return OK;
496 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700497
Jeff Sharkey3472e522017-10-06 18:02:53 -0600498 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700499 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700500 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
501 return OK;
502 }
Zim3623a212019-07-19 16:46:53 +0100503 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800504 return -errno;
505}
506
Ricky Wai23356372021-04-30 09:53:07 +0100507status_t KillProcessesWithTmpfsMountPrefix(const std::string& path) {
508 if (KillProcessesWithTmpfsMounts(path, SIGINT) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000509 return OK;
510 }
511 if (sSleepOnUnmount) sleep(5);
512
Ricky Wai23356372021-04-30 09:53:07 +0100513 if (KillProcessesWithTmpfsMounts(path, SIGTERM) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000514 return OK;
515 }
516 if (sSleepOnUnmount) sleep(5);
517
Ricky Wai23356372021-04-30 09:53:07 +0100518 if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000519 return OK;
520 }
521 if (sSleepOnUnmount) sleep(5);
522
523 // Send SIGKILL a second time to determine if we've
524 // actually killed everyone mount
Ricky Wai23356372021-04-30 09:53:07 +0100525 if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000526 return OK;
527 }
528 PLOG(ERROR) << "Failed to kill processes using " << path;
529 return -EBUSY;
530}
531
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700532status_t KillProcessesUsingPath(const std::string& path) {
Zim75273002021-03-04 12:21:24 +0000533 if (KillProcessesWithOpenFiles(path, SIGINT, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700534 return OK;
535 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700536 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700537
Zim75273002021-03-04 12:21:24 +0000538 if (KillProcessesWithOpenFiles(path, SIGTERM, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700539 return OK;
540 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700541 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700542
Zim75273002021-03-04 12:21:24 +0000543 if (KillProcessesWithOpenFiles(path, SIGKILL, false /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700544 return OK;
545 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700546 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700547
548 // Send SIGKILL a second time to determine if we've
549 // actually killed everyone with open files
Zim75273002021-03-04 12:21:24 +0000550 // This time, we also kill the FUSE daemon if found
551 if (KillProcessesWithOpenFiles(path, SIGKILL, true /* killFuseDaemon */) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700552 return OK;
553 }
554 PLOG(ERROR) << "Failed to kill processes using " << path;
555 return -EBUSY;
556}
557
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700558status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800559 if (UnmountTree(target) < 0) {
560 return -errno;
561 }
562 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700563 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
564 return -errno;
565 }
566 return OK;
567}
568
Sudheer Shanka023b5392019-02-06 12:39:19 -0800569status_t Symlink(const std::string& target, const std::string& linkpath) {
570 if (Unlink(linkpath) < 0) {
571 return -errno;
572 }
573 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
574 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
575 return -errno;
576 }
577 return OK;
578}
579
580status_t Unlink(const std::string& linkpath) {
581 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
582 PLOG(ERROR) << "Failed to unlink " << linkpath;
583 return -errno;
584 }
585 return OK;
586}
587
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000588status_t CreateDir(const std::string& dir, mode_t mode) {
589 struct stat sb;
590 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
591 if (S_ISDIR(sb.st_mode)) {
592 return OK;
593 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
594 PLOG(ERROR) << "Failed to unlink " << dir;
595 return -errno;
596 }
597 } else if (errno != ENOENT) {
598 PLOG(ERROR) << "Failed to stat " << dir;
599 return -errno;
600 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800601 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000602 PLOG(ERROR) << "Failed to mkdir " << dir;
603 return -errno;
604 }
605 return OK;
606}
607
Jeff Sharkey3472e522017-10-06 18:02:53 -0600608bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
609 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800610 size_t start = 0;
611 while (true) {
612 start = raw.find(qual, start);
613 if (start == std::string::npos) return false;
614 if (start == 0 || raw[start - 1] == ' ') {
615 break;
616 }
617 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600618 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600619 start += qual.length();
620
621 auto end = raw.find("\"", start);
622 if (end == std::string::npos) return false;
623
624 *value = raw.substr(start, end - start);
625 return true;
626}
627
Paul Crowley14c8c072018-09-18 13:30:21 -0700628static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
629 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600630 fsType->clear();
631 fsUuid->clear();
632 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700633
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700634 std::vector<std::string> cmd;
635 cmd.push_back(kBlkidPath);
636 cmd.push_back("-c");
637 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700638 cmd.push_back("-s");
639 cmd.push_back("TYPE");
640 cmd.push_back("-s");
641 cmd.push_back("UUID");
642 cmd.push_back("-s");
643 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700644 cmd.push_back(path);
645
646 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800647 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700648 if (res != OK) {
649 LOG(WARNING) << "blkid failed to identify " << path;
650 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700651 }
652
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700653 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700654 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600655 FindValue(line, "TYPE", fsType);
656 FindValue(line, "UUID", fsUuid);
657 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700658 }
659
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700660 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700661}
662
Paul Crowley14c8c072018-09-18 13:30:21 -0700663status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
664 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700665 return readMetadata(path, fsType, fsUuid, fsLabel, false);
666}
667
Paul Crowley14c8c072018-09-18 13:30:21 -0700668status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
669 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700670 return readMetadata(path, fsType, fsUuid, fsLabel, true);
671}
672
Paul Crowleyde2d6202018-11-30 11:43:47 -0800673static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
674 std::vector<const char*> argv;
675 argv.reserve(args.size() + 1);
676 for (const auto& arg : args) {
677 if (argv.empty()) {
678 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700679 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800680 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700681 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800682 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700683 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800684 argv.emplace_back(nullptr);
685 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700686}
687
Paul Crowleyde2d6202018-11-30 11:43:47 -0800688static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
689 android::base::unique_fd ufd) {
690 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700691 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800692 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700693 return -errno;
694 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800695 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700696 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800697 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700698 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800699 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700700 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800701 return OK;
702}
703
704status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
705 security_context_t context) {
706 auto argv = ConvertToArgv(args);
707
Paul Crowleye6d76632018-11-30 11:43:47 -0800708 android::base::unique_fd pipe_read, pipe_write;
709 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
710 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800711 return -errno;
712 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800713
714 pid_t pid = fork();
715 if (pid == 0) {
716 if (context) {
717 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800718 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800719 abort();
720 }
721 }
722 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800723 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
724 PLOG(ERROR) << "dup2 in ForkExecvp";
725 _exit(EXIT_FAILURE);
726 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800727 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800728 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800729 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800730 _exit(EXIT_FAILURE);
731 }
732 if (pid == -1) {
733 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700734 return -errno;
735 }
736
Paul Crowleyde2d6202018-11-30 11:43:47 -0800737 pipe_write.reset();
738 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
739 if (st != 0) return st;
740
741 int status;
742 if (waitpid(pid, &status, 0) == -1) {
743 PLOG(ERROR) << "waitpid in ForkExecvp";
744 return -errno;
745 }
746 if (!WIFEXITED(status)) {
747 LOG(ERROR) << "Process did not exit normally, status: " << status;
748 return -ECHILD;
749 }
750 if (WEXITSTATUS(status)) {
751 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
752 return WEXITSTATUS(status);
753 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700754 return OK;
755}
756
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700757pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800758 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700759
760 pid_t pid = fork();
761 if (pid == 0) {
762 close(STDIN_FILENO);
763 close(STDOUT_FILENO);
764 close(STDERR_FILENO);
765
Paul Crowleyde2d6202018-11-30 11:43:47 -0800766 execvp(argv[0], const_cast<char**>(argv.data()));
767 PLOG(ERROR) << "exec in ForkExecvpAsync";
768 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700769 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700770 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800771 PLOG(ERROR) << "fork in ForkExecvpAsync";
772 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700773 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700774 return pid;
775}
776
Jeff Sharkey9c484982015-03-31 10:35:33 -0700777status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100778 out.resize(bytes);
779 return ReadRandomBytes(bytes, &out[0]);
780}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700781
Pavel Grafove2e2d302017-08-01 17:15:53 +0100782status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700783 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
784 if (fd == -1) {
785 return -errno;
786 }
787
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800788 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100789 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700790 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100791 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700792 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700793 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700794
795 if (bytes == 0) {
796 return OK;
797 } else {
798 return -EIO;
799 }
800}
801
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600802status_t GenerateRandomUuid(std::string& out) {
803 status_t res = ReadRandomBytes(16, out);
804 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700805 out[6] &= 0x0f; /* clear version */
806 out[6] |= 0x40; /* set to version 4 */
807 out[8] &= 0x3f; /* clear variant */
808 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600809 }
810 return res;
811}
812
Jeff Sharkey9c484982015-03-31 10:35:33 -0700813status_t HexToStr(const std::string& hex, std::string& str) {
814 str.clear();
815 bool even = true;
816 char cur = 0;
817 for (size_t i = 0; i < hex.size(); i++) {
818 int val = 0;
819 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700820 // clang-format off
821 case ' ': case '-': case ':': continue;
822 case 'f': case 'F': val = 15; break;
823 case 'e': case 'E': val = 14; break;
824 case 'd': case 'D': val = 13; break;
825 case 'c': case 'C': val = 12; break;
826 case 'b': case 'B': val = 11; break;
827 case 'a': case 'A': val = 10; break;
828 case '9': val = 9; break;
829 case '8': val = 8; break;
830 case '7': val = 7; break;
831 case '6': val = 6; break;
832 case '5': val = 5; break;
833 case '4': val = 4; break;
834 case '3': val = 3; break;
835 case '2': val = 2; break;
836 case '1': val = 1; break;
837 case '0': val = 0; break;
838 default: return -EINVAL;
839 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700840 }
841
842 if (even) {
843 cur = val << 4;
844 } else {
845 cur += val;
846 str.push_back(cur);
847 cur = 0;
848 }
849 even = !even;
850 }
851 return even ? OK : -EINVAL;
852}
853
854static const char* kLookup = "0123456789abcdef";
855
856status_t StrToHex(const std::string& str, std::string& hex) {
857 hex.clear();
858 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700859 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700860 hex.push_back(kLookup[str[i] & 0x0F]);
861 }
862 return OK;
863}
864
Pavel Grafove2e2d302017-08-01 17:15:53 +0100865status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
866 hex.clear();
867 for (size_t i = 0; i < str.size(); i++) {
868 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
869 hex.push_back(kLookup[str.data()[i] & 0x0F]);
870 }
871 return OK;
872}
873
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700874status_t NormalizeHex(const std::string& in, std::string& out) {
875 std::string tmp;
876 if (HexToStr(in, tmp)) {
877 return -EINVAL;
878 }
879 return StrToHex(tmp, out);
880}
881
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200882status_t GetBlockDevSize(int fd, uint64_t* size) {
883 if (ioctl(fd, BLKGETSIZE64, size)) {
884 return -errno;
885 }
886
887 return OK;
888}
889
890status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
891 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
892 status_t res = OK;
893
894 if (fd < 0) {
895 return -errno;
896 }
897
898 res = GetBlockDevSize(fd, size);
899
900 close(fd);
901
902 return res;
903}
904
905status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
906 uint64_t size;
907 status_t res = GetBlockDevSize(path, &size);
908
909 if (res != OK) {
910 return res;
911 }
912
913 *nr_sec = size / 512;
914
915 return OK;
916}
917
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700918uint64_t GetFreeBytes(const std::string& path) {
919 struct statvfs sb;
920 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700921 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700922 } else {
923 return -1;
924 }
925}
926
927// TODO: borrowed from frameworks/native/libs/diskusage/ which should
928// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700929static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700930 int64_t blksize = s->st_blksize;
931 // count actual blocks used instead of nominal file size
932 int64_t size = s->st_blocks * 512;
933
934 if (blksize) {
935 /* round up to filesystem block size */
936 size = (size + blksize - 1) & (~(blksize - 1));
937 }
938
939 return size;
940}
941
942// TODO: borrowed from frameworks/native/libs/diskusage/ which should
943// eventually be migrated into system/
944int64_t calculate_dir_size(int dfd) {
945 int64_t size = 0;
946 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700947 DIR* d;
948 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700949
950 d = fdopendir(dfd);
951 if (d == NULL) {
952 close(dfd);
953 return 0;
954 }
955
956 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700957 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700958 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
959 size += stat_size(&s);
960 }
961 if (de->d_type == DT_DIR) {
962 int subfd;
963
964 /* always skip "." and ".." */
Eric Biggers7bcf4272020-11-02 15:31:56 -0800965 if (IsDotOrDotDot(*de)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700966
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600967 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700968 if (subfd >= 0) {
969 size += calculate_dir_size(subfd);
970 }
971 }
972 }
973 closedir(d);
974 return size;
975}
976
977uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600978 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700979 if (dirfd < 0) {
980 PLOG(WARNING) << "Failed to open " << path;
981 return -1;
982 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700983 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700984 }
985}
986
Ricky Wai07e64a42020-02-11 14:31:24 +0000987// TODO: Use a better way to determine if it's media provider app.
988bool IsFuseDaemon(const pid_t pid) {
989 auto path = StringPrintf("/proc/%d/mounts", pid);
990 char* tmp;
991 if (lgetfilecon(path.c_str(), &tmp) < 0) {
992 return false;
993 }
994 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
995 || android::base::StartsWith(tmp, kMediaProviderCtx);
996 freecon(tmp);
997 return result;
998}
999
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001000bool IsFilesystemSupported(const std::string& fsType) {
1001 std::string supported;
1002 if (!ReadFileToString(kProcFilesystems, &supported)) {
1003 PLOG(ERROR) << "Failed to read supported filesystems";
1004 return false;
1005 }
1006 return supported.find(fsType + "\n") != std::string::npos;
1007}
1008
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001009bool IsSdcardfsUsed() {
1010 return IsFilesystemSupported("sdcardfs") &&
1011 base::GetBoolProperty(kExternalStorageSdcardfs, true);
1012}
1013
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001014status_t WipeBlockDevice(const std::string& path) {
1015 status_t res = -1;
1016 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001017 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001018
1019 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
1020 if (fd == -1) {
1021 PLOG(ERROR) << "Failed to open " << path;
1022 goto done;
1023 }
1024
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02001025 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001026 PLOG(ERROR) << "Failed to determine size of " << path;
1027 goto done;
1028 }
1029
Jeff Sharkeyd0640f62015-05-21 22:35:42 -07001030 LOG(INFO) << "About to discard " << range[1] << " on " << path;
1031 if (ioctl(fd, BLKDISCARD, &range) == 0) {
1032 LOG(INFO) << "Discard success on " << path;
1033 res = 0;
1034 } else {
1035 PLOG(ERROR) << "Discard failure on " << path;
1036 }
1037
1038done:
1039 close(fd);
1040 return res;
1041}
1042
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001043static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001044 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001045 return false;
1046 } else {
1047 return true;
1048 }
1049}
1050
Jeff Sharkeybc40cc82015-06-18 14:25:08 -07001051std::string BuildKeyPath(const std::string& partGuid) {
1052 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1053}
1054
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001055std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001056 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001057}
1058
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001059std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001060 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001061}
1062
1063std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001064 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001065}
1066
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001067std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001068 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -06001069}
1070
Jeff Sharkey47695b22016-02-01 17:02:29 -07001071std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001072 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -07001073}
1074
1075std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001076 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001077}
1078
Calin Juravle79f55a42016-02-17 20:14:46 +00001079// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1080std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -07001081 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +00001082}
1083
Andreas Huber71cd43f2018-01-22 11:25:29 -08001084std::string BuildDataVendorCePath(userid_t userId) {
1085 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1086}
1087
1088std::string BuildDataVendorDePath(userid_t userId) {
1089 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1090}
1091
Paul Crowley3b71fc52017-10-09 10:55:21 -07001092std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001093 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -07001094 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001095 return "/data";
1096 } else {
1097 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001098 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001099 }
1100}
1101
Paul Crowley3b71fc52017-10-09 10:55:21 -07001102std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -07001103 // TODO: unify with installd path generation logic
1104 std::string data(BuildDataPath(volumeUuid));
1105 return StringPrintf("%s/media/%u", data.c_str(), userId);
1106}
1107
Paul Crowley3b71fc52017-10-09 10:55:21 -07001108std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001109 // TODO: unify with installd path generation logic
1110 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -07001111 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +08001112 std::string legacy = StringPrintf("%s/data", data.c_str());
1113 struct stat sb;
1114 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1115 /* /data/data is dir, return /data/data for legacy system */
1116 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001117 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001118 }
cjbaoeb501142017-04-12 00:09:00 +08001119 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001120}
1121
Paul Crowley3b71fc52017-10-09 10:55:21 -07001122std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -08001123 // TODO: unify with installd path generation logic
1124 std::string data(BuildDataPath(volumeUuid));
1125 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1126}
1127
Jeff Sharkey66270a22015-06-24 11:49:24 -07001128dev_t GetDevice(const std::string& path) {
1129 struct stat sb;
1130 if (stat(path.c_str(), &sb)) {
1131 PLOG(WARNING) << "Failed to stat " << path;
1132 return 0;
1133 } else {
1134 return sb.st_dev;
1135 }
1136}
1137
Eric Biggersf74373b2020-11-05 19:58:26 -08001138// Returns true if |path1| names the same existing file or directory as |path2|.
1139bool IsSameFile(const std::string& path1, const std::string& path2) {
1140 struct stat stbuf1, stbuf2;
1141 if (stat(path1.c_str(), &stbuf1) != 0 || stat(path2.c_str(), &stbuf2) != 0) return false;
1142 return stbuf1.st_ino == stbuf2.st_ino && stbuf1.st_dev == stbuf2.st_dev;
1143}
1144
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001145status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001146 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001147
Tom Cherryd6127ef2017-06-15 17:13:56 -07001148 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001149
Tom Cherryd6127ef2017-06-15 17:13:56 -07001150 android::base::SetProperty(kRestoreconString, "");
1151 android::base::SetProperty(kRestoreconString, path);
1152
1153 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001154
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -07001155 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -06001156 return OK;
1157}
1158
Jeff Sharkey3472e522017-10-06 18:02:53 -06001159bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1160 // Shamelessly borrowed from android::base::Readlink()
1161 result->clear();
1162
1163 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1164 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1165 // waste memory to just start there. We add 1 so that we can recognize
1166 // whether it actually fit (rather than being truncated to 4095).
1167 std::vector<char> buf(4095 + 1);
1168 while (true) {
1169 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1170 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -07001171 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001172 // It fit! (If size == buf.size(), it may have been truncated.)
1173 if (static_cast<size_t>(size) < buf.size()) {
1174 result->assign(&buf[0], size);
1175 return true;
1176 }
1177 // Double our buffer and try again.
1178 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +09001179 }
1180}
1181
Alistair Delvaff1fc9b2020-05-14 16:35:03 -07001182static unsigned int GetMajorBlockVirtioBlk() {
1183 std::string devices;
1184 if (!ReadFileToString(kProcDevices, &devices)) {
1185 PLOG(ERROR) << "Unable to open /proc/devices";
1186 return 0;
1187 }
1188
1189 bool blockSection = false;
1190 for (auto line : android::base::Split(devices, "\n")) {
1191 if (line == "Block devices:") {
1192 blockSection = true;
1193 } else if (line == "Character devices:") {
1194 blockSection = false;
1195 } else if (blockSection) {
1196 auto tokens = android::base::Split(line, " ");
1197 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1198 return std::stoul(tokens[0]);
1199 }
1200 }
1201 }
1202
1203 return 0;
1204}
1205
1206bool IsVirtioBlkDevice(unsigned int major) {
1207 // Most virtualized platforms expose block devices with the virtio-blk
1208 // block device driver. Unfortunately, this driver does not use a fixed
1209 // major number, but relies on the kernel to assign one from a specific
1210 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1211 // per Documentation/devices.txt. This is true even for the latest Linux
1212 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1213 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1214 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
Yu Ning942d4e82016-01-08 17:36:47 +08001215}
1216
Sudheer Shanka295fb242019-01-16 23:04:07 -08001217static status_t findMountPointsWithPrefix(const std::string& prefix,
1218 std::list<std::string>& mountPoints) {
1219 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1220 // when the prefix is /foo/bar
1221 std::string prefixWithSlash(prefix);
1222 if (prefix.back() != '/') {
1223 android::base::StringAppendF(&prefixWithSlash, "/");
1224 }
1225
1226 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1227 if (!mnts) {
1228 PLOG(ERROR) << "Unable to open /proc/mounts";
1229 return -errno;
1230 }
1231
1232 // Some volumes can be stacked on each other, so force unmount in
1233 // reverse order to give us the best chance of success.
1234 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1235 while ((mnt = getmntent(mnts.get())) != nullptr) {
1236 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1237 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1238 mountPoints.push_front(mountPoint);
1239 }
1240 }
1241 return OK;
1242}
1243
1244// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1245status_t UnmountTreeWithPrefix(const std::string& prefix) {
1246 std::list<std::string> toUnmount;
1247 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1248 if (result < 0) {
1249 return result;
1250 }
1251 for (const auto& path : toUnmount) {
1252 if (umount2(path.c_str(), MNT_DETACH)) {
1253 PLOG(ERROR) << "Failed to unmount " << path;
1254 result = -errno;
1255 }
1256 }
1257 return result;
1258}
1259
1260status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -08001261 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1262 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -08001263 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001264 return -errno;
1265 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -07001266 return OK;
1267}
1268
Eric Biggers7bcf4272020-11-02 15:31:56 -08001269bool IsDotOrDotDot(const struct dirent& ent) {
1270 return strcmp(ent.d_name, ".") == 0 || strcmp(ent.d_name, "..") == 0;
1271}
1272
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001273static status_t delete_dir_contents(DIR* dir) {
1274 // Shamelessly borrowed from android::installd
1275 int dfd = dirfd(dir);
1276 if (dfd < 0) {
1277 return -errno;
1278 }
1279
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001280 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001281 struct dirent* de;
1282 while ((de = readdir(dir))) {
1283 const char* name = de->d_name;
1284 if (de->d_type == DT_DIR) {
1285 /* always skip "." and ".." */
Eric Biggers7bcf4272020-11-02 15:31:56 -08001286 if (IsDotOrDotDot(*de)) continue;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001287
1288 android::base::unique_fd subfd(
1289 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1290 if (subfd.get() == -1) {
1291 PLOG(ERROR) << "Couldn't openat " << name;
1292 result = -errno;
1293 continue;
1294 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001295 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1296 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001297 if (!subdirp) {
1298 PLOG(ERROR) << "Couldn't fdopendir " << name;
1299 result = -errno;
1300 continue;
1301 }
1302 result = delete_dir_contents(subdirp.get());
1303 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1304 PLOG(ERROR) << "Couldn't unlinkat " << name;
1305 result = -errno;
1306 }
1307 } else {
1308 if (unlinkat(dfd, name, 0) < 0) {
1309 PLOG(ERROR) << "Couldn't unlinkat " << name;
1310 result = -errno;
1311 }
1312 }
1313 }
1314 return result;
1315}
1316
1317status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001318 status_t res = DeleteDirContents(pathname);
1319 if (res < 0) {
1320 return res;
1321 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001322 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001323 PLOG(ERROR) << "rmdir failed on " << pathname;
1324 return -errno;
1325 }
1326 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1327 return OK;
1328}
1329
1330status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001331 // Shamelessly borrowed from android::installd
1332 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1333 if (!dirp) {
1334 if (errno == ENOENT) {
1335 return OK;
1336 }
1337 PLOG(ERROR) << "Failed to opendir " << pathname;
1338 return -errno;
1339 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001340 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001341}
1342
Paul Crowley298fa322018-10-30 15:59:24 -07001343// TODO(118708649): fix duplication with init/util.h
1344status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1345 android::base::Timer t;
1346 while (t.duration() < timeout) {
1347 struct stat sb;
1348 if (stat(filename, &sb) != -1) {
1349 LOG(INFO) << "wait for '" << filename << "' took " << t;
1350 return 0;
1351 }
1352 std::this_thread::sleep_for(10ms);
1353 }
1354 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1355 return -1;
1356}
1357
Eric Biggersbd138dd2021-02-16 15:59:17 -08001358bool pathExists(const std::string& path) {
1359 return access(path.c_str(), F_OK) == 0;
1360}
1361
Paul Crowley621d9b92018-12-07 15:36:09 -08001362bool FsyncDirectory(const std::string& dirname) {
1363 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1364 if (fd == -1) {
1365 PLOG(ERROR) << "Failed to open " << dirname;
1366 return false;
1367 }
1368 if (fsync(fd) == -1) {
1369 if (errno == EROFS || errno == EINVAL) {
1370 PLOG(WARNING) << "Skip fsync " << dirname
1371 << " on a file system does not support synchronization";
1372 } else {
1373 PLOG(ERROR) << "Failed to fsync " << dirname;
1374 return false;
1375 }
1376 }
1377 return true;
1378}
1379
Eric Biggers3345a2a2021-02-16 15:59:17 -08001380bool FsyncParentDirectory(const std::string& path) {
1381 return FsyncDirectory(android::base::Dirname(path));
1382}
1383
Eric Biggersfec0c0e2021-02-16 15:59:17 -08001384// Creates all parent directories of |path| that don't already exist. Assigns
1385// the specified |mode| to any new directories, and also fsync()s their parent
1386// directories so that the new directories get written to disk right away.
1387bool MkdirsSync(const std::string& path, mode_t mode) {
1388 if (path[0] != '/') {
1389 LOG(ERROR) << "MkdirsSync() needs an absolute path, but got " << path;
1390 return false;
1391 }
1392 std::vector<std::string> components = android::base::Split(android::base::Dirname(path), "/");
1393
1394 std::string current_dir = "/";
1395 for (const std::string& component : components) {
1396 if (component.empty()) continue;
1397
1398 std::string parent_dir = current_dir;
1399 if (current_dir != "/") current_dir += "/";
1400 current_dir += component;
1401
1402 if (!pathExists(current_dir)) {
1403 if (mkdir(current_dir.c_str(), mode) != 0) {
1404 PLOG(ERROR) << "Failed to create " << current_dir;
1405 return false;
1406 }
1407 if (!FsyncDirectory(parent_dir)) return false;
1408 LOG(DEBUG) << "Created directory " << current_dir;
1409 }
1410 }
1411 return true;
1412}
1413
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001414bool writeStringToFile(const std::string& payload, const std::string& filename) {
1415 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1416 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1417 if (fd == -1) {
1418 PLOG(ERROR) << "Failed to open " << filename;
1419 return false;
1420 }
1421 if (!android::base::WriteStringToFd(payload, fd)) {
1422 PLOG(ERROR) << "Failed to write to " << filename;
1423 unlink(filename.c_str());
1424 return false;
1425 }
1426 // fsync as close won't guarantee flush data
1427 // see close(2), fsync(2) and b/68901441
1428 if (fsync(fd) == -1) {
1429 if (errno == EROFS || errno == EINVAL) {
1430 PLOG(WARNING) << "Skip fsync " << filename
1431 << " on a file system does not support synchronization";
1432 } else {
1433 PLOG(ERROR) << "Failed to fsync " << filename;
1434 unlink(filename.c_str());
1435 return false;
1436 }
1437 }
1438 return true;
1439}
1440
Martijn Coenen23c04452020-04-29 07:49:41 +02001441status_t AbortFuseConnections() {
1442 namespace fs = std::filesystem;
1443
1444 for (const auto& itEntry : fs::directory_iterator("/sys/fs/fuse/connections")) {
1445 std::string abortPath = itEntry.path().string() + "/abort";
1446 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1447 bool ret = writeStringToFile("1", abortPath);
1448 if (!ret) {
1449 LOG(WARNING) << "Failed to write to " << abortPath;
1450 }
1451 }
1452
1453 return OK;
1454}
1455
Ricky Wai07e64a42020-02-11 14:31:24 +00001456status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1457 if (access(path.c_str(), F_OK) != 0) {
1458 PLOG(WARNING) << "Dir does not exist: " << path;
1459 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1460 return -errno;
1461 }
1462 }
1463 return OK;
1464}
1465
Martijn Coenena4850062020-06-29 11:53:34 +02001466// Gets the sysfs path for parameters of the backing device info (bdi)
1467static std::string getBdiPathForMount(const std::string& mount) {
1468 // First figure out MAJOR:MINOR of mount. Simplest way is to stat the path.
1469 struct stat info;
1470 if (stat(mount.c_str(), &info) != 0) {
1471 PLOG(ERROR) << "Failed to stat " << mount;
1472 return "";
1473 }
1474 unsigned int maj = major(info.st_dev);
1475 unsigned int min = minor(info.st_dev);
1476
1477 return StringPrintf("/sys/class/bdi/%u:%u", maj, min);
1478}
1479
1480// Configures max_ratio for the FUSE filesystem.
1481void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio) {
1482 LOG(INFO) << "Configuring max_ratio of " << fuse_mount << " fuse filesystem to " << max_ratio;
1483 if (max_ratio > 100) {
1484 LOG(ERROR) << "Invalid max_ratio: " << max_ratio;
1485 return;
1486 }
1487 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1488 if (fuseBdiPath == "") {
1489 return;
1490 }
1491 std::string max_ratio_file = StringPrintf("%s/max_ratio", fuseBdiPath.c_str());
1492 unique_fd fd(TEMP_FAILURE_RETRY(open(max_ratio_file.c_str(), O_WRONLY | O_CLOEXEC)));
1493 if (fd.get() == -1) {
1494 PLOG(ERROR) << "Failed to open " << max_ratio_file;
1495 return;
1496 }
1497 LOG(INFO) << "Writing " << max_ratio << " to " << max_ratio_file;
1498 if (!WriteStringToFd(std::to_string(max_ratio), fd)) {
1499 PLOG(ERROR) << "Failed to write to " << max_ratio_file;
1500 }
1501}
1502
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001503// Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1504// writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
1505void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1506 LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1507 << read_ahead_kb << "kb";
Martijn Coenena4850062020-06-29 11:53:34 +02001508 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1509 if (fuseBdiPath == "") {
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001510 return;
1511 }
Martijn Coenena4850062020-06-29 11:53:34 +02001512 // We found the bdi path for our filesystem, time to configure read ahead!
1513 std::string read_ahead_file = StringPrintf("%s/read_ahead_kb", fuseBdiPath.c_str());
Nikita Ioffedcee5c12020-06-12 12:59:45 +01001514 unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1515 if (fd.get() == -1) {
1516 PLOG(ERROR) << "Failed to open " << read_ahead_file;
1517 return;
1518 }
1519 LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1520 if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1521 PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1522 }
1523}
1524
Zima438b242019-09-25 14:37:38 +01001525status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1526 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1527 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1528 std::string fuse_path(
1529 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1530
1531 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1532 std::string pass_through_path(
1533 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001534
Zim1242be82020-01-22 18:22:29 +00001535 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1536 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001537 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001538 if (result != android::OK) {
1539 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1540 return -1;
1541 }
1542
Zim06b0caf2020-01-05 02:11:47 +00001543 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1544 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1545 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1546 // These bits should be consistent with what is set in zygote in
1547 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001548 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001549 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001550 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001551 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001552 return -1;
1553 }
1554
Zima438b242019-09-25 14:37:38 +01001555 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1556 if (result != android::OK) {
1557 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1558 return -1;
1559 }
1560
Zim26eec702020-01-31 16:00:58 +00001561 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001562 if (result != android::OK) {
1563 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1564 return -1;
1565 }
1566
Zim26eec702020-01-31 16:00:58 +00001567 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001568 if (result != android::OK) {
1569 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1570 return -1;
1571 }
1572
1573 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001574 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1575 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001576 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001577 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001578 return -1;
1579 }
Zime5393d42019-11-15 11:44:12 +00001580 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001581 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001582
1583 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001584 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001585 if (result != android::OK) {
1586 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1587 return -1;
1588 }
1589 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001590 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001591 }
1592
Nandana Dutta914cc72019-08-29 15:22:42 +01001593 // Open fuse fd.
1594 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1595 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001596 PLOG(ERROR) << "Failed to open /dev/fuse";
1597 return -1;
1598 }
1599
1600 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1601 // permission checks before routing to FUSE daemon.
1602 const auto opts = StringPrintf(
1603 "fd=%i,"
1604 "rootmode=40000,"
1605 "allow_other,"
1606 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001607 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001608
Zima438b242019-09-25 14:37:38 +01001609 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1610 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1611 opts.c_str()));
1612 if (result != 0) {
1613 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001614 return -errno;
1615 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001616
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001617 if (IsSdcardfsUsed()) {
Martijn Coenen86f21a22020-01-06 09:48:14 +01001618 std::string sdcardfs_path(
1619 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1620
1621 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1622 return BindMount(sdcardfs_path, pass_through_path);
1623 } else {
1624 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1625 return BindMount(absolute_lower_path, pass_through_path);
1626 }
Zima438b242019-09-25 14:37:38 +01001627}
1628
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001629status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1630 const std::string& relative_upper_path) {
1631 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1632 std::string pass_through_path(
1633 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1634
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001635 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001636 android::status_t result = ForceUnmount(fuse_path);
Zima438b242019-09-25 14:37:38 +01001637 if (result != android::OK) {
1638 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1639 // Figure out why we get EBUSY and remove this special casing if possible.
1640 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1641 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1642 errno != ENOENT) {
1643 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1644 return -errno;
1645 }
Martijn Coenen57002612019-11-28 11:56:13 +01001646 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001647 }
Martijn Coenen57002612019-11-28 11:56:13 +01001648 rmdir(fuse_path.c_str());
1649
Martijn Coenen64b3bba2020-11-05 10:34:28 +01001650 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1651 auto status = ForceUnmount(pass_through_path);
1652 if (status != android::OK) {
1653 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1654 }
1655 rmdir(pass_through_path.c_str());
1656
Zima438b242019-09-25 14:37:38 +01001657 return result;
Zim3623a212019-07-19 16:46:53 +01001658}
1659
Martijn Coenen62a4b272020-01-31 15:23:09 +01001660status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1661 std::string androidDir = volumeRoot + kAndroidDir;
1662 std::string androidDataDir = volumeRoot + kAppDataDir;
1663 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001664 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001665
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001666 bool useSdcardFs = IsSdcardfsUsed();
Martijn Coenen62a4b272020-01-31 15:23:09 +01001667
Martijn Coenen10570c02020-02-18 10:41:37 +01001668 // mode 0771 + sticky bit for inheriting GIDs
1669 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1670 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001671 PLOG(ERROR) << "Failed to create " << androidDir;
1672 return -errno;
1673 }
1674
1675 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001676 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001677 PLOG(ERROR) << "Failed to create " << androidDataDir;
1678 return -errno;
1679 }
1680
1681 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
Martijn Coenen10570c02020-02-18 10:41:37 +01001682 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +01001683 PLOG(ERROR) << "Failed to create " << androidObbDir;
1684 return -errno;
1685 }
Martijn Coenen442bb832020-02-18 13:44:59 +01001686 // Some other apps, like installers, have write access to the OBB directory
1687 // to pre-download them. To make sure newly created folders in this directory
1688 // have the right permissions, set a default ACL.
Martijn Coenen1129b812020-06-16 14:58:52 +02001689 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
Martijn Coenen62a4b272020-01-31 15:23:09 +01001690
Martijn Coenen10570c02020-02-18 10:41:37 +01001691 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
Zima13d81b2020-02-07 16:39:31 +00001692 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1693 return -errno;
1694 }
1695
Martijn Coenen62a4b272020-01-31 15:23:09 +01001696 return OK;
1697}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001698} // namespace vold
1699} // namespace android