blob: 04a61d0305c4e482e232a9673aa2df5fd36813b0 [file] [log] [blame]
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkeydeb24052015-03-02 21:01:40 -080017#include "Utils.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070018
Jeff Sharkeydeb24052015-03-02 21:01:40 -080019#include "Process.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070020#include "sehandle.h"
Jeff Sharkeydeb24052015-03-02 21:01:40 -080021
Paul Crowley298fa322018-10-30 15:59:24 -070022#include <android-base/chrono_utils.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080023#include <android-base/file.h>
24#include <android-base/logging.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070025#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080026#include <android-base/stringprintf.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070027#include <android-base/strings.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070028#include <android-base/unique_fd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080029#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070030#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070031#include <private/android_filesystem_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080032
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070033#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080034#include <fcntl.h>
35#include <linux/fs.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070036#include <mntent.h>
37#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080038#include <stdlib.h>
Tommy Chiu0bd2d112019-03-26 17:18:09 +080039#include <unistd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080040#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080041#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070042#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070043#include <sys/sysmacros.h>
44#include <sys/types.h>
45#include <sys/wait.h>
Paul Crowley747b4212019-04-05 04:09:57 -070046#include <unistd.h>
Paul Crowley298fa322018-10-30 15:59:24 -070047
Sudheer Shanka89ddf992018-09-25 14:22:07 -070048#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070049#include <mutex>
Martijn Coenen04bb17f2020-02-10 23:48:11 +010050#include <regex>
Paul Crowley298fa322018-10-30 15:59:24 -070051#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080052
53#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070054#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080055#endif
56
Paul Crowley298fa322018-10-30 15:59:24 -070057using namespace std::chrono_literals;
Martijn Coenenba9868b2020-01-31 15:49:24 +010058using android::base::EndsWith;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070059using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010060using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070061using android::base::StringPrintf;
62
Jeff Sharkeydeb24052015-03-02 21:01:40 -080063namespace android {
64namespace vold {
65
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070066security_context_t sBlkidContext = nullptr;
67security_context_t sBlkidUntrustedContext = nullptr;
68security_context_t sFsckContext = nullptr;
69security_context_t sFsckUntrustedContext = nullptr;
70
Paul Crowley56292ef2017-10-20 08:07:53 -070071bool sSleepOnUnmount = true;
72
Jeff Sharkey9c484982015-03-31 10:35:33 -070073static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070074static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070075
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070076static const char* kProcFilesystems = "/proc/filesystems";
77
Martijn Coenen04bb17f2020-02-10 23:48:11 +010078static const char* kAndroidDir = "/Android/";
79static const char* kAppDataDir = "/Android/data/";
80static const char* kAppMediaDir = "/Android/media/";
81static const char* kAppObbDir = "/Android/obb/";
82
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060083// Lock used to protect process-level SELinux changes from racing with each
84// other between multiple threads.
85static std::mutex kSecurityLock;
86
Jeff Sharkeydeb24052015-03-02 21:01:40 -080087status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060088 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080089 const char* cpath = path.c_str();
90 status_t res = 0;
91
92 char* secontext = nullptr;
93 if (sehandle) {
94 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
95 setfscreatecon(secontext);
96 }
97 }
98
99 mode_t mode = 0660 | S_IFBLK;
100 if (mknod(cpath, mode, dev) < 0) {
101 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700102 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
103 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800104 res = -errno;
105 }
106 }
107
108 if (secontext) {
109 setfscreatecon(nullptr);
110 freecon(secontext);
111 }
112
113 return res;
114}
115
116status_t DestroyDeviceNode(const std::string& path) {
117 const char* cpath = path.c_str();
118 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
119 return -errno;
120 } else {
121 return OK;
122 }
123}
124
Martijn Coenen5fe1b162020-02-06 18:57:47 +0100125int SetQuotaInherit(const std::string& path) {
126 unsigned long flags;
127
128 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
129 if (fd == -1) {
130 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
131 return -1;
132 }
133
134 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
135 if (ret == -1) {
136 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
137 return ret;
138 }
139
140 flags |= FS_PROJINHERIT_FL;
141
142 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
143 if (ret == -1) {
144 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
145 return ret;
146 }
147
148 return 0;
149}
150
151int SetQuotaProjectId(const std::string& path, long projectId) {
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100152 struct fsxattr fsx;
153
154 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
155 if (fd == -1) {
156 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
157 return -1;
158 }
159
160 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
161 if (ret == -1) {
162 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
163 return ret;
164 }
165
166 fsx.fsx_projid = projectId;
167 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
168}
169
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100170int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
171 long projectId) {
172 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
173
174 if (ret != 0) {
175 return ret;
Martijn Coenen13ff6682019-12-24 12:57:16 +0100176 }
Martijn Coenenba9868b2020-01-31 15:49:24 +0100177
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100178 if (!IsFilesystemSupported("sdcardfs")) {
179 ret = SetQuotaProjectId(path, projectId);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100180 }
181
182 return ret;
183}
184
Martijn Coenen04bb17f2020-02-10 23:48:11 +0100185static gid_t getAppDirGid(const std::string& appDir) {
186 gid_t gid = AID_MEDIA_RW;
187 if (!IsFilesystemSupported("sdcardfs")) {
188 if (appDir == android::vold::kAppDataDir) {
189 gid = AID_EXT_DATA_RW;
190 } else if (appDir == android::vold::kAppObbDir) {
191 gid = AID_EXT_OBB_RW;
192 } else if (appDir == android::vold::kAppMediaDir) {
193 gid = AID_MEDIA_RW;
194 } else {
195 gid = AID_MEDIA_RW;
196 }
197 }
198
199 return gid;
200}
201
202int PrepareAppDirFromRoot(std::string path, int appUid) {
203 int ret = 0;
204 // Extract various parts of the path to setup correctly
205 // Sample path:
206 // /data/media/0/Android/data/com.foo/files
207 // [1]: path in which to create app-specific dir, eg. /data/media/0/Android/data/
208 // [2]: the part of [1] starting from /Android, eg. /Android/data/
209 // [3]: the package name part of the path, eg. com.foo
210 // [4]: the directory to create within [3], eg files
211 std::regex re("(^/.*(/Android/(?:data|media|obb|sandbox)/))([^/]+)/([^/]+)?/?");
212
213 std::smatch match;
214 bool is_match = regex_match(path, match, re);
215
216 if (!is_match) {
217 LOG(ERROR) << "Invalid application directory: " << path;
218 return -EINVAL;
219 }
220
221 uid_t uid = appUid;
222 gid_t gid = getAppDirGid(match.str(2));
223 // mode = 770, plus sticky bit on directory to inherit GID when apps
224 // create subdirs
225 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
226 long projectId = uid - AID_APP_START + AID_EXT_GID_START;
227
228 // First, create the package-path
229 std::string package_path = match.str(1) + match.str(3);
230 ret = PrepareDirWithProjectId(package_path, mode, uid, gid, projectId);
231 if (ret) {
232 return ret;
233 }
234
235 // Next, create the directory within the package, if needed
236 if (match.size() <= 4) {
237 return OK;
238 }
239
240 if (match.str(4) == "cache") {
241 // All dirs use the "app" project ID, except for the cache dir
242 projectId = uid - AID_APP_START + AID_CACHE_GID_START;
243 }
244 return PrepareDirWithProjectId(path.c_str(), mode, uid, gid, projectId);
245}
246
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700247status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600248 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700249 const char* cpath = path.c_str();
250
251 char* secontext = nullptr;
252 if (sehandle) {
253 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
254 setfscreatecon(secontext);
255 }
256 }
257
258 int res = fs_prepare_dir(cpath, mode, uid, gid);
259
260 if (secontext) {
261 setfscreatecon(nullptr);
262 freecon(secontext);
263 }
264
265 if (res == 0) {
266 return OK;
267 } else {
268 return -errno;
269 }
270}
271
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800272status_t ForceUnmount(const std::string& path) {
273 const char* cpath = path.c_str();
274 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
275 return OK;
276 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700277 // Apps might still be handling eject request, so wait before
278 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700279 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700280
Jeff Sharkey3472e522017-10-06 18:02:53 -0600281 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700282 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700283 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
284 return OK;
285 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700286
Jeff Sharkey3472e522017-10-06 18:02:53 -0600287 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700288 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800289 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
290 return OK;
291 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700292
Jeff Sharkey3472e522017-10-06 18:02:53 -0600293 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700294 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700295 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
296 return OK;
297 }
Zim3623a212019-07-19 16:46:53 +0100298 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800299 return -errno;
300}
301
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700302status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600303 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700304 return OK;
305 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700306 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700307
Jeff Sharkey3472e522017-10-06 18:02:53 -0600308 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700309 return OK;
310 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700311 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700312
Jeff Sharkey3472e522017-10-06 18:02:53 -0600313 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700314 return OK;
315 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700316 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700317
318 // Send SIGKILL a second time to determine if we've
319 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600320 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700321 return OK;
322 }
323 PLOG(ERROR) << "Failed to kill processes using " << path;
324 return -EBUSY;
325}
326
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700327status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800328 if (UnmountTree(target) < 0) {
329 return -errno;
330 }
331 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700332 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
333 return -errno;
334 }
335 return OK;
336}
337
Sudheer Shanka023b5392019-02-06 12:39:19 -0800338status_t Symlink(const std::string& target, const std::string& linkpath) {
339 if (Unlink(linkpath) < 0) {
340 return -errno;
341 }
342 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
343 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
344 return -errno;
345 }
346 return OK;
347}
348
349status_t Unlink(const std::string& linkpath) {
350 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
351 PLOG(ERROR) << "Failed to unlink " << linkpath;
352 return -errno;
353 }
354 return OK;
355}
356
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000357status_t CreateDir(const std::string& dir, mode_t mode) {
358 struct stat sb;
359 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
360 if (S_ISDIR(sb.st_mode)) {
361 return OK;
362 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
363 PLOG(ERROR) << "Failed to unlink " << dir;
364 return -errno;
365 }
366 } else if (errno != ENOENT) {
367 PLOG(ERROR) << "Failed to stat " << dir;
368 return -errno;
369 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800370 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000371 PLOG(ERROR) << "Failed to mkdir " << dir;
372 return -errno;
373 }
374 return OK;
375}
376
Jeff Sharkey3472e522017-10-06 18:02:53 -0600377bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
378 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800379 size_t start = 0;
380 while (true) {
381 start = raw.find(qual, start);
382 if (start == std::string::npos) return false;
383 if (start == 0 || raw[start - 1] == ' ') {
384 break;
385 }
386 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600387 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600388 start += qual.length();
389
390 auto end = raw.find("\"", start);
391 if (end == std::string::npos) return false;
392
393 *value = raw.substr(start, end - start);
394 return true;
395}
396
Paul Crowley14c8c072018-09-18 13:30:21 -0700397static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
398 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600399 fsType->clear();
400 fsUuid->clear();
401 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700402
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700403 std::vector<std::string> cmd;
404 cmd.push_back(kBlkidPath);
405 cmd.push_back("-c");
406 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700407 cmd.push_back("-s");
408 cmd.push_back("TYPE");
409 cmd.push_back("-s");
410 cmd.push_back("UUID");
411 cmd.push_back("-s");
412 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700413 cmd.push_back(path);
414
415 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800416 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700417 if (res != OK) {
418 LOG(WARNING) << "blkid failed to identify " << path;
419 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700420 }
421
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700422 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700423 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600424 FindValue(line, "TYPE", fsType);
425 FindValue(line, "UUID", fsUuid);
426 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700427 }
428
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700429 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700430}
431
Paul Crowley14c8c072018-09-18 13:30:21 -0700432status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
433 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700434 return readMetadata(path, fsType, fsUuid, fsLabel, false);
435}
436
Paul Crowley14c8c072018-09-18 13:30:21 -0700437status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
438 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700439 return readMetadata(path, fsType, fsUuid, fsLabel, true);
440}
441
Paul Crowleyde2d6202018-11-30 11:43:47 -0800442static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
443 std::vector<const char*> argv;
444 argv.reserve(args.size() + 1);
445 for (const auto& arg : args) {
446 if (argv.empty()) {
447 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700448 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800449 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700450 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800451 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700452 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800453 argv.emplace_back(nullptr);
454 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700455}
456
Paul Crowleyde2d6202018-11-30 11:43:47 -0800457static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
458 android::base::unique_fd ufd) {
459 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700460 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800461 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700462 return -errno;
463 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800464 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700465 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800466 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700467 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800468 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700469 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800470 return OK;
471}
472
473status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
474 security_context_t context) {
475 auto argv = ConvertToArgv(args);
476
Paul Crowleye6d76632018-11-30 11:43:47 -0800477 android::base::unique_fd pipe_read, pipe_write;
478 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
479 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800480 return -errno;
481 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800482
483 pid_t pid = fork();
484 if (pid == 0) {
485 if (context) {
486 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800487 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800488 abort();
489 }
490 }
491 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800492 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
493 PLOG(ERROR) << "dup2 in ForkExecvp";
494 _exit(EXIT_FAILURE);
495 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800496 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800497 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800498 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800499 _exit(EXIT_FAILURE);
500 }
501 if (pid == -1) {
502 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700503 return -errno;
504 }
505
Paul Crowleyde2d6202018-11-30 11:43:47 -0800506 pipe_write.reset();
507 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
508 if (st != 0) return st;
509
510 int status;
511 if (waitpid(pid, &status, 0) == -1) {
512 PLOG(ERROR) << "waitpid in ForkExecvp";
513 return -errno;
514 }
515 if (!WIFEXITED(status)) {
516 LOG(ERROR) << "Process did not exit normally, status: " << status;
517 return -ECHILD;
518 }
519 if (WEXITSTATUS(status)) {
520 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
521 return WEXITSTATUS(status);
522 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700523 return OK;
524}
525
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700526pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800527 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700528
529 pid_t pid = fork();
530 if (pid == 0) {
531 close(STDIN_FILENO);
532 close(STDOUT_FILENO);
533 close(STDERR_FILENO);
534
Paul Crowleyde2d6202018-11-30 11:43:47 -0800535 execvp(argv[0], const_cast<char**>(argv.data()));
536 PLOG(ERROR) << "exec in ForkExecvpAsync";
537 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700538 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700539 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800540 PLOG(ERROR) << "fork in ForkExecvpAsync";
541 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700542 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700543 return pid;
544}
545
Jeff Sharkey9c484982015-03-31 10:35:33 -0700546status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100547 out.resize(bytes);
548 return ReadRandomBytes(bytes, &out[0]);
549}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700550
Pavel Grafove2e2d302017-08-01 17:15:53 +0100551status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700552 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
553 if (fd == -1) {
554 return -errno;
555 }
556
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800557 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100558 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700559 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100560 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700561 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700562 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700563
564 if (bytes == 0) {
565 return OK;
566 } else {
567 return -EIO;
568 }
569}
570
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600571status_t GenerateRandomUuid(std::string& out) {
572 status_t res = ReadRandomBytes(16, out);
573 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700574 out[6] &= 0x0f; /* clear version */
575 out[6] |= 0x40; /* set to version 4 */
576 out[8] &= 0x3f; /* clear variant */
577 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600578 }
579 return res;
580}
581
Jeff Sharkey9c484982015-03-31 10:35:33 -0700582status_t HexToStr(const std::string& hex, std::string& str) {
583 str.clear();
584 bool even = true;
585 char cur = 0;
586 for (size_t i = 0; i < hex.size(); i++) {
587 int val = 0;
588 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700589 // clang-format off
590 case ' ': case '-': case ':': continue;
591 case 'f': case 'F': val = 15; break;
592 case 'e': case 'E': val = 14; break;
593 case 'd': case 'D': val = 13; break;
594 case 'c': case 'C': val = 12; break;
595 case 'b': case 'B': val = 11; break;
596 case 'a': case 'A': val = 10; break;
597 case '9': val = 9; break;
598 case '8': val = 8; break;
599 case '7': val = 7; break;
600 case '6': val = 6; break;
601 case '5': val = 5; break;
602 case '4': val = 4; break;
603 case '3': val = 3; break;
604 case '2': val = 2; break;
605 case '1': val = 1; break;
606 case '0': val = 0; break;
607 default: return -EINVAL;
608 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700609 }
610
611 if (even) {
612 cur = val << 4;
613 } else {
614 cur += val;
615 str.push_back(cur);
616 cur = 0;
617 }
618 even = !even;
619 }
620 return even ? OK : -EINVAL;
621}
622
623static const char* kLookup = "0123456789abcdef";
624
625status_t StrToHex(const std::string& str, std::string& hex) {
626 hex.clear();
627 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700628 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700629 hex.push_back(kLookup[str[i] & 0x0F]);
630 }
631 return OK;
632}
633
Pavel Grafove2e2d302017-08-01 17:15:53 +0100634status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
635 hex.clear();
636 for (size_t i = 0; i < str.size(); i++) {
637 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
638 hex.push_back(kLookup[str.data()[i] & 0x0F]);
639 }
640 return OK;
641}
642
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700643status_t NormalizeHex(const std::string& in, std::string& out) {
644 std::string tmp;
645 if (HexToStr(in, tmp)) {
646 return -EINVAL;
647 }
648 return StrToHex(tmp, out);
649}
650
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200651status_t GetBlockDevSize(int fd, uint64_t* size) {
652 if (ioctl(fd, BLKGETSIZE64, size)) {
653 return -errno;
654 }
655
656 return OK;
657}
658
659status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
660 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
661 status_t res = OK;
662
663 if (fd < 0) {
664 return -errno;
665 }
666
667 res = GetBlockDevSize(fd, size);
668
669 close(fd);
670
671 return res;
672}
673
674status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
675 uint64_t size;
676 status_t res = GetBlockDevSize(path, &size);
677
678 if (res != OK) {
679 return res;
680 }
681
682 *nr_sec = size / 512;
683
684 return OK;
685}
686
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700687uint64_t GetFreeBytes(const std::string& path) {
688 struct statvfs sb;
689 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700690 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700691 } else {
692 return -1;
693 }
694}
695
696// TODO: borrowed from frameworks/native/libs/diskusage/ which should
697// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700698static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700699 int64_t blksize = s->st_blksize;
700 // count actual blocks used instead of nominal file size
701 int64_t size = s->st_blocks * 512;
702
703 if (blksize) {
704 /* round up to filesystem block size */
705 size = (size + blksize - 1) & (~(blksize - 1));
706 }
707
708 return size;
709}
710
711// TODO: borrowed from frameworks/native/libs/diskusage/ which should
712// eventually be migrated into system/
713int64_t calculate_dir_size(int dfd) {
714 int64_t size = 0;
715 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700716 DIR* d;
717 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700718
719 d = fdopendir(dfd);
720 if (d == NULL) {
721 close(dfd);
722 return 0;
723 }
724
725 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700726 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700727 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
728 size += stat_size(&s);
729 }
730 if (de->d_type == DT_DIR) {
731 int subfd;
732
733 /* always skip "." and ".." */
734 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700735 if (name[1] == 0) continue;
736 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700737 }
738
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600739 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700740 if (subfd >= 0) {
741 size += calculate_dir_size(subfd);
742 }
743 }
744 }
745 closedir(d);
746 return size;
747}
748
749uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600750 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700751 if (dirfd < 0) {
752 PLOG(WARNING) << "Failed to open " << path;
753 return -1;
754 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700755 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700756 }
757}
758
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700759bool IsFilesystemSupported(const std::string& fsType) {
760 std::string supported;
761 if (!ReadFileToString(kProcFilesystems, &supported)) {
762 PLOG(ERROR) << "Failed to read supported filesystems";
763 return false;
764 }
765 return supported.find(fsType + "\n") != std::string::npos;
766}
767
768status_t WipeBlockDevice(const std::string& path) {
769 status_t res = -1;
770 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200771 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700772
773 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
774 if (fd == -1) {
775 PLOG(ERROR) << "Failed to open " << path;
776 goto done;
777 }
778
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200779 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700780 PLOG(ERROR) << "Failed to determine size of " << path;
781 goto done;
782 }
783
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700784 LOG(INFO) << "About to discard " << range[1] << " on " << path;
785 if (ioctl(fd, BLKDISCARD, &range) == 0) {
786 LOG(INFO) << "Discard success on " << path;
787 res = 0;
788 } else {
789 PLOG(ERROR) << "Discard failure on " << path;
790 }
791
792done:
793 close(fd);
794 return res;
795}
796
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800797static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700798 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800799 return false;
800 } else {
801 return true;
802 }
803}
804
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700805std::string BuildKeyPath(const std::string& partGuid) {
806 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
807}
808
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600809std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700810 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600811}
812
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800813std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700814 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700815}
816
817std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700818 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700819}
820
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600821std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700822 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600823}
824
Jeff Sharkey47695b22016-02-01 17:02:29 -0700825std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700826 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700827}
828
829std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700830 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800831}
832
Calin Juravle79f55a42016-02-17 20:14:46 +0000833// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
834std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700835 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000836}
837
Andreas Huber71cd43f2018-01-22 11:25:29 -0800838std::string BuildDataVendorCePath(userid_t userId) {
839 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
840}
841
842std::string BuildDataVendorDePath(userid_t userId) {
843 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
844}
845
Paul Crowley3b71fc52017-10-09 10:55:21 -0700846std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800847 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700848 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800849 return "/data";
850 } else {
851 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700852 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800853 }
854}
855
Paul Crowley3b71fc52017-10-09 10:55:21 -0700856std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700857 // TODO: unify with installd path generation logic
858 std::string data(BuildDataPath(volumeUuid));
859 return StringPrintf("%s/media/%u", data.c_str(), userId);
860}
861
Paul Crowley3b71fc52017-10-09 10:55:21 -0700862std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800863 // TODO: unify with installd path generation logic
864 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700865 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800866 std::string legacy = StringPrintf("%s/data", data.c_str());
867 struct stat sb;
868 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
869 /* /data/data is dir, return /data/data for legacy system */
870 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800871 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800872 }
cjbaoeb501142017-04-12 00:09:00 +0800873 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800874}
875
Paul Crowley3b71fc52017-10-09 10:55:21 -0700876std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800877 // TODO: unify with installd path generation logic
878 std::string data(BuildDataPath(volumeUuid));
879 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
880}
881
Jeff Sharkey66270a22015-06-24 11:49:24 -0700882dev_t GetDevice(const std::string& path) {
883 struct stat sb;
884 if (stat(path.c_str(), &sb)) {
885 PLOG(WARNING) << "Failed to stat " << path;
886 return 0;
887 } else {
888 return sb.st_dev;
889 }
890}
891
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600892status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700893 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600894
Tom Cherryd6127ef2017-06-15 17:13:56 -0700895 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600896
Tom Cherryd6127ef2017-06-15 17:13:56 -0700897 android::base::SetProperty(kRestoreconString, "");
898 android::base::SetProperty(kRestoreconString, path);
899
900 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600901
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700902 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600903 return OK;
904}
905
Jeff Sharkey3472e522017-10-06 18:02:53 -0600906bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
907 // Shamelessly borrowed from android::base::Readlink()
908 result->clear();
909
910 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
911 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
912 // waste memory to just start there. We add 1 so that we can recognize
913 // whether it actually fit (rather than being truncated to 4095).
914 std::vector<char> buf(4095 + 1);
915 while (true) {
916 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
917 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700918 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600919 // It fit! (If size == buf.size(), it may have been truncated.)
920 if (static_cast<size_t>(size) < buf.size()) {
921 result->assign(&buf[0], size);
922 return true;
923 }
924 // Double our buffer and try again.
925 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900926 }
927}
928
Yu Ning942d4e82016-01-08 17:36:47 +0800929bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700930 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800931}
932
Sudheer Shanka295fb242019-01-16 23:04:07 -0800933static status_t findMountPointsWithPrefix(const std::string& prefix,
934 std::list<std::string>& mountPoints) {
935 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
936 // when the prefix is /foo/bar
937 std::string prefixWithSlash(prefix);
938 if (prefix.back() != '/') {
939 android::base::StringAppendF(&prefixWithSlash, "/");
940 }
941
942 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
943 if (!mnts) {
944 PLOG(ERROR) << "Unable to open /proc/mounts";
945 return -errno;
946 }
947
948 // Some volumes can be stacked on each other, so force unmount in
949 // reverse order to give us the best chance of success.
950 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
951 while ((mnt = getmntent(mnts.get())) != nullptr) {
952 auto mountPoint = std::string(mnt->mnt_dir) + "/";
953 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
954 mountPoints.push_front(mountPoint);
955 }
956 }
957 return OK;
958}
959
960// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
961status_t UnmountTreeWithPrefix(const std::string& prefix) {
962 std::list<std::string> toUnmount;
963 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
964 if (result < 0) {
965 return result;
966 }
967 for (const auto& path : toUnmount) {
968 if (umount2(path.c_str(), MNT_DETACH)) {
969 PLOG(ERROR) << "Failed to unmount " << path;
970 result = -errno;
971 }
972 }
973 return result;
974}
975
976status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800977 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
978 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800979 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700980 return -errno;
981 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700982 return OK;
983}
984
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700985static status_t delete_dir_contents(DIR* dir) {
986 // Shamelessly borrowed from android::installd
987 int dfd = dirfd(dir);
988 if (dfd < 0) {
989 return -errno;
990 }
991
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800992 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700993 struct dirent* de;
994 while ((de = readdir(dir))) {
995 const char* name = de->d_name;
996 if (de->d_type == DT_DIR) {
997 /* always skip "." and ".." */
998 if (name[0] == '.') {
999 if (name[1] == 0) continue;
1000 if ((name[1] == '.') && (name[2] == 0)) continue;
1001 }
1002
1003 android::base::unique_fd subfd(
1004 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1005 if (subfd.get() == -1) {
1006 PLOG(ERROR) << "Couldn't openat " << name;
1007 result = -errno;
1008 continue;
1009 }
Josh Gaoe3c32e02018-11-05 13:47:28 -08001010 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1011 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001012 if (!subdirp) {
1013 PLOG(ERROR) << "Couldn't fdopendir " << name;
1014 result = -errno;
1015 continue;
1016 }
1017 result = delete_dir_contents(subdirp.get());
1018 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1019 PLOG(ERROR) << "Couldn't unlinkat " << name;
1020 result = -errno;
1021 }
1022 } else {
1023 if (unlinkat(dfd, name, 0) < 0) {
1024 PLOG(ERROR) << "Couldn't unlinkat " << name;
1025 result = -errno;
1026 }
1027 }
1028 }
1029 return result;
1030}
1031
1032status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001033 status_t res = DeleteDirContents(pathname);
1034 if (res < 0) {
1035 return res;
1036 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -08001037 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001038 PLOG(ERROR) << "rmdir failed on " << pathname;
1039 return -errno;
1040 }
1041 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1042 return OK;
1043}
1044
1045status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001046 // Shamelessly borrowed from android::installd
1047 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1048 if (!dirp) {
1049 if (errno == ENOENT) {
1050 return OK;
1051 }
1052 PLOG(ERROR) << "Failed to opendir " << pathname;
1053 return -errno;
1054 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001055 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001056}
1057
Paul Crowley298fa322018-10-30 15:59:24 -07001058// TODO(118708649): fix duplication with init/util.h
1059status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1060 android::base::Timer t;
1061 while (t.duration() < timeout) {
1062 struct stat sb;
1063 if (stat(filename, &sb) != -1) {
1064 LOG(INFO) << "wait for '" << filename << "' took " << t;
1065 return 0;
1066 }
1067 std::this_thread::sleep_for(10ms);
1068 }
1069 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1070 return -1;
1071}
1072
Paul Crowley621d9b92018-12-07 15:36:09 -08001073bool FsyncDirectory(const std::string& dirname) {
1074 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1075 if (fd == -1) {
1076 PLOG(ERROR) << "Failed to open " << dirname;
1077 return false;
1078 }
1079 if (fsync(fd) == -1) {
1080 if (errno == EROFS || errno == EINVAL) {
1081 PLOG(WARNING) << "Skip fsync " << dirname
1082 << " on a file system does not support synchronization";
1083 } else {
1084 PLOG(ERROR) << "Failed to fsync " << dirname;
1085 return false;
1086 }
1087 }
1088 return true;
1089}
1090
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001091bool writeStringToFile(const std::string& payload, const std::string& filename) {
1092 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1093 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1094 if (fd == -1) {
1095 PLOG(ERROR) << "Failed to open " << filename;
1096 return false;
1097 }
1098 if (!android::base::WriteStringToFd(payload, fd)) {
1099 PLOG(ERROR) << "Failed to write to " << filename;
1100 unlink(filename.c_str());
1101 return false;
1102 }
1103 // fsync as close won't guarantee flush data
1104 // see close(2), fsync(2) and b/68901441
1105 if (fsync(fd) == -1) {
1106 if (errno == EROFS || errno == EINVAL) {
1107 PLOG(WARNING) << "Skip fsync " << filename
1108 << " on a file system does not support synchronization";
1109 } else {
1110 PLOG(ERROR) << "Failed to fsync " << filename;
1111 unlink(filename.c_str());
1112 return false;
1113 }
1114 }
1115 return true;
1116}
1117
Zima438b242019-09-25 14:37:38 +01001118status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1119 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1120 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1121 std::string fuse_path(
1122 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1123
1124 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1125 std::string pass_through_path(
1126 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001127
Zim1242be82020-01-22 18:22:29 +00001128 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1129 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001130 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001131 if (result != android::OK) {
1132 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1133 return -1;
1134 }
1135
Zim06b0caf2020-01-05 02:11:47 +00001136 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1137 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1138 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1139 // These bits should be consistent with what is set in zygote in
1140 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001141 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001142 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001143 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001144 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001145 return -1;
1146 }
1147
Zima438b242019-09-25 14:37:38 +01001148 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1149 if (result != android::OK) {
1150 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1151 return -1;
1152 }
1153
Zim26eec702020-01-31 16:00:58 +00001154 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001155 if (result != android::OK) {
1156 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1157 return -1;
1158 }
1159
Zim26eec702020-01-31 16:00:58 +00001160 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
Zima438b242019-09-25 14:37:38 +01001161 if (result != android::OK) {
1162 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1163 return -1;
1164 }
1165
1166 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001167 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1168 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001169 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001170 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001171 return -1;
1172 }
Zime5393d42019-11-15 11:44:12 +00001173 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001174 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001175
1176 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
Zim26eec702020-01-31 16:00:58 +00001177 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
Zimaea12472020-01-08 11:09:47 +00001178 if (result != android::OK) {
1179 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1180 return -1;
1181 }
1182 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001183 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001184 }
1185
Nandana Dutta914cc72019-08-29 15:22:42 +01001186 // Open fuse fd.
1187 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1188 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001189 PLOG(ERROR) << "Failed to open /dev/fuse";
1190 return -1;
1191 }
1192
1193 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1194 // permission checks before routing to FUSE daemon.
1195 const auto opts = StringPrintf(
1196 "fd=%i,"
1197 "rootmode=40000,"
1198 "allow_other,"
1199 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001200 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001201
Zima438b242019-09-25 14:37:38 +01001202 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1203 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1204 opts.c_str()));
1205 if (result != 0) {
1206 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001207 return -errno;
1208 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001209
Martijn Coenen86f21a22020-01-06 09:48:14 +01001210 if (IsFilesystemSupported("sdcardfs")) {
1211 std::string sdcardfs_path(
1212 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1213
1214 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1215 return BindMount(sdcardfs_path, pass_through_path);
1216 } else {
1217 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1218 return BindMount(absolute_lower_path, pass_through_path);
1219 }
Zima438b242019-09-25 14:37:38 +01001220}
1221
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001222status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1223 const std::string& relative_upper_path) {
1224 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1225 std::string pass_through_path(
1226 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1227
Zima438b242019-09-25 14:37:38 +01001228 // Best effort unmount pass_through path
1229 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001230 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1231 auto status = ForceUnmount(pass_through_path);
1232 if (status != android::OK) {
1233 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1234 }
Martijn Coenen57002612019-11-28 11:56:13 +01001235 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001236
1237 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001238 android::status_t result = ForceUnmount(fuse_path);
1239 sSleepOnUnmount = true;
1240 if (result != android::OK) {
1241 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1242 // Figure out why we get EBUSY and remove this special casing if possible.
1243 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1244 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1245 errno != ENOENT) {
1246 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1247 return -errno;
1248 }
Martijn Coenen57002612019-11-28 11:56:13 +01001249 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001250 }
Martijn Coenen57002612019-11-28 11:56:13 +01001251 rmdir(fuse_path.c_str());
1252
Zima438b242019-09-25 14:37:38 +01001253 return result;
Zim3623a212019-07-19 16:46:53 +01001254}
1255
Martijn Coenen62a4b272020-01-31 15:23:09 +01001256status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1257 std::string androidDir = volumeRoot + kAndroidDir;
1258 std::string androidDataDir = volumeRoot + kAppDataDir;
1259 std::string androidObbDir = volumeRoot + kAppObbDir;
Zima13d81b2020-02-07 16:39:31 +00001260 std::string androidMediaDir = volumeRoot + kAppMediaDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +01001261
1262 bool useSdcardFs = IsFilesystemSupported("sdcardfs");
1263
1264 if (fs_prepare_dir(androidDir.c_str(), 0771, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1265 PLOG(ERROR) << "Failed to create " << androidDir;
1266 return -errno;
1267 }
1268
1269 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
1270 if (fs_prepare_dir(androidDataDir.c_str(), 0771, AID_MEDIA_RW, dataGid) != 0) {
1271 PLOG(ERROR) << "Failed to create " << androidDataDir;
1272 return -errno;
1273 }
1274
1275 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
1276 if (fs_prepare_dir(androidObbDir.c_str(), 0771, AID_MEDIA_RW, obbGid) != 0) {
1277 PLOG(ERROR) << "Failed to create " << androidObbDir;
1278 return -errno;
1279 }
1280
Zima13d81b2020-02-07 16:39:31 +00001281 if (fs_prepare_dir(androidMediaDir.c_str(), 0771, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1282 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1283 return -errno;
1284 }
1285
Martijn Coenen62a4b272020-01-31 15:23:09 +01001286 return OK;
1287}
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001288} // namespace vold
1289} // namespace android