blob: 3b0eda06fb6c3a1ec464371d7225f1a1e67ddc8f [file] [log] [blame]
bigbiff7ba75002020-04-11 20:47:09 -04001/*
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
17#include "Utils.h"
18
19#include "Process.h"
20#include "sehandle.h"
21
22#include <android-base/chrono_utils.h>
23#include <android-base/file.h>
24#include <android-base/logging.h>
25#include <android-base/properties.h>
26#include <android-base/stringprintf.h>
27#include <android-base/strings.h>
28#include <android-base/unique_fd.h>
29#include <cutils/fs.h>
30#include <logwrap/logwrap.h>
31#include <private/android_filesystem_config.h>
bigbiffa957f072021-03-07 18:20:29 -050032#include <private/android_projectid_config.h>
bigbiff7ba75002020-04-11 20:47:09 -040033
34#include <dirent.h>
35#include <fcntl.h>
36#include <linux/fs.h>
bigbiffa957f072021-03-07 18:20:29 -050037#include <linux/posix_acl.h>
38#include <linux/posix_acl_xattr.h>
bigbiff7ba75002020-04-11 20:47:09 -040039#include <mntent.h>
40#include <stdio.h>
41#include <stdlib.h>
bigbiff7ba75002020-04-11 20:47:09 -040042#include <sys/mount.h>
43#include <sys/stat.h>
44#include <sys/statvfs.h>
45#include <sys/sysmacros.h>
46#include <sys/types.h>
47#include <sys/wait.h>
bigbiffa957f072021-03-07 18:20:29 -050048#include <sys/xattr.h>
49#include <unistd.h>
bigbiff7ba75002020-04-11 20:47:09 -040050
bigbiffa957f072021-03-07 18:20:29 -050051#include <filesystem>
bigbiff7ba75002020-04-11 20:47:09 -040052#include <list>
53#include <mutex>
bigbiffa957f072021-03-07 18:20:29 -050054#include <regex>
bigbiff7ba75002020-04-11 20:47:09 -040055#include <thread>
56
57#ifndef UMOUNT_NOFOLLOW
58#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
59#endif
60
61using namespace std::chrono_literals;
bigbiffa957f072021-03-07 18:20:29 -050062using android::base::EndsWith;
bigbiff7ba75002020-04-11 20:47:09 -040063using android::base::ReadFileToString;
bigbiffa957f072021-03-07 18:20:29 -050064using android::base::StartsWith;
bigbiff7ba75002020-04-11 20:47:09 -040065using android::base::StringPrintf;
bigbiffa957f072021-03-07 18:20:29 -050066using android::base::unique_fd;
bigbiff7ba75002020-04-11 20:47:09 -040067
bigbiffa957f072021-03-07 18:20:29 -050068struct selabel_handle* sehandle;
bigbiff7ba75002020-04-11 20:47:09 -040069
70security_context_t sBlkidContext = nullptr;
71security_context_t sBlkidUntrustedContext = nullptr;
72security_context_t sFsckContext = nullptr;
73security_context_t sFsckUntrustedContext = nullptr;
bigbiff7ba75002020-04-11 20:47:09 -040074
75bool sSleepOnUnmount = true;
76
77static const char* kBlkidPath = "/system/bin/blkid";
78static const char* kKeyPath = "/data/misc/vold";
79
bigbiffa957f072021-03-07 18:20:29 -050080static const char* kProcDevices = "/proc/devices";
bigbiff7ba75002020-04-11 20:47:09 -040081static const char* kProcFilesystems = "/proc/filesystems";
82
bigbiffa957f072021-03-07 18:20:29 -050083static const char* kAndroidDir = "/Android/";
84static const char* kAppDataDir = "/Android/data/";
85static const char* kAppMediaDir = "/Android/media/";
86static const char* kAppObbDir = "/Android/obb/";
87
88static const char* kMediaProviderCtx = "u:r:mediaprovider:";
89static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
90
bigbiff7ba75002020-04-11 20:47:09 -040091// Lock used to protect process-level SELinux changes from racing with each
92// other between multiple threads.
93static std::mutex kSecurityLock;
94
bigbiffa957f072021-03-07 18:20:29 -050095std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path) {
96 return StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str());
97}
98
99android::status_t CreateDeviceNode(const std::string& path, dev_t dev) {
bigbiff7ba75002020-04-11 20:47:09 -0400100 std::lock_guard<std::mutex> lock(kSecurityLock);
101 const char* cpath = path.c_str();
bigbiffa957f072021-03-07 18:20:29 -0500102 android::status_t res = 0;
bigbiff7ba75002020-04-11 20:47:09 -0400103
104 char* secontext = nullptr;
105 if (sehandle) {
106 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
107 setfscreatecon(secontext);
108 }
109 }
110
111 mode_t mode = 0660 | S_IFBLK;
112 if (mknod(cpath, mode, dev) < 0) {
113 if (errno != EEXIST) {
114 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
115 << " at " << path;
116 res = -errno;
117 }
118 }
119
120 if (secontext) {
121 setfscreatecon(nullptr);
122 freecon(secontext);
123 }
124
125 return res;
126}
127
bigbiffa957f072021-03-07 18:20:29 -0500128android::status_t DestroyDeviceNode(const std::string& path) {
bigbiff7ba75002020-04-11 20:47:09 -0400129 const char* cpath = path.c_str();
130 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
131 return -errno;
132 } else {
bigbiffa957f072021-03-07 18:20:29 -0500133 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400134 }
135}
136
bigbiffa957f072021-03-07 18:20:29 -0500137// Sets a default ACL on the directory.
138int SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
139 std::vector<gid_t> additionalGids) {
140 if (IsSdcardfsUsed()) {
141 // sdcardfs magically takes care of this
142 return android::OK;
143 }
144
145 size_t num_entries = 3 + (additionalGids.size() > 0 ? additionalGids.size() + 1 : 0);
146 size_t size = sizeof(posix_acl_xattr_header) + num_entries * sizeof(posix_acl_xattr_entry);
147 auto buf = std::make_unique<uint8_t[]>(size);
148
149 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
150 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
151
152 posix_acl_xattr_entry* entry =
153 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
154
155 int tag_index = 0;
156
157 entry[tag_index].e_tag = ACL_USER_OBJ;
158 // The existing mode_t mask has the ACL in the lower 9 bits:
159 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
160 // Use the mode_t masks to get these bits out, and shift them to get the
161 // correct value per entity.
162 //
163 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
164 entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
165 entry[tag_index].e_id = uid;
166 tag_index++;
167
168 entry[tag_index].e_tag = ACL_GROUP_OBJ;
169 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
170 entry[tag_index].e_id = gid;
171 tag_index++;
172
173 if (additionalGids.size() > 0) {
174 for (gid_t additional_gid : additionalGids) {
175 entry[tag_index].e_tag = ACL_GROUP;
176 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
177 entry[tag_index].e_id = additional_gid;
178 tag_index++;
179 }
180
181 entry[tag_index].e_tag = ACL_MASK;
182 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
183 entry[tag_index].e_id = 0;
184 tag_index++;
185 }
186
187 entry[tag_index].e_tag = ACL_OTHER;
188 entry[tag_index].e_perm = mode & S_IRWXO;
189 entry[tag_index].e_id = 0;
190
191 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
192
193 if (ret != 0) {
194 PLOG(ERROR) << "Failed to set default ACL on " << path;
195 }
196
197 return ret;
198}
199
200int SetQuotaInherit(const std::string& path) {
201 unsigned long flags;
202
203 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
204 if (fd == -1) {
205 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
206 return -1;
207 }
208
209 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
210 if (ret == -1) {
211 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
212 return ret;
213 }
214
215 flags |= FS_PROJINHERIT_FL;
216
217 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
218 if (ret == -1) {
219 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
220 return ret;
221 }
222
223 return 0;
224}
225
226int SetQuotaProjectId(const std::string& path, long projectId) {
227 struct fsxattr fsx;
228
229 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
230 if (fd == -1) {
231 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
232 return -1;
233 }
234
235 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
236 if (ret == -1) {
237 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
238 return ret;
239 }
240
241 fsx.fsx_projid = projectId;
242 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
243}
244
245int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
246 long projectId) {
247 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
248
249 if (ret != 0) {
250 return ret;
251 }
252
253 if (!IsSdcardfsUsed()) {
254 ret = SetQuotaProjectId(path, projectId);
255 }
256
257 return ret;
258}
259
260static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
261 namespace fs = std::filesystem;
262
263 // Setup the directory itself correctly
264 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
265 if (ret != android::OK) {
266 return ret;
267 }
268
269 // Fixup all of its file entries
270 for (const auto& itEntry : fs::directory_iterator(path)) {
271 ret = lchown(itEntry.path().c_str(), uid, gid);
272 if (ret != 0) {
273 return ret;
274 }
275
276 ret = chmod(itEntry.path().c_str(), mode);
277 if (ret != 0) {
278 return ret;
279 }
280
281 if (!IsSdcardfsUsed()) {
282 ret = SetQuotaProjectId(itEntry.path(), projectId);
283 if (ret != 0) {
284 return ret;
285 }
286 }
287 }
288
289 return android::OK;
290}
291
292int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
293 bool fixupExisting) {
294 long projectId;
295 size_t pos;
296 int ret = 0;
297 bool sdcardfsSupport = IsSdcardfsUsed();
298
299 // Make sure the Android/ directories exist and are setup correctly
300 ret = PrepareAndroidDirs(root);
301 if (ret != 0) {
302 LOG(ERROR) << "Failed to prepare Android/ directories.";
303 return ret;
304 }
305
306 // Now create the application-specific subdir(s)
307 // path is something like /data/media/0/Android/data/com.foo/files
308 // First, chop off the volume root, eg /data/media/0
309 std::string pathFromRoot = path.substr(root.length());
310
311 uid_t uid = appUid;
312 gid_t gid = AID_MEDIA_RW;
313 std::vector<gid_t> additionalGids;
314 std::string appDir;
315
316 // Check that the next part matches one of the allowed Android/ dirs
317 if (StartsWith(pathFromRoot, kAppDataDir)) {
318 appDir = kAppDataDir;
319 if (!sdcardfsSupport) {
320 gid = AID_EXT_DATA_RW;
321 // Also add the app's own UID as a group; since apps belong to a group
322 // that matches their UID, this ensures that they will always have access to
323 // the files created in these dirs, even if they are created by other processes
324 additionalGids.push_back(uid);
325 }
326 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
327 appDir = kAppMediaDir;
328 if (!sdcardfsSupport) {
329 gid = AID_MEDIA_RW;
330 }
331 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
332 appDir = kAppObbDir;
333 if (!sdcardfsSupport) {
334 gid = AID_EXT_OBB_RW;
335 // See comments for kAppDataDir above
336 additionalGids.push_back(uid);
337 }
338 } else {
339 LOG(ERROR) << "Invalid application directory: " << path;
340 return -EINVAL;
341 }
342
343 // mode = 770, plus sticky bit on directory to inherit GID when apps
344 // create subdirs
345 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
346 // the project ID for application-specific directories is directly
347 // derived from their uid
348
349 // Chop off the generic application-specific part, eg /Android/data/
350 // this leaves us with something like com.foo/files/
351 std::string leftToCreate = pathFromRoot.substr(appDir.length());
352 if (!EndsWith(leftToCreate, "/")) {
353 leftToCreate += "/";
354 }
355 std::string pathToCreate = root + appDir;
356 int depth = 0;
357 // Derive initial project ID
358 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
359 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
360 } else if (appDir == kAppObbDir) {
361 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
362 }
363
364 while ((pos = leftToCreate.find('/')) != std::string::npos) {
365 std::string component = leftToCreate.substr(0, pos + 1);
366 leftToCreate = leftToCreate.erase(0, pos + 1);
367 pathToCreate = pathToCreate + component;
368
369 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
370 // All dirs use the "app" project ID, except for the cache dirs in
371 // Android/data, eg Android/data/com.foo/cache
372 // Note that this "sticks" - eg subdirs of this dir need the same
373 // project ID.
374 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
375 }
376
377 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
378 // Fixup all files in this existing directory with the correct UID/GID
379 // and project ID.
380 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
381 } else {
382 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
383 }
384
385 if (ret != 0) {
386 return ret;
387 }
388
389 if (depth == 0) {
390 // Set the default ACL on the top-level application-specific directories,
391 // to ensure that even if applications run with a umask of 0077,
392 // new directories within these directories will allow the GID
393 // specified here to write; this is necessary for apps like
394 // installers and MTP, that require access here.
395 //
396 // See man (5) acl for more details.
397 ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
398 if (ret != 0) {
399 return ret;
400 }
401
402 if (!sdcardfsSupport) {
403 // Set project ID inheritance, so that future subdirectories inherit the
404 // same project ID
405 ret = SetQuotaInherit(pathToCreate);
406 if (ret != 0) {
407 return ret;
408 }
409 }
410 }
411
412 depth++;
413 }
414
415 return android::OK;
416}
417
418android::status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
bigbiff7ba75002020-04-11 20:47:09 -0400419 std::lock_guard<std::mutex> lock(kSecurityLock);
420 const char* cpath = path.c_str();
421
422 char* secontext = nullptr;
423 if (sehandle) {
424 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
425 setfscreatecon(secontext);
426 }
427 }
428
429 int res = fs_prepare_dir(cpath, mode, uid, gid);
430
431 if (secontext) {
432 setfscreatecon(nullptr);
433 freecon(secontext);
434 }
435
436 if (res == 0) {
bigbiffa957f072021-03-07 18:20:29 -0500437 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400438 } else {
439 return -errno;
440 }
441}
442
bigbiffa957f072021-03-07 18:20:29 -0500443android::status_t ForceUnmount(const std::string& path) {
bigbiff7ba75002020-04-11 20:47:09 -0400444 const char* cpath = path.c_str();
445 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
bigbiffa957f072021-03-07 18:20:29 -0500446 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400447 }
448 // Apps might still be handling eject request, so wait before
449 // we start sending signals
450 if (sSleepOnUnmount) sleep(5);
451
bigbiffa957f072021-03-07 18:20:29 -0500452 android::vold::KillProcessesWithOpenFiles(path, SIGINT);
bigbiff7ba75002020-04-11 20:47:09 -0400453 if (sSleepOnUnmount) sleep(5);
454 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
bigbiffa957f072021-03-07 18:20:29 -0500455 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400456 }
457
bigbiffa957f072021-03-07 18:20:29 -0500458 android::vold::KillProcessesWithOpenFiles(path, SIGTERM);
bigbiff7ba75002020-04-11 20:47:09 -0400459 if (sSleepOnUnmount) sleep(5);
460 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
bigbiffa957f072021-03-07 18:20:29 -0500461 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400462 }
463
bigbiffa957f072021-03-07 18:20:29 -0500464 android::vold::KillProcessesWithOpenFiles(path, SIGKILL);
bigbiff7ba75002020-04-11 20:47:09 -0400465 if (sSleepOnUnmount) sleep(5);
466 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
bigbiffa957f072021-03-07 18:20:29 -0500467 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400468 }
bigbiffa957f072021-03-07 18:20:29 -0500469 PLOG(INFO) << "ForceUnmount failed";
bigbiff7ba75002020-04-11 20:47:09 -0400470 return -errno;
471}
472
bigbiffa957f072021-03-07 18:20:29 -0500473android::status_t KillProcessesWithMountPrefix(const std::string& path) {
474 if (android::vold::KillProcessesWithMounts(path, SIGINT) == 0) {
475 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400476 }
477 if (sSleepOnUnmount) sleep(5);
478
bigbiffa957f072021-03-07 18:20:29 -0500479 if (android::vold::KillProcessesWithMounts(path, SIGTERM) == 0) {
480 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400481 }
482 if (sSleepOnUnmount) sleep(5);
483
bigbiffa957f072021-03-07 18:20:29 -0500484 if (android::vold::KillProcessesWithMounts(path, SIGKILL) == 0) {
485 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400486 }
487 if (sSleepOnUnmount) sleep(5);
488
489 // Send SIGKILL a second time to determine if we've
bigbiffa957f072021-03-07 18:20:29 -0500490 // actually killed everyone mount
491 if (android::vold::KillProcessesWithMounts(path, SIGKILL) == 0) {
492 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400493 }
494 PLOG(ERROR) << "Failed to kill processes using " << path;
495 return -EBUSY;
496}
497
bigbiffa957f072021-03-07 18:20:29 -0500498android::status_t KillProcessesUsingPath(const std::string& path) {
499 if (android::vold::KillProcessesWithOpenFiles(path, SIGINT) == 0) {
500 return android::OK;
501 }
502 if (sSleepOnUnmount) sleep(5);
503
504 if (android::vold::KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
505 return android::OK;
506 }
507 if (sSleepOnUnmount) sleep(5);
508
509 if (android::vold::KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
510 return android::OK;
511 }
512 if (sSleepOnUnmount) sleep(5);
513
514 // Send SIGKILL a second time to determine if we've
515 // actually killed everyone with open files
516 if (android::vold::KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
517 return android::OK;
518 }
519 PLOG(ERROR) << "Failed to kill processes using " << path;
520 return -EBUSY;
521}
522
523android::status_t BindMount(const std::string& source, const std::string& target) {
bigbiff7ba75002020-04-11 20:47:09 -0400524 if (UnmountTree(target) < 0) {
525 return -errno;
526 }
527 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
528 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
529 return -errno;
530 }
bigbiffa957f072021-03-07 18:20:29 -0500531 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400532}
533
bigbiffa957f072021-03-07 18:20:29 -0500534android::status_t Symlink(const std::string& target, const std::string& linkpath) {
bigbiff7ba75002020-04-11 20:47:09 -0400535 if (Unlink(linkpath) < 0) {
536 return -errno;
537 }
538 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
539 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
540 return -errno;
541 }
bigbiffa957f072021-03-07 18:20:29 -0500542 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400543}
544
bigbiffa957f072021-03-07 18:20:29 -0500545android::status_t Unlink(const std::string& linkpath) {
bigbiff7ba75002020-04-11 20:47:09 -0400546 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
547 PLOG(ERROR) << "Failed to unlink " << linkpath;
548 return -errno;
549 }
bigbiffa957f072021-03-07 18:20:29 -0500550 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400551}
552
bigbiffa957f072021-03-07 18:20:29 -0500553android::status_t CreateDir(const std::string& dir, mode_t mode) {
bigbiff7ba75002020-04-11 20:47:09 -0400554 struct stat sb;
555 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
556 if (S_ISDIR(sb.st_mode)) {
bigbiffa957f072021-03-07 18:20:29 -0500557 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400558 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
559 PLOG(ERROR) << "Failed to unlink " << dir;
560 return -errno;
561 }
562 } else if (errno != ENOENT) {
563 PLOG(ERROR) << "Failed to stat " << dir;
564 return -errno;
565 }
566 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
567 PLOG(ERROR) << "Failed to mkdir " << dir;
568 return -errno;
569 }
bigbiffa957f072021-03-07 18:20:29 -0500570 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400571}
572
573bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
574 auto qual = key + "=\"";
575 size_t start = 0;
576 while (true) {
577 start = raw.find(qual, start);
578 if (start == std::string::npos) return false;
579 if (start == 0 || raw[start - 1] == ' ') {
580 break;
581 }
582 start += 1;
583 }
584 start += qual.length();
585
586 auto end = raw.find("\"", start);
587 if (end == std::string::npos) return false;
588
589 *value = raw.substr(start, end - start);
590 return true;
591}
592
bigbiffa957f072021-03-07 18:20:29 -0500593static android::status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
bigbiff7ba75002020-04-11 20:47:09 -0400594 std::string* fsLabel, bool untrusted) {
595 fsType->clear();
596 fsUuid->clear();
597 fsLabel->clear();
598
599 std::vector<std::string> cmd;
600 cmd.push_back(kBlkidPath);
601 cmd.push_back("-c");
602 cmd.push_back("/dev/null");
603 cmd.push_back("-s");
604 cmd.push_back("TYPE");
605 cmd.push_back("-s");
606 cmd.push_back("UUID");
607 cmd.push_back("-s");
608 cmd.push_back("LABEL");
609 cmd.push_back(path);
610
611 std::vector<std::string> output;
bigbiffa957f072021-03-07 18:20:29 -0500612 android::status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
613 if (res != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400614 LOG(WARNING) << "blkid failed to identify " << path;
615 return res;
616 }
617
618 for (const auto& line : output) {
619 // Extract values from blkid output, if defined
620 FindValue(line, "TYPE", fsType);
621 FindValue(line, "UUID", fsUuid);
622 FindValue(line, "LABEL", fsLabel);
623 }
624
bigbiffa957f072021-03-07 18:20:29 -0500625 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400626}
627
bigbiffa957f072021-03-07 18:20:29 -0500628android::status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
bigbiff7ba75002020-04-11 20:47:09 -0400629 std::string* fsLabel) {
630 return readMetadata(path, fsType, fsUuid, fsLabel, false);
631}
632
bigbiffa957f072021-03-07 18:20:29 -0500633android::status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
bigbiff7ba75002020-04-11 20:47:09 -0400634 std::string* fsLabel) {
635 return readMetadata(path, fsType, fsUuid, fsLabel, true);
636}
637
638static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
639 std::vector<const char*> argv;
640 argv.reserve(args.size() + 1);
641 for (const auto& arg : args) {
642 if (argv.empty()) {
643 LOG(DEBUG) << arg;
644 } else {
645 LOG(DEBUG) << " " << arg;
646 }
647 argv.emplace_back(arg.data());
648 }
649 argv.emplace_back(nullptr);
650 return argv;
651}
652
bigbiffa957f072021-03-07 18:20:29 -0500653static android::status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
bigbiff7ba75002020-04-11 20:47:09 -0400654 android::base::unique_fd ufd) {
655 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
656 if (!fp) {
657 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
658 return -errno;
659 }
660 if (output) output->clear();
661 char line[1024];
662 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
663 LOG(DEBUG) << line;
664 if (output) output->emplace_back(line);
665 }
bigbiffa957f072021-03-07 18:20:29 -0500666 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400667}
668
bigbiffa957f072021-03-07 18:20:29 -0500669android::status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
bigbiff7ba75002020-04-11 20:47:09 -0400670 security_context_t context) {
671 auto argv = ConvertToArgv(args);
672
673 android::base::unique_fd pipe_read, pipe_write;
674 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
675 PLOG(ERROR) << "Pipe in ForkExecvp";
676 return -errno;
677 }
678
679 pid_t pid = fork();
680 if (pid == 0) {
681 if (context) {
682 if (setexeccon(context)) {
683 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
684 abort();
685 }
686 }
687 pipe_read.reset();
688 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
689 PLOG(ERROR) << "dup2 in ForkExecvp";
690 _exit(EXIT_FAILURE);
691 }
692 pipe_write.reset();
693 execvp(argv[0], const_cast<char**>(argv.data()));
bigbiffa957f072021-03-07 18:20:29 -0500694 PLOG(ERROR) << "exec in ForkExecvp";
bigbiff7ba75002020-04-11 20:47:09 -0400695 _exit(EXIT_FAILURE);
696 }
697 if (pid == -1) {
698 PLOG(ERROR) << "fork in ForkExecvp";
699 return -errno;
700 }
701
702 pipe_write.reset();
703 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
704 if (st != 0) return st;
705
706 int status;
707 if (waitpid(pid, &status, 0) == -1) {
708 PLOG(ERROR) << "waitpid in ForkExecvp";
709 return -errno;
710 }
711 if (!WIFEXITED(status)) {
712 LOG(ERROR) << "Process did not exit normally, status: " << status;
713 return -ECHILD;
714 }
715 if (WEXITSTATUS(status)) {
716 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
717 return WEXITSTATUS(status);
718 }
bigbiffa957f072021-03-07 18:20:29 -0500719 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400720}
721
722pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
723 auto argv = ConvertToArgv(args);
724
725 pid_t pid = fork();
726 if (pid == 0) {
727 close(STDIN_FILENO);
728 close(STDOUT_FILENO);
729 close(STDERR_FILENO);
730
731 execvp(argv[0], const_cast<char**>(argv.data()));
732 PLOG(ERROR) << "exec in ForkExecvpAsync";
733 _exit(EXIT_FAILURE);
734 }
735 if (pid == -1) {
736 PLOG(ERROR) << "fork in ForkExecvpAsync";
737 return -1;
738 }
739 return pid;
740}
741
bigbiffa957f072021-03-07 18:20:29 -0500742android::status_t ReadRandomBytes(size_t bytes, std::string& out) {
bigbiff7ba75002020-04-11 20:47:09 -0400743 out.resize(bytes);
744 return ReadRandomBytes(bytes, &out[0]);
745}
746
bigbiffa957f072021-03-07 18:20:29 -0500747android::status_t ReadRandomBytes(size_t bytes, char* buf) {
bigbiff7ba75002020-04-11 20:47:09 -0400748 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
749 if (fd == -1) {
750 return -errno;
751 }
752
753 ssize_t n;
754 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
755 bytes -= n;
756 buf += n;
757 }
758 close(fd);
759
760 if (bytes == 0) {
bigbiffa957f072021-03-07 18:20:29 -0500761 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400762 } else {
763 return -EIO;
764 }
765}
766
bigbiffa957f072021-03-07 18:20:29 -0500767android::status_t GenerateRandomUuid(std::string& out) {
768 android::status_t res = ReadRandomBytes(16, out);
769 if (res == android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400770 out[6] &= 0x0f; /* clear version */
771 out[6] |= 0x40; /* set to version 4 */
772 out[8] &= 0x3f; /* clear variant */
773 out[8] |= 0x80; /* set to IETF variant */
774 }
775 return res;
776}
777
bigbiffa957f072021-03-07 18:20:29 -0500778android::status_t HexToStr(const std::string& hex, std::string& str) {
bigbiff7ba75002020-04-11 20:47:09 -0400779 str.clear();
780 bool even = true;
781 char cur = 0;
782 for (size_t i = 0; i < hex.size(); i++) {
783 int val = 0;
784 switch (hex[i]) {
785 // clang-format off
786 case ' ': case '-': case ':': continue;
787 case 'f': case 'F': val = 15; break;
788 case 'e': case 'E': val = 14; break;
789 case 'd': case 'D': val = 13; break;
790 case 'c': case 'C': val = 12; break;
791 case 'b': case 'B': val = 11; break;
792 case 'a': case 'A': val = 10; break;
793 case '9': val = 9; break;
794 case '8': val = 8; break;
795 case '7': val = 7; break;
796 case '6': val = 6; break;
797 case '5': val = 5; break;
798 case '4': val = 4; break;
799 case '3': val = 3; break;
800 case '2': val = 2; break;
801 case '1': val = 1; break;
802 case '0': val = 0; break;
803 default: return -EINVAL;
804 // clang-format on
805 }
806
807 if (even) {
808 cur = val << 4;
809 } else {
810 cur += val;
811 str.push_back(cur);
812 cur = 0;
813 }
814 even = !even;
815 }
bigbiffa957f072021-03-07 18:20:29 -0500816 return even ? android::OK : -EINVAL;
bigbiff7ba75002020-04-11 20:47:09 -0400817}
818
819static const char* kLookup = "0123456789abcdef";
820
bigbiffa957f072021-03-07 18:20:29 -0500821android::status_t StrToHex(const std::string& str, std::string& hex) {
bigbiff7ba75002020-04-11 20:47:09 -0400822 hex.clear();
823 for (size_t i = 0; i < str.size(); i++) {
824 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
825 hex.push_back(kLookup[str[i] & 0x0F]);
826 }
bigbiffa957f072021-03-07 18:20:29 -0500827 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400828}
829
bigbiffa957f072021-03-07 18:20:29 -0500830android::status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
bigbiff7ba75002020-04-11 20:47:09 -0400831 hex.clear();
832 for (size_t i = 0; i < str.size(); i++) {
833 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
834 hex.push_back(kLookup[str.data()[i] & 0x0F]);
835 }
bigbiffa957f072021-03-07 18:20:29 -0500836 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400837}
838
bigbiffa957f072021-03-07 18:20:29 -0500839android::status_t NormalizeHex(const std::string& in, std::string& out) {
bigbiff7ba75002020-04-11 20:47:09 -0400840 std::string tmp;
841 if (HexToStr(in, tmp)) {
842 return -EINVAL;
843 }
844 return StrToHex(tmp, out);
845}
846
bigbiffa957f072021-03-07 18:20:29 -0500847android::status_t GetBlockDevSize(int fd, uint64_t* size) {
bigbiff7ba75002020-04-11 20:47:09 -0400848 if (ioctl(fd, BLKGETSIZE64, size)) {
849 return -errno;
850 }
851
bigbiffa957f072021-03-07 18:20:29 -0500852 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400853}
854
bigbiffa957f072021-03-07 18:20:29 -0500855android::status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
bigbiff7ba75002020-04-11 20:47:09 -0400856 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
bigbiffa957f072021-03-07 18:20:29 -0500857 android::status_t res = android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400858
859 if (fd < 0) {
860 return -errno;
861 }
862
863 res = GetBlockDevSize(fd, size);
864
865 close(fd);
866
867 return res;
868}
869
bigbiffa957f072021-03-07 18:20:29 -0500870android::status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
bigbiff7ba75002020-04-11 20:47:09 -0400871 uint64_t size;
bigbiffa957f072021-03-07 18:20:29 -0500872 android::status_t res = GetBlockDevSize(path, &size);
bigbiff7ba75002020-04-11 20:47:09 -0400873
bigbiffa957f072021-03-07 18:20:29 -0500874 if (res != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400875 return res;
876 }
877
878 *nr_sec = size / 512;
879
bigbiffa957f072021-03-07 18:20:29 -0500880 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -0400881}
882
883uint64_t GetFreeBytes(const std::string& path) {
884 struct statvfs sb;
885 if (statvfs(path.c_str(), &sb) == 0) {
886 return (uint64_t)sb.f_bavail * sb.f_frsize;
887 } else {
888 return -1;
889 }
890}
891
892// TODO: borrowed from frameworks/native/libs/diskusage/ which should
893// eventually be migrated into system/
894static int64_t stat_size(struct stat* s) {
895 int64_t blksize = s->st_blksize;
896 // count actual blocks used instead of nominal file size
897 int64_t size = s->st_blocks * 512;
898
899 if (blksize) {
900 /* round up to filesystem block size */
901 size = (size + blksize - 1) & (~(blksize - 1));
902 }
903
904 return size;
905}
906
907// TODO: borrowed from frameworks/native/libs/diskusage/ which should
908// eventually be migrated into system/
909int64_t calculate_dir_size(int dfd) {
910 int64_t size = 0;
911 struct stat s;
912 DIR* d;
913 struct dirent* de;
914
915 d = fdopendir(dfd);
916 if (d == NULL) {
917 close(dfd);
918 return 0;
919 }
920
921 while ((de = readdir(d))) {
922 const char* name = de->d_name;
923 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
924 size += stat_size(&s);
925 }
926 if (de->d_type == DT_DIR) {
927 int subfd;
928
929 /* always skip "." and ".." */
930 if (name[0] == '.') {
931 if (name[1] == 0) continue;
932 if ((name[1] == '.') && (name[2] == 0)) continue;
933 }
934
935 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
936 if (subfd >= 0) {
937 size += calculate_dir_size(subfd);
938 }
939 }
940 }
941 closedir(d);
942 return size;
943}
944
945uint64_t GetTreeBytes(const std::string& path) {
946 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
947 if (dirfd < 0) {
948 PLOG(WARNING) << "Failed to open " << path;
949 return -1;
950 } else {
951 return calculate_dir_size(dirfd);
952 }
953}
954
bigbiffa957f072021-03-07 18:20:29 -0500955// TODO: Use a better way to determine if it's media provider app.
956bool IsFuseDaemon(const pid_t pid) {
957 auto path = StringPrintf("/proc/%d/mounts", pid);
958 char* tmp;
959 if (lgetfilecon(path.c_str(), &tmp) < 0) {
960 return false;
961 }
962 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
963 || android::base::StartsWith(tmp, kMediaProviderCtx);
964 freecon(tmp);
965 return result;
966}
967
bigbiff7ba75002020-04-11 20:47:09 -0400968bool IsFilesystemSupported(const std::string& fsType) {
969 std::string supported;
970 if (!ReadFileToString(kProcFilesystems, &supported)) {
971 PLOG(ERROR) << "Failed to read supported filesystems";
972 return false;
973 }
974 return supported.find(fsType + "\n") != std::string::npos;
975}
976
bigbiffa957f072021-03-07 18:20:29 -0500977bool IsSdcardfsUsed() {
978 return IsFilesystemSupported("sdcardfs") &&
979 android::base::GetBoolProperty(kExternalStorageSdcardfs, true);
980}
981
982android::status_t WipeBlockDevice(const std::string& path) {
983 android::status_t res = -1;
bigbiff7ba75002020-04-11 20:47:09 -0400984 const char* c_path = path.c_str();
985 uint64_t range[2] = {0, 0};
986
987 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
988 if (fd == -1) {
989 PLOG(ERROR) << "Failed to open " << path;
990 goto done;
991 }
992
bigbiffa957f072021-03-07 18:20:29 -0500993 if (GetBlockDevSize(fd, &range[1]) != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400994 PLOG(ERROR) << "Failed to determine size of " << path;
995 goto done;
996 }
997
998 LOG(INFO) << "About to discard " << range[1] << " on " << path;
999 if (ioctl(fd, BLKDISCARD, &range) == 0) {
1000 LOG(INFO) << "Discard success on " << path;
1001 res = 0;
1002 } else {
1003 PLOG(ERROR) << "Discard failure on " << path;
1004 }
1005
1006done:
1007 close(fd);
1008 return res;
1009}
1010
1011static bool isValidFilename(const std::string& name) {
1012 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
1013 return false;
1014 } else {
1015 return true;
1016 }
1017}
1018
1019std::string BuildKeyPath(const std::string& partGuid) {
1020 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1021}
1022
1023std::string BuildDataSystemLegacyPath(userid_t userId) {
1024 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
1025}
1026
1027std::string BuildDataSystemCePath(userid_t userId) {
1028 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
1029}
1030
1031std::string BuildDataSystemDePath(userid_t userId) {
1032 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
1033}
1034
1035std::string BuildDataMiscLegacyPath(userid_t userId) {
1036 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
1037}
1038
1039std::string BuildDataMiscCePath(userid_t userId) {
1040 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
1041}
1042
1043std::string BuildDataMiscDePath(userid_t userId) {
1044 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
1045}
1046
1047// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1048std::string BuildDataProfilesDePath(userid_t userId) {
1049 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
1050}
1051
1052std::string BuildDataVendorCePath(userid_t userId) {
1053 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1054}
1055
1056std::string BuildDataVendorDePath(userid_t userId) {
1057 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1058}
1059
1060std::string BuildDataPath(const std::string& volumeUuid) {
1061 // TODO: unify with installd path generation logic
1062 if (volumeUuid.empty()) {
1063 return "/data";
1064 } else {
1065 CHECK(isValidFilename(volumeUuid));
1066 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
1067 }
1068}
1069
1070std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
1071 // TODO: unify with installd path generation logic
1072 std::string data(BuildDataPath(volumeUuid));
1073 return StringPrintf("%s/media/%u", data.c_str(), userId);
1074}
1075
1076std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
1077 // TODO: unify with installd path generation logic
1078 std::string data(BuildDataPath(volumeUuid));
1079 if (volumeUuid.empty() && userId == 0) {
1080 std::string legacy = StringPrintf("%s/data", data.c_str());
1081 struct stat sb;
1082 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1083 /* /data/data is dir, return /data/data for legacy system */
1084 return legacy;
1085 }
1086 }
1087 return StringPrintf("%s/user/%u", data.c_str(), userId);
1088}
1089
1090std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
1091 // TODO: unify with installd path generation logic
1092 std::string data(BuildDataPath(volumeUuid));
1093 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1094}
1095
1096dev_t GetDevice(const std::string& path) {
1097 struct stat sb;
1098 if (stat(path.c_str(), &sb)) {
1099 PLOG(WARNING) << "Failed to stat " << path;
1100 return 0;
1101 } else {
1102 return sb.st_dev;
1103 }
1104}
1105
bigbiffa957f072021-03-07 18:20:29 -05001106android::status_t RestoreconRecursive(const std::string& path) {
bigbiff7ba75002020-04-11 20:47:09 -04001107 LOG(DEBUG) << "Starting restorecon of " << path;
1108
1109 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
1110
1111 android::base::SetProperty(kRestoreconString, "");
1112 android::base::SetProperty(kRestoreconString, path);
1113
1114 android::base::WaitForProperty(kRestoreconString, path);
1115
1116 LOG(DEBUG) << "Finished restorecon of " << path;
bigbiffa957f072021-03-07 18:20:29 -05001117 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -04001118}
1119
1120bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1121 // Shamelessly borrowed from android::base::Readlink()
1122 result->clear();
1123
1124 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1125 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1126 // waste memory to just start there. We add 1 so that we can recognize
1127 // whether it actually fit (rather than being truncated to 4095).
1128 std::vector<char> buf(4095 + 1);
1129 while (true) {
1130 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1131 // Unrecoverable error?
1132 if (size == -1) return false;
1133 // It fit! (If size == buf.size(), it may have been truncated.)
1134 if (static_cast<size_t>(size) < buf.size()) {
1135 result->assign(&buf[0], size);
1136 return true;
1137 }
1138 // Double our buffer and try again.
1139 buf.resize(buf.size() * 2);
1140 }
1141}
1142
bigbiffa957f072021-03-07 18:20:29 -05001143static unsigned int GetMajorBlockVirtioBlk() {
1144 std::string devices;
1145 if (!ReadFileToString(kProcDevices, &devices)) {
1146 PLOG(ERROR) << "Unable to open /proc/devices";
1147 return 0;
1148 }
1149
1150 bool blockSection = false;
1151 for (auto line : android::base::Split(devices, "\n")) {
1152 if (line == "Block devices:") {
1153 blockSection = true;
1154 } else if (line == "Character devices:") {
1155 blockSection = false;
1156 } else if (blockSection) {
1157 auto tokens = android::base::Split(line, " ");
1158 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1159 return std::stoul(tokens[0]);
1160 }
1161 }
1162 }
1163
1164 return 0;
bigbiff7ba75002020-04-11 20:47:09 -04001165}
1166
bigbiffa957f072021-03-07 18:20:29 -05001167bool IsVirtioBlkDevice(unsigned int major) {
1168 // Most virtualized platforms expose block devices with the virtio-blk
1169 // block device driver. Unfortunately, this driver does not use a fixed
1170 // major number, but relies on the kernel to assign one from a specific
1171 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1172 // per Documentation/devices.txt. This is true even for the latest Linux
1173 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1174 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1175 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
1176}
1177
1178static android::status_t findMountPointsWithPrefix(const std::string& prefix,
bigbiff7ba75002020-04-11 20:47:09 -04001179 std::list<std::string>& mountPoints) {
1180 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1181 // when the prefix is /foo/bar
1182 std::string prefixWithSlash(prefix);
1183 if (prefix.back() != '/') {
1184 android::base::StringAppendF(&prefixWithSlash, "/");
1185 }
1186
1187 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1188 if (!mnts) {
1189 PLOG(ERROR) << "Unable to open /proc/mounts";
1190 return -errno;
1191 }
1192
1193 // Some volumes can be stacked on each other, so force unmount in
1194 // reverse order to give us the best chance of success.
1195 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1196 while ((mnt = getmntent(mnts.get())) != nullptr) {
1197 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1198 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1199 mountPoints.push_front(mountPoint);
1200 }
1201 }
bigbiffa957f072021-03-07 18:20:29 -05001202 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -04001203}
1204
1205// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
bigbiffa957f072021-03-07 18:20:29 -05001206android::status_t UnmountTreeWithPrefix(const std::string& prefix) {
bigbiff7ba75002020-04-11 20:47:09 -04001207 std::list<std::string> toUnmount;
bigbiffa957f072021-03-07 18:20:29 -05001208 android::status_t result = findMountPointsWithPrefix(prefix, toUnmount);
bigbiff7ba75002020-04-11 20:47:09 -04001209 if (result < 0) {
1210 return result;
1211 }
1212 for (const auto& path : toUnmount) {
1213 if (umount2(path.c_str(), MNT_DETACH)) {
1214 PLOG(ERROR) << "Failed to unmount " << path;
1215 result = -errno;
1216 }
1217 }
1218 return result;
1219}
1220
bigbiffa957f072021-03-07 18:20:29 -05001221android::status_t UnmountTree(const std::string& mountPoint) {
bigbiff7ba75002020-04-11 20:47:09 -04001222 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1223 errno != ENOENT) {
1224 PLOG(ERROR) << "Failed to unmount " << mountPoint;
1225 return -errno;
1226 }
bigbiffa957f072021-03-07 18:20:29 -05001227 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -04001228}
1229
bigbiffa957f072021-03-07 18:20:29 -05001230static android::status_t delete_dir_contents(DIR* dir) {
bigbiff7ba75002020-04-11 20:47:09 -04001231 // Shamelessly borrowed from android::installd
1232 int dfd = dirfd(dir);
1233 if (dfd < 0) {
1234 return -errno;
1235 }
1236
bigbiffa957f072021-03-07 18:20:29 -05001237 android::status_t result = android::OK;
bigbiff7ba75002020-04-11 20:47:09 -04001238 struct dirent* de;
1239 while ((de = readdir(dir))) {
1240 const char* name = de->d_name;
1241 if (de->d_type == DT_DIR) {
1242 /* always skip "." and ".." */
1243 if (name[0] == '.') {
1244 if (name[1] == 0) continue;
1245 if ((name[1] == '.') && (name[2] == 0)) continue;
1246 }
1247
1248 android::base::unique_fd subfd(
1249 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1250 if (subfd.get() == -1) {
1251 PLOG(ERROR) << "Couldn't openat " << name;
1252 result = -errno;
1253 continue;
1254 }
1255 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1256 android::base::Fdopendir(std::move(subfd)), closedir);
1257 if (!subdirp) {
1258 PLOG(ERROR) << "Couldn't fdopendir " << name;
1259 result = -errno;
1260 continue;
1261 }
1262 result = delete_dir_contents(subdirp.get());
1263 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1264 PLOG(ERROR) << "Couldn't unlinkat " << name;
1265 result = -errno;
1266 }
1267 } else {
1268 if (unlinkat(dfd, name, 0) < 0) {
1269 PLOG(ERROR) << "Couldn't unlinkat " << name;
1270 result = -errno;
1271 }
1272 }
1273 }
1274 return result;
1275}
1276
bigbiffa957f072021-03-07 18:20:29 -05001277android::status_t DeleteDirContentsAndDir(const std::string& pathname) {
1278 android::status_t res = DeleteDirContents(pathname);
bigbiff7ba75002020-04-11 20:47:09 -04001279 if (res < 0) {
1280 return res;
1281 }
1282 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
1283 PLOG(ERROR) << "rmdir failed on " << pathname;
1284 return -errno;
1285 }
1286 LOG(VERBOSE) << "Success: rmdir on " << pathname;
bigbiffa957f072021-03-07 18:20:29 -05001287 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -04001288}
1289
bigbiffa957f072021-03-07 18:20:29 -05001290android::status_t DeleteDirContents(const std::string& pathname) {
bigbiff7ba75002020-04-11 20:47:09 -04001291 // Shamelessly borrowed from android::installd
1292 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1293 if (!dirp) {
1294 if (errno == ENOENT) {
bigbiffa957f072021-03-07 18:20:29 -05001295 return android::OK;
bigbiff7ba75002020-04-11 20:47:09 -04001296 }
1297 PLOG(ERROR) << "Failed to opendir " << pathname;
1298 return -errno;
1299 }
1300 return delete_dir_contents(dirp.get());
1301}
1302
1303// TODO(118708649): fix duplication with init/util.h
bigbiffa957f072021-03-07 18:20:29 -05001304android::status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
bigbiff7ba75002020-04-11 20:47:09 -04001305 android::base::Timer t;
1306 while (t.duration() < timeout) {
1307 struct stat sb;
1308 if (stat(filename, &sb) != -1) {
1309 LOG(INFO) << "wait for '" << filename << "' took " << t;
1310 return 0;
1311 }
1312 std::this_thread::sleep_for(10ms);
1313 }
1314 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1315 return -1;
1316}
1317
1318bool FsyncDirectory(const std::string& dirname) {
1319 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1320 if (fd == -1) {
1321 PLOG(ERROR) << "Failed to open " << dirname;
1322 return false;
1323 }
1324 if (fsync(fd) == -1) {
1325 if (errno == EROFS || errno == EINVAL) {
1326 PLOG(WARNING) << "Skip fsync " << dirname
1327 << " on a file system does not support synchronization";
1328 } else {
1329 PLOG(ERROR) << "Failed to fsync " << dirname;
1330 return false;
1331 }
1332 }
1333 return true;
1334}
1335
1336bool writeStringToFile(const std::string& payload, const std::string& filename) {
1337 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1338 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1339 if (fd == -1) {
1340 PLOG(ERROR) << "Failed to open " << filename;
1341 return false;
1342 }
1343 if (!android::base::WriteStringToFd(payload, fd)) {
1344 PLOG(ERROR) << "Failed to write to " << filename;
1345 unlink(filename.c_str());
1346 return false;
1347 }
1348 // fsync as close won't guarantee flush data
1349 // see close(2), fsync(2) and b/68901441
1350 if (fsync(fd) == -1) {
1351 if (errno == EROFS || errno == EINVAL) {
1352 PLOG(WARNING) << "Skip fsync " << filename
1353 << " on a file system does not support synchronization";
1354 } else {
1355 PLOG(ERROR) << "Failed to fsync " << filename;
1356 unlink(filename.c_str());
1357 return false;
1358 }
1359 }
1360 return true;
1361}
1362
bigbiffa957f072021-03-07 18:20:29 -05001363android::status_t AbortFuseConnections() {
1364 namespace fs = std::filesystem;
1365
1366 for (const auto& itEntry : fs::directory_iterator("/sys/fs/fuse/connections")) {
1367 std::string abortPath = itEntry.path().string() + "/abort";
1368 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1369 bool ret = writeStringToFile("1", abortPath);
1370 if (!ret) {
1371 LOG(WARNING) << "Failed to write to " << abortPath;
1372 }
1373 }
1374
1375 return android::OK;
1376}
1377
1378android::status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1379 if (access(path.c_str(), F_OK) != 0) {
1380 PLOG(WARNING) << "Dir does not exist: " << path;
1381 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1382 return -errno;
1383 }
1384 }
1385 return android::OK;
1386}
1387
1388// Gets the sysfs path for parameters of the backing device info (bdi)
1389static std::string getBdiPathForMount(const std::string& mount) {
1390 // First figure out MAJOR:MINOR of mount. Simplest way is to stat the path.
1391 struct stat info;
1392 if (stat(mount.c_str(), &info) != 0) {
1393 PLOG(ERROR) << "Failed to stat " << mount;
1394 return "";
1395 }
1396 unsigned int maj = major(info.st_dev);
1397 unsigned int min = minor(info.st_dev);
1398
1399 return StringPrintf("/sys/class/bdi/%u:%u", maj, min);
1400}
1401
1402// Configures max_ratio for the FUSE filesystem.
1403void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio) {
1404 LOG(INFO) << "Configuring max_ratio of " << fuse_mount << " fuse filesystem to " << max_ratio;
1405 if (max_ratio > 100) {
1406 LOG(ERROR) << "Invalid max_ratio: " << max_ratio;
1407 return;
1408 }
1409 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1410 if (fuseBdiPath == "") {
1411 return;
1412 }
1413 std::string max_ratio_file = StringPrintf("%s/max_ratio", fuseBdiPath.c_str());
1414 unique_fd fd(TEMP_FAILURE_RETRY(open(max_ratio_file.c_str(), O_WRONLY | O_CLOEXEC)));
1415 if (fd.get() == -1) {
1416 PLOG(ERROR) << "Failed to open " << max_ratio_file;
1417 return;
1418 }
1419 LOG(INFO) << "Writing " << max_ratio << " to " << max_ratio_file;
1420 if (!WriteStringToFd(std::to_string(max_ratio), fd)) {
1421 PLOG(ERROR) << "Failed to write to " << max_ratio_file;
1422 }
1423}
1424
1425// Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1426// writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
1427void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1428 LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1429 << read_ahead_kb << "kb";
1430 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1431 if (fuseBdiPath == "") {
1432 return;
1433 }
1434 // We found the bdi path for our filesystem, time to configure read ahead!
1435 std::string read_ahead_file = StringPrintf("%s/read_ahead_kb", fuseBdiPath.c_str());
1436 unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1437 if (fd.get() == -1) {
1438 PLOG(ERROR) << "Failed to open " << read_ahead_file;
1439 return;
1440 }
1441 LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1442 if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1443 PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1444 }
1445}
1446
1447android::status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1448 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1449 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1450 std::string fuse_path(
1451 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1452
1453 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1454 std::string pass_through_path(
1455 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
1456
1457 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1458 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
1459 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
1460 if (result != android::OK) {
1461 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1462 return -1;
1463 }
1464
1465 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1466 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1467 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1468 // These bits should be consistent with what is set in zygote in
1469 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
1470 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
1471 multiuser_get_uid(user_id, AID_EVERYBODY));
1472 if (result != android::OK) {
1473 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
1474 return -1;
1475 }
1476
1477 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1478 if (result != android::OK) {
1479 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1480 return -1;
1481 }
1482
1483 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
1484 if (result != android::OK) {
1485 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1486 return -1;
1487 }
1488
1489 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
1490 if (result != android::OK) {
1491 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1492 return -1;
1493 }
1494
1495 if (relative_upper_path == "emulated") {
1496 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1497 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
1498 if (result != android::OK) {
1499 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
1500 return -1;
1501 }
1502 linkpath += "/primary";
1503 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
1504
1505 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
1506 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
1507 if (result != android::OK) {
1508 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1509 return -1;
1510 }
1511 pass_through_linkpath += "/primary";
1512 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
1513 }
1514
1515 // Open fuse fd.
1516 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1517 if (fuse_fd->get() == -1) {
1518 PLOG(ERROR) << "Failed to open /dev/fuse";
1519 return -1;
1520 }
1521
1522 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1523 // permission checks before routing to FUSE daemon.
1524 const auto opts = StringPrintf(
1525 "fd=%i,"
1526 "rootmode=40000,"
1527 "allow_other,"
1528 "user_id=0,group_id=0,",
1529 fuse_fd->get());
1530
1531 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1532 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1533 opts.c_str()));
1534 if (result != 0) {
1535 PLOG(ERROR) << "Failed to mount " << fuse_path;
1536 return -errno;
1537 }
1538
1539 if (IsSdcardfsUsed()) {
1540 std::string sdcardfs_path(
1541 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1542
1543 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1544 return BindMount(sdcardfs_path, pass_through_path);
1545 } else {
1546 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1547 return BindMount(absolute_lower_path, pass_through_path);
1548 }
1549}
1550
1551android::status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1552 const std::string& relative_upper_path) {
1553 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1554 std::string pass_through_path(
1555 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1556
1557 // Best effort unmount pass_through path
1558 sSleepOnUnmount = false;
1559 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1560 auto status = ForceUnmount(pass_through_path);
1561 if (status != android::OK) {
1562 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1563 }
1564 rmdir(pass_through_path.c_str());
1565
1566 LOG(INFO) << "Unmounting fuse path " << fuse_path;
1567 android::status_t result = ForceUnmount(fuse_path);
1568 sSleepOnUnmount = true;
1569 if (result != android::OK) {
1570 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1571 // Figure out why we get EBUSY and remove this special casing if possible.
1572 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1573 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1574 errno != ENOENT) {
1575 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1576 return -errno;
1577 }
1578 result = android::OK;
1579 }
1580 rmdir(fuse_path.c_str());
1581
1582 return result;
1583}
1584
1585android::status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1586 std::string androidDir = volumeRoot + kAndroidDir;
1587 std::string androidDataDir = volumeRoot + kAppDataDir;
1588 std::string androidObbDir = volumeRoot + kAppObbDir;
1589 std::string androidMediaDir = volumeRoot + kAppMediaDir;
1590
1591 bool useSdcardFs = IsSdcardfsUsed();
1592
1593 // mode 0771 + sticky bit for inheriting GIDs
1594 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1595 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1596 PLOG(ERROR) << "Failed to create " << androidDir;
1597 return -errno;
1598 }
1599
1600 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
1601 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
1602 PLOG(ERROR) << "Failed to create " << androidDataDir;
1603 return -errno;
1604 }
1605
1606 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
1607 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
1608 PLOG(ERROR) << "Failed to create " << androidObbDir;
1609 return -errno;
1610 }
1611 // Some other apps, like installers, have write access to the OBB directory
1612 // to pre-download them. To make sure newly created folders in this directory
1613 // have the right permissions, set a default ACL.
1614 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
1615
1616 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1617 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1618 return -errno;
1619 }
1620
1621 return android::OK;
1622}