blob: 4720645d015af8cbfc58f8eb3ee7f2eb381a55e1 [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>
Paul Crowley298fa322018-10-30 15:59:24 -070050#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080051
52#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070053#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080054#endif
55
Paul Crowley298fa322018-10-30 15:59:24 -070056using namespace std::chrono_literals;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070057using android::base::ReadFileToString;
Martijn Coenen13ff6682019-12-24 12:57:16 +010058using android::base::StartsWith;
Jeff Sharkey9c484982015-03-31 10:35:33 -070059using android::base::StringPrintf;
60
Jeff Sharkeydeb24052015-03-02 21:01:40 -080061namespace android {
62namespace vold {
63
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070064security_context_t sBlkidContext = nullptr;
65security_context_t sBlkidUntrustedContext = nullptr;
66security_context_t sFsckContext = nullptr;
67security_context_t sFsckUntrustedContext = nullptr;
68
Paul Crowley56292ef2017-10-20 08:07:53 -070069bool sSleepOnUnmount = true;
70
Jeff Sharkey9c484982015-03-31 10:35:33 -070071static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070072static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070073
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070074static const char* kProcFilesystems = "/proc/filesystems";
75
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060076// Lock used to protect process-level SELinux changes from racing with each
77// other between multiple threads.
78static std::mutex kSecurityLock;
79
Jeff Sharkeydeb24052015-03-02 21:01:40 -080080status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060081 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080082 const char* cpath = path.c_str();
83 status_t res = 0;
84
85 char* secontext = nullptr;
86 if (sehandle) {
87 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
88 setfscreatecon(secontext);
89 }
90 }
91
92 mode_t mode = 0660 | S_IFBLK;
93 if (mknod(cpath, mode, dev) < 0) {
94 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070095 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
96 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080097 res = -errno;
98 }
99 }
100
101 if (secontext) {
102 setfscreatecon(nullptr);
103 freecon(secontext);
104 }
105
106 return res;
107}
108
109status_t DestroyDeviceNode(const std::string& path) {
110 const char* cpath = path.c_str();
111 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
112 return -errno;
113 } else {
114 return OK;
115 }
116}
117
Martijn Coenenfb42bc42020-01-16 01:25:27 +0100118int SetQuotaProjectId(std::string path, long projectId) {
119 struct fsxattr fsx;
120
121 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
122 if (fd == -1) {
123 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
124 return -1;
125 }
126
127 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
128 if (ret == -1) {
129 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
130 return ret;
131 }
132
133 fsx.fsx_projid = projectId;
134 return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
135}
136
Martijn Coenen13ff6682019-12-24 12:57:16 +0100137int PrepareDirsFromRoot(std::string path, std::string root, mode_t mode, uid_t uid, gid_t gid) {
138 int ret = 0;
139 if (!StartsWith(path, root)) {
140 return -1;
141 }
142 std::string to_create_from_root = path.substr(root.length());
143
144 size_t pos = 0;
145 while ((pos = to_create_from_root.find('/')) != std::string::npos) {
146 auto component = to_create_from_root.substr(0, pos);
147 to_create_from_root.erase(0, pos + 1);
148 root = root + component + "/";
149 ret = fs_prepare_dir(root.c_str(), mode, uid, gid);
150 if (ret) {
151 break;
152 }
153 }
154
155 return ret;
156}
157
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700158status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600159 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700160 const char* cpath = path.c_str();
161
162 char* secontext = nullptr;
163 if (sehandle) {
164 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
165 setfscreatecon(secontext);
166 }
167 }
168
169 int res = fs_prepare_dir(cpath, mode, uid, gid);
170
171 if (secontext) {
172 setfscreatecon(nullptr);
173 freecon(secontext);
174 }
175
176 if (res == 0) {
177 return OK;
178 } else {
179 return -errno;
180 }
181}
182
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800183status_t ForceUnmount(const std::string& path) {
184 const char* cpath = path.c_str();
185 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
186 return OK;
187 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700188 // Apps might still be handling eject request, so wait before
189 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700190 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700191
Jeff Sharkey3472e522017-10-06 18:02:53 -0600192 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700193 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700194 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
195 return OK;
196 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700197
Jeff Sharkey3472e522017-10-06 18:02:53 -0600198 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700199 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800200 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
201 return OK;
202 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700203
Jeff Sharkey3472e522017-10-06 18:02:53 -0600204 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700205 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700206 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
207 return OK;
208 }
Zim3623a212019-07-19 16:46:53 +0100209 PLOG(INFO) << "ForceUnmount failed";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800210 return -errno;
211}
212
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700213status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600214 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700215 return OK;
216 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700217 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700218
Jeff Sharkey3472e522017-10-06 18:02:53 -0600219 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700220 return OK;
221 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700222 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700223
Jeff Sharkey3472e522017-10-06 18:02:53 -0600224 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700225 return OK;
226 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700227 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700228
229 // Send SIGKILL a second time to determine if we've
230 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600231 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700232 return OK;
233 }
234 PLOG(ERROR) << "Failed to kill processes using " << path;
235 return -EBUSY;
236}
237
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700238status_t BindMount(const std::string& source, const std::string& target) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800239 if (UnmountTree(target) < 0) {
240 return -errno;
241 }
242 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700243 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
244 return -errno;
245 }
246 return OK;
247}
248
Sudheer Shanka023b5392019-02-06 12:39:19 -0800249status_t Symlink(const std::string& target, const std::string& linkpath) {
250 if (Unlink(linkpath) < 0) {
251 return -errno;
252 }
253 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
254 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
255 return -errno;
256 }
257 return OK;
258}
259
260status_t Unlink(const std::string& linkpath) {
261 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
262 PLOG(ERROR) << "Failed to unlink " << linkpath;
263 return -errno;
264 }
265 return OK;
266}
267
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000268status_t CreateDir(const std::string& dir, mode_t mode) {
269 struct stat sb;
270 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
271 if (S_ISDIR(sb.st_mode)) {
272 return OK;
273 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
274 PLOG(ERROR) << "Failed to unlink " << dir;
275 return -errno;
276 }
277 } else if (errno != ENOENT) {
278 PLOG(ERROR) << "Failed to stat " << dir;
279 return -errno;
280 }
Sudheer Shanka6d285ce2019-02-19 14:12:20 -0800281 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000282 PLOG(ERROR) << "Failed to mkdir " << dir;
283 return -errno;
284 }
285 return OK;
286}
287
Jeff Sharkey3472e522017-10-06 18:02:53 -0600288bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
289 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800290 size_t start = 0;
291 while (true) {
292 start = raw.find(qual, start);
293 if (start == std::string::npos) return false;
294 if (start == 0 || raw[start - 1] == ' ') {
295 break;
296 }
297 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600298 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600299 start += qual.length();
300
301 auto end = raw.find("\"", start);
302 if (end == std::string::npos) return false;
303
304 *value = raw.substr(start, end - start);
305 return true;
306}
307
Paul Crowley14c8c072018-09-18 13:30:21 -0700308static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
309 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600310 fsType->clear();
311 fsUuid->clear();
312 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700313
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700314 std::vector<std::string> cmd;
315 cmd.push_back(kBlkidPath);
316 cmd.push_back("-c");
317 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700318 cmd.push_back("-s");
319 cmd.push_back("TYPE");
320 cmd.push_back("-s");
321 cmd.push_back("UUID");
322 cmd.push_back("-s");
323 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700324 cmd.push_back(path);
325
326 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800327 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700328 if (res != OK) {
329 LOG(WARNING) << "blkid failed to identify " << path;
330 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700331 }
332
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700333 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700334 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600335 FindValue(line, "TYPE", fsType);
336 FindValue(line, "UUID", fsUuid);
337 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700338 }
339
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700340 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700341}
342
Paul Crowley14c8c072018-09-18 13:30:21 -0700343status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
344 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700345 return readMetadata(path, fsType, fsUuid, fsLabel, false);
346}
347
Paul Crowley14c8c072018-09-18 13:30:21 -0700348status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
349 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700350 return readMetadata(path, fsType, fsUuid, fsLabel, true);
351}
352
Paul Crowleyde2d6202018-11-30 11:43:47 -0800353static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
354 std::vector<const char*> argv;
355 argv.reserve(args.size() + 1);
356 for (const auto& arg : args) {
357 if (argv.empty()) {
358 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700359 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800360 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700361 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800362 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700363 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800364 argv.emplace_back(nullptr);
365 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700366}
367
Paul Crowleyde2d6202018-11-30 11:43:47 -0800368static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
369 android::base::unique_fd ufd) {
370 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700371 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800372 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700373 return -errno;
374 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800375 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700376 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800377 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700378 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800379 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700380 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800381 return OK;
382}
383
384status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
385 security_context_t context) {
386 auto argv = ConvertToArgv(args);
387
Paul Crowleye6d76632018-11-30 11:43:47 -0800388 android::base::unique_fd pipe_read, pipe_write;
389 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
390 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800391 return -errno;
392 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800393
394 pid_t pid = fork();
395 if (pid == 0) {
396 if (context) {
397 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800398 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800399 abort();
400 }
401 }
402 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800403 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
404 PLOG(ERROR) << "dup2 in ForkExecvp";
405 _exit(EXIT_FAILURE);
406 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800407 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800408 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800409 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800410 _exit(EXIT_FAILURE);
411 }
412 if (pid == -1) {
413 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700414 return -errno;
415 }
416
Paul Crowleyde2d6202018-11-30 11:43:47 -0800417 pipe_write.reset();
418 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
419 if (st != 0) return st;
420
421 int status;
422 if (waitpid(pid, &status, 0) == -1) {
423 PLOG(ERROR) << "waitpid in ForkExecvp";
424 return -errno;
425 }
426 if (!WIFEXITED(status)) {
427 LOG(ERROR) << "Process did not exit normally, status: " << status;
428 return -ECHILD;
429 }
430 if (WEXITSTATUS(status)) {
431 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
432 return WEXITSTATUS(status);
433 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700434 return OK;
435}
436
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700437pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800438 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700439
440 pid_t pid = fork();
441 if (pid == 0) {
442 close(STDIN_FILENO);
443 close(STDOUT_FILENO);
444 close(STDERR_FILENO);
445
Paul Crowleyde2d6202018-11-30 11:43:47 -0800446 execvp(argv[0], const_cast<char**>(argv.data()));
447 PLOG(ERROR) << "exec in ForkExecvpAsync";
448 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700449 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700450 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800451 PLOG(ERROR) << "fork in ForkExecvpAsync";
452 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700453 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700454 return pid;
455}
456
Jeff Sharkey9c484982015-03-31 10:35:33 -0700457status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100458 out.resize(bytes);
459 return ReadRandomBytes(bytes, &out[0]);
460}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700461
Pavel Grafove2e2d302017-08-01 17:15:53 +0100462status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700463 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
464 if (fd == -1) {
465 return -errno;
466 }
467
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800468 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100469 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700470 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100471 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700472 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700473 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700474
475 if (bytes == 0) {
476 return OK;
477 } else {
478 return -EIO;
479 }
480}
481
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600482status_t GenerateRandomUuid(std::string& out) {
483 status_t res = ReadRandomBytes(16, out);
484 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700485 out[6] &= 0x0f; /* clear version */
486 out[6] |= 0x40; /* set to version 4 */
487 out[8] &= 0x3f; /* clear variant */
488 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600489 }
490 return res;
491}
492
Jeff Sharkey9c484982015-03-31 10:35:33 -0700493status_t HexToStr(const std::string& hex, std::string& str) {
494 str.clear();
495 bool even = true;
496 char cur = 0;
497 for (size_t i = 0; i < hex.size(); i++) {
498 int val = 0;
499 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700500 // clang-format off
501 case ' ': case '-': case ':': continue;
502 case 'f': case 'F': val = 15; break;
503 case 'e': case 'E': val = 14; break;
504 case 'd': case 'D': val = 13; break;
505 case 'c': case 'C': val = 12; break;
506 case 'b': case 'B': val = 11; break;
507 case 'a': case 'A': val = 10; break;
508 case '9': val = 9; break;
509 case '8': val = 8; break;
510 case '7': val = 7; break;
511 case '6': val = 6; break;
512 case '5': val = 5; break;
513 case '4': val = 4; break;
514 case '3': val = 3; break;
515 case '2': val = 2; break;
516 case '1': val = 1; break;
517 case '0': val = 0; break;
518 default: return -EINVAL;
519 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700520 }
521
522 if (even) {
523 cur = val << 4;
524 } else {
525 cur += val;
526 str.push_back(cur);
527 cur = 0;
528 }
529 even = !even;
530 }
531 return even ? OK : -EINVAL;
532}
533
534static const char* kLookup = "0123456789abcdef";
535
536status_t StrToHex(const std::string& str, std::string& hex) {
537 hex.clear();
538 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700539 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700540 hex.push_back(kLookup[str[i] & 0x0F]);
541 }
542 return OK;
543}
544
Pavel Grafove2e2d302017-08-01 17:15:53 +0100545status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
546 hex.clear();
547 for (size_t i = 0; i < str.size(); i++) {
548 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
549 hex.push_back(kLookup[str.data()[i] & 0x0F]);
550 }
551 return OK;
552}
553
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700554status_t NormalizeHex(const std::string& in, std::string& out) {
555 std::string tmp;
556 if (HexToStr(in, tmp)) {
557 return -EINVAL;
558 }
559 return StrToHex(tmp, out);
560}
561
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200562status_t GetBlockDevSize(int fd, uint64_t* size) {
563 if (ioctl(fd, BLKGETSIZE64, size)) {
564 return -errno;
565 }
566
567 return OK;
568}
569
570status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
571 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
572 status_t res = OK;
573
574 if (fd < 0) {
575 return -errno;
576 }
577
578 res = GetBlockDevSize(fd, size);
579
580 close(fd);
581
582 return res;
583}
584
585status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
586 uint64_t size;
587 status_t res = GetBlockDevSize(path, &size);
588
589 if (res != OK) {
590 return res;
591 }
592
593 *nr_sec = size / 512;
594
595 return OK;
596}
597
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700598uint64_t GetFreeBytes(const std::string& path) {
599 struct statvfs sb;
600 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700601 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700602 } else {
603 return -1;
604 }
605}
606
607// TODO: borrowed from frameworks/native/libs/diskusage/ which should
608// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700609static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700610 int64_t blksize = s->st_blksize;
611 // count actual blocks used instead of nominal file size
612 int64_t size = s->st_blocks * 512;
613
614 if (blksize) {
615 /* round up to filesystem block size */
616 size = (size + blksize - 1) & (~(blksize - 1));
617 }
618
619 return size;
620}
621
622// TODO: borrowed from frameworks/native/libs/diskusage/ which should
623// eventually be migrated into system/
624int64_t calculate_dir_size(int dfd) {
625 int64_t size = 0;
626 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700627 DIR* d;
628 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700629
630 d = fdopendir(dfd);
631 if (d == NULL) {
632 close(dfd);
633 return 0;
634 }
635
636 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700637 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700638 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
639 size += stat_size(&s);
640 }
641 if (de->d_type == DT_DIR) {
642 int subfd;
643
644 /* always skip "." and ".." */
645 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700646 if (name[1] == 0) continue;
647 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700648 }
649
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600650 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700651 if (subfd >= 0) {
652 size += calculate_dir_size(subfd);
653 }
654 }
655 }
656 closedir(d);
657 return size;
658}
659
660uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600661 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700662 if (dirfd < 0) {
663 PLOG(WARNING) << "Failed to open " << path;
664 return -1;
665 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700666 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700667 }
668}
669
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700670bool IsFilesystemSupported(const std::string& fsType) {
671 std::string supported;
672 if (!ReadFileToString(kProcFilesystems, &supported)) {
673 PLOG(ERROR) << "Failed to read supported filesystems";
674 return false;
675 }
676 return supported.find(fsType + "\n") != std::string::npos;
677}
678
679status_t WipeBlockDevice(const std::string& path) {
680 status_t res = -1;
681 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200682 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700683
684 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
685 if (fd == -1) {
686 PLOG(ERROR) << "Failed to open " << path;
687 goto done;
688 }
689
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200690 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700691 PLOG(ERROR) << "Failed to determine size of " << path;
692 goto done;
693 }
694
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700695 LOG(INFO) << "About to discard " << range[1] << " on " << path;
696 if (ioctl(fd, BLKDISCARD, &range) == 0) {
697 LOG(INFO) << "Discard success on " << path;
698 res = 0;
699 } else {
700 PLOG(ERROR) << "Discard failure on " << path;
701 }
702
703done:
704 close(fd);
705 return res;
706}
707
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800708static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700709 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800710 return false;
711 } else {
712 return true;
713 }
714}
715
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700716std::string BuildKeyPath(const std::string& partGuid) {
717 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
718}
719
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600720std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700721 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600722}
723
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800724std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700725 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700726}
727
728std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700729 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700730}
731
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600732std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700733 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600734}
735
Jeff Sharkey47695b22016-02-01 17:02:29 -0700736std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700737 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700738}
739
740std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700741 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800742}
743
Calin Juravle79f55a42016-02-17 20:14:46 +0000744// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
745std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700746 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000747}
748
Andreas Huber71cd43f2018-01-22 11:25:29 -0800749std::string BuildDataVendorCePath(userid_t userId) {
750 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
751}
752
753std::string BuildDataVendorDePath(userid_t userId) {
754 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
755}
756
Paul Crowley3b71fc52017-10-09 10:55:21 -0700757std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800758 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700759 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800760 return "/data";
761 } else {
762 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700763 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800764 }
765}
766
Paul Crowley3b71fc52017-10-09 10:55:21 -0700767std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700768 // TODO: unify with installd path generation logic
769 std::string data(BuildDataPath(volumeUuid));
770 return StringPrintf("%s/media/%u", data.c_str(), userId);
771}
772
Paul Crowley3b71fc52017-10-09 10:55:21 -0700773std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800774 // TODO: unify with installd path generation logic
775 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700776 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800777 std::string legacy = StringPrintf("%s/data", data.c_str());
778 struct stat sb;
779 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
780 /* /data/data is dir, return /data/data for legacy system */
781 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800782 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800783 }
cjbaoeb501142017-04-12 00:09:00 +0800784 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800785}
786
Paul Crowley3b71fc52017-10-09 10:55:21 -0700787std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800788 // TODO: unify with installd path generation logic
789 std::string data(BuildDataPath(volumeUuid));
790 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
791}
792
Jeff Sharkey66270a22015-06-24 11:49:24 -0700793dev_t GetDevice(const std::string& path) {
794 struct stat sb;
795 if (stat(path.c_str(), &sb)) {
796 PLOG(WARNING) << "Failed to stat " << path;
797 return 0;
798 } else {
799 return sb.st_dev;
800 }
801}
802
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600803status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700804 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600805
Tom Cherryd6127ef2017-06-15 17:13:56 -0700806 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600807
Tom Cherryd6127ef2017-06-15 17:13:56 -0700808 android::base::SetProperty(kRestoreconString, "");
809 android::base::SetProperty(kRestoreconString, path);
810
811 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600812
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700813 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600814 return OK;
815}
816
Jeff Sharkey3472e522017-10-06 18:02:53 -0600817bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
818 // Shamelessly borrowed from android::base::Readlink()
819 result->clear();
820
821 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
822 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
823 // waste memory to just start there. We add 1 so that we can recognize
824 // whether it actually fit (rather than being truncated to 4095).
825 std::vector<char> buf(4095 + 1);
826 while (true) {
827 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
828 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700829 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600830 // It fit! (If size == buf.size(), it may have been truncated.)
831 if (static_cast<size_t>(size) < buf.size()) {
832 result->assign(&buf[0], size);
833 return true;
834 }
835 // Double our buffer and try again.
836 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900837 }
838}
839
Yu Ning942d4e82016-01-08 17:36:47 +0800840bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700841 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800842}
843
Sudheer Shanka295fb242019-01-16 23:04:07 -0800844static status_t findMountPointsWithPrefix(const std::string& prefix,
845 std::list<std::string>& mountPoints) {
846 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
847 // when the prefix is /foo/bar
848 std::string prefixWithSlash(prefix);
849 if (prefix.back() != '/') {
850 android::base::StringAppendF(&prefixWithSlash, "/");
851 }
852
853 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
854 if (!mnts) {
855 PLOG(ERROR) << "Unable to open /proc/mounts";
856 return -errno;
857 }
858
859 // Some volumes can be stacked on each other, so force unmount in
860 // reverse order to give us the best chance of success.
861 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
862 while ((mnt = getmntent(mnts.get())) != nullptr) {
863 auto mountPoint = std::string(mnt->mnt_dir) + "/";
864 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
865 mountPoints.push_front(mountPoint);
866 }
867 }
868 return OK;
869}
870
871// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
872status_t UnmountTreeWithPrefix(const std::string& prefix) {
873 std::list<std::string> toUnmount;
874 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
875 if (result < 0) {
876 return result;
877 }
878 for (const auto& path : toUnmount) {
879 if (umount2(path.c_str(), MNT_DETACH)) {
880 PLOG(ERROR) << "Failed to unmount " << path;
881 result = -errno;
882 }
883 }
884 return result;
885}
886
887status_t UnmountTree(const std::string& mountPoint) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800888 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
889 errno != ENOENT) {
Sudheer Shanka295fb242019-01-16 23:04:07 -0800890 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700891 return -errno;
892 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700893 return OK;
894}
895
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700896static status_t delete_dir_contents(DIR* dir) {
897 // Shamelessly borrowed from android::installd
898 int dfd = dirfd(dir);
899 if (dfd < 0) {
900 return -errno;
901 }
902
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800903 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700904 struct dirent* de;
905 while ((de = readdir(dir))) {
906 const char* name = de->d_name;
907 if (de->d_type == DT_DIR) {
908 /* always skip "." and ".." */
909 if (name[0] == '.') {
910 if (name[1] == 0) continue;
911 if ((name[1] == '.') && (name[2] == 0)) continue;
912 }
913
914 android::base::unique_fd subfd(
915 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
916 if (subfd.get() == -1) {
917 PLOG(ERROR) << "Couldn't openat " << name;
918 result = -errno;
919 continue;
920 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800921 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
922 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700923 if (!subdirp) {
924 PLOG(ERROR) << "Couldn't fdopendir " << name;
925 result = -errno;
926 continue;
927 }
928 result = delete_dir_contents(subdirp.get());
929 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
930 PLOG(ERROR) << "Couldn't unlinkat " << name;
931 result = -errno;
932 }
933 } else {
934 if (unlinkat(dfd, name, 0) < 0) {
935 PLOG(ERROR) << "Couldn't unlinkat " << name;
936 result = -errno;
937 }
938 }
939 }
940 return result;
941}
942
943status_t DeleteDirContentsAndDir(const std::string& pathname) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800944 status_t res = DeleteDirContents(pathname);
945 if (res < 0) {
946 return res;
947 }
Sudheer Shanka8255a2b2019-02-25 12:21:23 -0800948 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800949 PLOG(ERROR) << "rmdir failed on " << pathname;
950 return -errno;
951 }
952 LOG(VERBOSE) << "Success: rmdir on " << pathname;
953 return OK;
954}
955
956status_t DeleteDirContents(const std::string& pathname) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700957 // Shamelessly borrowed from android::installd
958 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
959 if (!dirp) {
960 if (errno == ENOENT) {
961 return OK;
962 }
963 PLOG(ERROR) << "Failed to opendir " << pathname;
964 return -errno;
965 }
Sudheer Shanka30df1c62019-02-22 17:03:02 -0800966 return delete_dir_contents(dirp.get());
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700967}
968
Paul Crowley298fa322018-10-30 15:59:24 -0700969// TODO(118708649): fix duplication with init/util.h
970status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
971 android::base::Timer t;
972 while (t.duration() < timeout) {
973 struct stat sb;
974 if (stat(filename, &sb) != -1) {
975 LOG(INFO) << "wait for '" << filename << "' took " << t;
976 return 0;
977 }
978 std::this_thread::sleep_for(10ms);
979 }
980 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
981 return -1;
982}
983
Paul Crowley621d9b92018-12-07 15:36:09 -0800984bool FsyncDirectory(const std::string& dirname) {
985 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
986 if (fd == -1) {
987 PLOG(ERROR) << "Failed to open " << dirname;
988 return false;
989 }
990 if (fsync(fd) == -1) {
991 if (errno == EROFS || errno == EINVAL) {
992 PLOG(WARNING) << "Skip fsync " << dirname
993 << " on a file system does not support synchronization";
994 } else {
995 PLOG(ERROR) << "Failed to fsync " << dirname;
996 return false;
997 }
998 }
999 return true;
1000}
1001
Tommy Chiu0bd2d112019-03-26 17:18:09 +08001002bool writeStringToFile(const std::string& payload, const std::string& filename) {
1003 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1004 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1005 if (fd == -1) {
1006 PLOG(ERROR) << "Failed to open " << filename;
1007 return false;
1008 }
1009 if (!android::base::WriteStringToFd(payload, fd)) {
1010 PLOG(ERROR) << "Failed to write to " << filename;
1011 unlink(filename.c_str());
1012 return false;
1013 }
1014 // fsync as close won't guarantee flush data
1015 // see close(2), fsync(2) and b/68901441
1016 if (fsync(fd) == -1) {
1017 if (errno == EROFS || errno == EINVAL) {
1018 PLOG(WARNING) << "Skip fsync " << filename
1019 << " on a file system does not support synchronization";
1020 } else {
1021 PLOG(ERROR) << "Failed to fsync " << filename;
1022 unlink(filename.c_str());
1023 return false;
1024 }
1025 }
1026 return true;
1027}
1028
Zima438b242019-09-25 14:37:38 +01001029status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1030 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1031 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1032 std::string fuse_path(
1033 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1034
1035 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1036 std::string pass_through_path(
1037 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
Zim3623a212019-07-19 16:46:53 +01001038
Zim1242be82020-01-22 18:22:29 +00001039 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1040 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
Zim4dd47092020-01-29 02:44:46 +00001041 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
Zim1242be82020-01-22 18:22:29 +00001042 if (result != android::OK) {
1043 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1044 return -1;
1045 }
1046
Zim06b0caf2020-01-05 02:11:47 +00001047 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1048 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1049 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1050 // These bits should be consistent with what is set in zygote in
1051 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
Zim1242be82020-01-22 18:22:29 +00001052 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
Zim06b0caf2020-01-05 02:11:47 +00001053 multiuser_get_uid(user_id, AID_EVERYBODY));
Zim3623a212019-07-19 16:46:53 +01001054 if (result != android::OK) {
Zima438b242019-09-25 14:37:38 +01001055 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
Zim3623a212019-07-19 16:46:53 +01001056 return -1;
1057 }
1058
Zima438b242019-09-25 14:37:38 +01001059 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1060 if (result != android::OK) {
1061 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1062 return -1;
1063 }
1064
1065 result = PrepareDir(pre_pass_through_path, 0755, AID_ROOT, AID_ROOT);
1066 if (result != android::OK) {
1067 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1068 return -1;
1069 }
1070
1071 result = PrepareDir(pass_through_path, 0755, AID_ROOT, AID_ROOT);
1072 if (result != android::OK) {
1073 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1074 return -1;
1075 }
1076
1077 if (relative_upper_path == "emulated") {
Zime5393d42019-11-15 11:44:12 +00001078 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1079 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
Zima438b242019-09-25 14:37:38 +01001080 if (result != android::OK) {
Zime5393d42019-11-15 11:44:12 +00001081 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
Zima438b242019-09-25 14:37:38 +01001082 return -1;
1083 }
Zime5393d42019-11-15 11:44:12 +00001084 linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001085 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
Zimaea12472020-01-08 11:09:47 +00001086
1087 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
1088 result = PrepareDir(pass_through_linkpath, 0755, AID_ROOT, AID_ROOT);
1089 if (result != android::OK) {
1090 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1091 return -1;
1092 }
1093 pass_through_linkpath += "/primary";
Zim53d16d32020-01-17 01:21:24 +00001094 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
Zima438b242019-09-25 14:37:38 +01001095 }
1096
Nandana Dutta914cc72019-08-29 15:22:42 +01001097 // Open fuse fd.
1098 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1099 if (fuse_fd->get() == -1) {
Zim3623a212019-07-19 16:46:53 +01001100 PLOG(ERROR) << "Failed to open /dev/fuse";
1101 return -1;
1102 }
1103
1104 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1105 // permission checks before routing to FUSE daemon.
1106 const auto opts = StringPrintf(
1107 "fd=%i,"
1108 "rootmode=40000,"
1109 "allow_other,"
1110 "user_id=0,group_id=0,",
Nandana Dutta914cc72019-08-29 15:22:42 +01001111 fuse_fd->get());
Zim3623a212019-07-19 16:46:53 +01001112
Zima438b242019-09-25 14:37:38 +01001113 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1114 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1115 opts.c_str()));
1116 if (result != 0) {
1117 PLOG(ERROR) << "Failed to mount " << fuse_path;
Zim3623a212019-07-19 16:46:53 +01001118 return -errno;
1119 }
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001120
Martijn Coenen86f21a22020-01-06 09:48:14 +01001121 if (IsFilesystemSupported("sdcardfs")) {
1122 std::string sdcardfs_path(
1123 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1124
1125 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1126 return BindMount(sdcardfs_path, pass_through_path);
1127 } else {
1128 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1129 return BindMount(absolute_lower_path, pass_through_path);
1130 }
Zima438b242019-09-25 14:37:38 +01001131}
1132
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001133status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1134 const std::string& relative_upper_path) {
1135 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1136 std::string pass_through_path(
1137 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1138
Zima438b242019-09-25 14:37:38 +01001139 // Best effort unmount pass_through path
1140 sSleepOnUnmount = false;
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001141 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1142 auto status = ForceUnmount(pass_through_path);
1143 if (status != android::OK) {
1144 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1145 }
Martijn Coenen57002612019-11-28 11:56:13 +01001146 rmdir(pass_through_path.c_str());
Martijn Coenen6f5802e2019-11-28 11:53:53 +01001147
1148 LOG(INFO) << "Unmounting fuse path " << fuse_path;
Zima438b242019-09-25 14:37:38 +01001149 android::status_t result = ForceUnmount(fuse_path);
1150 sSleepOnUnmount = true;
1151 if (result != android::OK) {
1152 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1153 // Figure out why we get EBUSY and remove this special casing if possible.
1154 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1155 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1156 errno != ENOENT) {
1157 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1158 return -errno;
1159 }
Martijn Coenen57002612019-11-28 11:56:13 +01001160 result = android::OK;
Zima438b242019-09-25 14:37:38 +01001161 }
Martijn Coenen57002612019-11-28 11:56:13 +01001162 rmdir(fuse_path.c_str());
1163
Zima438b242019-09-25 14:37:38 +01001164 return result;
Zim3623a212019-07-19 16:46:53 +01001165}
1166
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001167} // namespace vold
1168} // namespace android