blob: 92f25d949b2de21e6345bf9d7ad41c87a69521f9 [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>
39#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080040#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070041#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070042#include <sys/sysmacros.h>
43#include <sys/types.h>
44#include <sys/wait.h>
Paul Crowley298fa322018-10-30 15:59:24 -070045
Sudheer Shanka89ddf992018-09-25 14:22:07 -070046#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070047#include <mutex>
Paul Crowley298fa322018-10-30 15:59:24 -070048#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080049
50#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070051#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080052#endif
53
Paul Crowley298fa322018-10-30 15:59:24 -070054using namespace std::chrono_literals;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070055using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070056using android::base::StringPrintf;
57
Jeff Sharkeydeb24052015-03-02 21:01:40 -080058namespace android {
59namespace vold {
60
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070061security_context_t sBlkidContext = nullptr;
62security_context_t sBlkidUntrustedContext = nullptr;
63security_context_t sFsckContext = nullptr;
64security_context_t sFsckUntrustedContext = nullptr;
65
Paul Crowley56292ef2017-10-20 08:07:53 -070066bool sSleepOnUnmount = true;
67
Jeff Sharkey9c484982015-03-31 10:35:33 -070068static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070069static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070070
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070071static const char* kProcFilesystems = "/proc/filesystems";
72
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060073// Lock used to protect process-level SELinux changes from racing with each
74// other between multiple threads.
75static std::mutex kSecurityLock;
76
Jeff Sharkeydeb24052015-03-02 21:01:40 -080077status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060078 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080079 const char* cpath = path.c_str();
80 status_t res = 0;
81
82 char* secontext = nullptr;
83 if (sehandle) {
84 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
85 setfscreatecon(secontext);
86 }
87 }
88
89 mode_t mode = 0660 | S_IFBLK;
90 if (mknod(cpath, mode, dev) < 0) {
91 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070092 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
93 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080094 res = -errno;
95 }
96 }
97
98 if (secontext) {
99 setfscreatecon(nullptr);
100 freecon(secontext);
101 }
102
103 return res;
104}
105
106status_t DestroyDeviceNode(const std::string& path) {
107 const char* cpath = path.c_str();
108 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
109 return -errno;
110 } else {
111 return OK;
112 }
113}
114
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700115status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600116 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700117 const char* cpath = path.c_str();
118
119 char* secontext = nullptr;
120 if (sehandle) {
121 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
122 setfscreatecon(secontext);
123 }
124 }
125
126 int res = fs_prepare_dir(cpath, mode, uid, gid);
127
128 if (secontext) {
129 setfscreatecon(nullptr);
130 freecon(secontext);
131 }
132
133 if (res == 0) {
134 return OK;
135 } else {
136 return -errno;
137 }
138}
139
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800140status_t ForceUnmount(const std::string& path) {
141 const char* cpath = path.c_str();
142 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
143 return OK;
144 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700145 // Apps might still be handling eject request, so wait before
146 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700147 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700148
Jeff Sharkey3472e522017-10-06 18:02:53 -0600149 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700150 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700151 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
152 return OK;
153 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700154
Jeff Sharkey3472e522017-10-06 18:02:53 -0600155 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700156 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800157 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
158 return OK;
159 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700160
Jeff Sharkey3472e522017-10-06 18:02:53 -0600161 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700162 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700163 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
164 return OK;
165 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700166
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800167 return -errno;
168}
169
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700170status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600171 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700172 return OK;
173 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700174 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700175
Jeff Sharkey3472e522017-10-06 18:02:53 -0600176 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700177 return OK;
178 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700179 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700180
Jeff Sharkey3472e522017-10-06 18:02:53 -0600181 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700182 return OK;
183 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700184 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700185
186 // Send SIGKILL a second time to determine if we've
187 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600188 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700189 return OK;
190 }
191 PLOG(ERROR) << "Failed to kill processes using " << path;
192 return -EBUSY;
193}
194
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700195status_t BindMount(const std::string& source, const std::string& target) {
196 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
197 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
198 return -errno;
199 }
200 return OK;
201}
202
Jeff Sharkey3472e522017-10-06 18:02:53 -0600203bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
204 auto qual = key + "=\"";
Paul Crowley95abfa02019-02-05 15:33:34 -0800205 size_t start = 0;
206 while (true) {
207 start = raw.find(qual, start);
208 if (start == std::string::npos) return false;
209 if (start == 0 || raw[start - 1] == ' ') {
210 break;
211 }
212 start += 1;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600213 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600214 start += qual.length();
215
216 auto end = raw.find("\"", start);
217 if (end == std::string::npos) return false;
218
219 *value = raw.substr(start, end - start);
220 return true;
221}
222
Paul Crowley14c8c072018-09-18 13:30:21 -0700223static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
224 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600225 fsType->clear();
226 fsUuid->clear();
227 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700228
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700229 std::vector<std::string> cmd;
230 cmd.push_back(kBlkidPath);
231 cmd.push_back("-c");
232 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700233 cmd.push_back("-s");
234 cmd.push_back("TYPE");
235 cmd.push_back("-s");
236 cmd.push_back("UUID");
237 cmd.push_back("-s");
238 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700239 cmd.push_back(path);
240
241 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800242 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700243 if (res != OK) {
244 LOG(WARNING) << "blkid failed to identify " << path;
245 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700246 }
247
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700248 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700249 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600250 FindValue(line, "TYPE", fsType);
251 FindValue(line, "UUID", fsUuid);
252 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700253 }
254
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700255 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700256}
257
Paul Crowley14c8c072018-09-18 13:30:21 -0700258status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
259 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700260 return readMetadata(path, fsType, fsUuid, fsLabel, false);
261}
262
Paul Crowley14c8c072018-09-18 13:30:21 -0700263status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
264 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700265 return readMetadata(path, fsType, fsUuid, fsLabel, true);
266}
267
Paul Crowleyde2d6202018-11-30 11:43:47 -0800268static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
269 std::vector<const char*> argv;
270 argv.reserve(args.size() + 1);
271 for (const auto& arg : args) {
272 if (argv.empty()) {
273 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700274 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800275 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700276 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800277 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700278 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800279 argv.emplace_back(nullptr);
280 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700281}
282
Paul Crowleyde2d6202018-11-30 11:43:47 -0800283static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
284 android::base::unique_fd ufd) {
285 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700286 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800287 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700288 return -errno;
289 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800290 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700291 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800292 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700293 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800294 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700295 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800296 return OK;
297}
298
299status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
300 security_context_t context) {
301 auto argv = ConvertToArgv(args);
302
Paul Crowleye6d76632018-11-30 11:43:47 -0800303 android::base::unique_fd pipe_read, pipe_write;
304 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
305 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800306 return -errno;
307 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800308
309 pid_t pid = fork();
310 if (pid == 0) {
311 if (context) {
312 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800313 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800314 abort();
315 }
316 }
317 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800318 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
319 PLOG(ERROR) << "dup2 in ForkExecvp";
320 _exit(EXIT_FAILURE);
321 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800322 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800323 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800324 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800325 _exit(EXIT_FAILURE);
326 }
327 if (pid == -1) {
328 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700329 return -errno;
330 }
331
Paul Crowleyde2d6202018-11-30 11:43:47 -0800332 pipe_write.reset();
333 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
334 if (st != 0) return st;
335
336 int status;
337 if (waitpid(pid, &status, 0) == -1) {
338 PLOG(ERROR) << "waitpid in ForkExecvp";
339 return -errno;
340 }
341 if (!WIFEXITED(status)) {
342 LOG(ERROR) << "Process did not exit normally, status: " << status;
343 return -ECHILD;
344 }
345 if (WEXITSTATUS(status)) {
346 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
347 return WEXITSTATUS(status);
348 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700349 return OK;
350}
351
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700352pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800353 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700354
355 pid_t pid = fork();
356 if (pid == 0) {
357 close(STDIN_FILENO);
358 close(STDOUT_FILENO);
359 close(STDERR_FILENO);
360
Paul Crowleyde2d6202018-11-30 11:43:47 -0800361 execvp(argv[0], const_cast<char**>(argv.data()));
362 PLOG(ERROR) << "exec in ForkExecvpAsync";
363 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700364 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700365 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800366 PLOG(ERROR) << "fork in ForkExecvpAsync";
367 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700368 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700369 return pid;
370}
371
Jeff Sharkey9c484982015-03-31 10:35:33 -0700372status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100373 out.resize(bytes);
374 return ReadRandomBytes(bytes, &out[0]);
375}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700376
Pavel Grafove2e2d302017-08-01 17:15:53 +0100377status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700378 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
379 if (fd == -1) {
380 return -errno;
381 }
382
Eric Biggers0ef7bfd2019-01-16 13:05:34 -0800383 ssize_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100384 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700385 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100386 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700387 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700388 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700389
390 if (bytes == 0) {
391 return OK;
392 } else {
393 return -EIO;
394 }
395}
396
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600397status_t GenerateRandomUuid(std::string& out) {
398 status_t res = ReadRandomBytes(16, out);
399 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700400 out[6] &= 0x0f; /* clear version */
401 out[6] |= 0x40; /* set to version 4 */
402 out[8] &= 0x3f; /* clear variant */
403 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600404 }
405 return res;
406}
407
Jeff Sharkey9c484982015-03-31 10:35:33 -0700408status_t HexToStr(const std::string& hex, std::string& str) {
409 str.clear();
410 bool even = true;
411 char cur = 0;
412 for (size_t i = 0; i < hex.size(); i++) {
413 int val = 0;
414 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700415 // clang-format off
416 case ' ': case '-': case ':': continue;
417 case 'f': case 'F': val = 15; break;
418 case 'e': case 'E': val = 14; break;
419 case 'd': case 'D': val = 13; break;
420 case 'c': case 'C': val = 12; break;
421 case 'b': case 'B': val = 11; break;
422 case 'a': case 'A': val = 10; break;
423 case '9': val = 9; break;
424 case '8': val = 8; break;
425 case '7': val = 7; break;
426 case '6': val = 6; break;
427 case '5': val = 5; break;
428 case '4': val = 4; break;
429 case '3': val = 3; break;
430 case '2': val = 2; break;
431 case '1': val = 1; break;
432 case '0': val = 0; break;
433 default: return -EINVAL;
434 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700435 }
436
437 if (even) {
438 cur = val << 4;
439 } else {
440 cur += val;
441 str.push_back(cur);
442 cur = 0;
443 }
444 even = !even;
445 }
446 return even ? OK : -EINVAL;
447}
448
449static const char* kLookup = "0123456789abcdef";
450
451status_t StrToHex(const std::string& str, std::string& hex) {
452 hex.clear();
453 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700454 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700455 hex.push_back(kLookup[str[i] & 0x0F]);
456 }
457 return OK;
458}
459
Pavel Grafove2e2d302017-08-01 17:15:53 +0100460status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
461 hex.clear();
462 for (size_t i = 0; i < str.size(); i++) {
463 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
464 hex.push_back(kLookup[str.data()[i] & 0x0F]);
465 }
466 return OK;
467}
468
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700469status_t NormalizeHex(const std::string& in, std::string& out) {
470 std::string tmp;
471 if (HexToStr(in, tmp)) {
472 return -EINVAL;
473 }
474 return StrToHex(tmp, out);
475}
476
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200477status_t GetBlockDevSize(int fd, uint64_t* size) {
478 if (ioctl(fd, BLKGETSIZE64, size)) {
479 return -errno;
480 }
481
482 return OK;
483}
484
485status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
486 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
487 status_t res = OK;
488
489 if (fd < 0) {
490 return -errno;
491 }
492
493 res = GetBlockDevSize(fd, size);
494
495 close(fd);
496
497 return res;
498}
499
500status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
501 uint64_t size;
502 status_t res = GetBlockDevSize(path, &size);
503
504 if (res != OK) {
505 return res;
506 }
507
508 *nr_sec = size / 512;
509
510 return OK;
511}
512
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700513uint64_t GetFreeBytes(const std::string& path) {
514 struct statvfs sb;
515 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700516 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700517 } else {
518 return -1;
519 }
520}
521
522// TODO: borrowed from frameworks/native/libs/diskusage/ which should
523// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700524static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700525 int64_t blksize = s->st_blksize;
526 // count actual blocks used instead of nominal file size
527 int64_t size = s->st_blocks * 512;
528
529 if (blksize) {
530 /* round up to filesystem block size */
531 size = (size + blksize - 1) & (~(blksize - 1));
532 }
533
534 return size;
535}
536
537// TODO: borrowed from frameworks/native/libs/diskusage/ which should
538// eventually be migrated into system/
539int64_t calculate_dir_size(int dfd) {
540 int64_t size = 0;
541 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700542 DIR* d;
543 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700544
545 d = fdopendir(dfd);
546 if (d == NULL) {
547 close(dfd);
548 return 0;
549 }
550
551 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700552 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700553 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
554 size += stat_size(&s);
555 }
556 if (de->d_type == DT_DIR) {
557 int subfd;
558
559 /* always skip "." and ".." */
560 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700561 if (name[1] == 0) continue;
562 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700563 }
564
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600565 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700566 if (subfd >= 0) {
567 size += calculate_dir_size(subfd);
568 }
569 }
570 }
571 closedir(d);
572 return size;
573}
574
575uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600576 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700577 if (dirfd < 0) {
578 PLOG(WARNING) << "Failed to open " << path;
579 return -1;
580 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700581 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700582 }
583}
584
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700585bool IsFilesystemSupported(const std::string& fsType) {
586 std::string supported;
587 if (!ReadFileToString(kProcFilesystems, &supported)) {
588 PLOG(ERROR) << "Failed to read supported filesystems";
589 return false;
590 }
591 return supported.find(fsType + "\n") != std::string::npos;
592}
593
594status_t WipeBlockDevice(const std::string& path) {
595 status_t res = -1;
596 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200597 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700598
599 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
600 if (fd == -1) {
601 PLOG(ERROR) << "Failed to open " << path;
602 goto done;
603 }
604
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200605 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700606 PLOG(ERROR) << "Failed to determine size of " << path;
607 goto done;
608 }
609
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700610 LOG(INFO) << "About to discard " << range[1] << " on " << path;
611 if (ioctl(fd, BLKDISCARD, &range) == 0) {
612 LOG(INFO) << "Discard success on " << path;
613 res = 0;
614 } else {
615 PLOG(ERROR) << "Discard failure on " << path;
616 }
617
618done:
619 close(fd);
620 return res;
621}
622
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800623static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700624 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800625 return false;
626 } else {
627 return true;
628 }
629}
630
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700631std::string BuildKeyPath(const std::string& partGuid) {
632 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
633}
634
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600635std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700636 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600637}
638
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800639std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700640 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700641}
642
643std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700644 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700645}
646
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600647std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700648 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600649}
650
Jeff Sharkey47695b22016-02-01 17:02:29 -0700651std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700652 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700653}
654
655std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700656 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800657}
658
Calin Juravle79f55a42016-02-17 20:14:46 +0000659// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
660std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700661 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000662}
663
Andreas Huber71cd43f2018-01-22 11:25:29 -0800664std::string BuildDataVendorCePath(userid_t userId) {
665 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
666}
667
668std::string BuildDataVendorDePath(userid_t userId) {
669 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
670}
671
Paul Crowley3b71fc52017-10-09 10:55:21 -0700672std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800673 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700674 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800675 return "/data";
676 } else {
677 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700678 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800679 }
680}
681
Paul Crowley3b71fc52017-10-09 10:55:21 -0700682std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700683 // TODO: unify with installd path generation logic
684 std::string data(BuildDataPath(volumeUuid));
685 return StringPrintf("%s/media/%u", data.c_str(), userId);
686}
687
Paul Crowley3b71fc52017-10-09 10:55:21 -0700688std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800689 // TODO: unify with installd path generation logic
690 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700691 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800692 std::string legacy = StringPrintf("%s/data", data.c_str());
693 struct stat sb;
694 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
695 /* /data/data is dir, return /data/data for legacy system */
696 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800697 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800698 }
cjbaoeb501142017-04-12 00:09:00 +0800699 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800700}
701
Paul Crowley3b71fc52017-10-09 10:55:21 -0700702std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800703 // TODO: unify with installd path generation logic
704 std::string data(BuildDataPath(volumeUuid));
705 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
706}
707
Jeff Sharkey66270a22015-06-24 11:49:24 -0700708dev_t GetDevice(const std::string& path) {
709 struct stat sb;
710 if (stat(path.c_str(), &sb)) {
711 PLOG(WARNING) << "Failed to stat " << path;
712 return 0;
713 } else {
714 return sb.st_dev;
715 }
716}
717
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600718status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700719 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600720
Tom Cherryd6127ef2017-06-15 17:13:56 -0700721 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600722
Tom Cherryd6127ef2017-06-15 17:13:56 -0700723 android::base::SetProperty(kRestoreconString, "");
724 android::base::SetProperty(kRestoreconString, path);
725
726 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600727
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700728 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600729 return OK;
730}
731
Jeff Sharkey3472e522017-10-06 18:02:53 -0600732bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
733 // Shamelessly borrowed from android::base::Readlink()
734 result->clear();
735
736 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
737 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
738 // waste memory to just start there. We add 1 so that we can recognize
739 // whether it actually fit (rather than being truncated to 4095).
740 std::vector<char> buf(4095 + 1);
741 while (true) {
742 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
743 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700744 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600745 // It fit! (If size == buf.size(), it may have been truncated.)
746 if (static_cast<size_t>(size) < buf.size()) {
747 result->assign(&buf[0], size);
748 return true;
749 }
750 // Double our buffer and try again.
751 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900752 }
753}
754
Yu Ning942d4e82016-01-08 17:36:47 +0800755bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700756 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800757}
758
Sudheer Shanka295fb242019-01-16 23:04:07 -0800759static status_t findMountPointsWithPrefix(const std::string& prefix,
760 std::list<std::string>& mountPoints) {
761 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
762 // when the prefix is /foo/bar
763 std::string prefixWithSlash(prefix);
764 if (prefix.back() != '/') {
765 android::base::StringAppendF(&prefixWithSlash, "/");
766 }
767
768 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
769 if (!mnts) {
770 PLOG(ERROR) << "Unable to open /proc/mounts";
771 return -errno;
772 }
773
774 // Some volumes can be stacked on each other, so force unmount in
775 // reverse order to give us the best chance of success.
776 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
777 while ((mnt = getmntent(mnts.get())) != nullptr) {
778 auto mountPoint = std::string(mnt->mnt_dir) + "/";
779 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
780 mountPoints.push_front(mountPoint);
781 }
782 }
783 return OK;
784}
785
786// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
787status_t UnmountTreeWithPrefix(const std::string& prefix) {
788 std::list<std::string> toUnmount;
789 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
790 if (result < 0) {
791 return result;
792 }
793 for (const auto& path : toUnmount) {
794 if (umount2(path.c_str(), MNT_DETACH)) {
795 PLOG(ERROR) << "Failed to unmount " << path;
796 result = -errno;
797 }
798 }
799 return result;
800}
801
802status_t UnmountTree(const std::string& mountPoint) {
803 if (umount2(mountPoint.c_str(), MNT_DETACH)) {
804 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700805 return -errno;
806 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700807 return OK;
808}
809
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700810static status_t delete_dir_contents(DIR* dir) {
811 // Shamelessly borrowed from android::installd
812 int dfd = dirfd(dir);
813 if (dfd < 0) {
814 return -errno;
815 }
816
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800817 status_t result = OK;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700818 struct dirent* de;
819 while ((de = readdir(dir))) {
820 const char* name = de->d_name;
821 if (de->d_type == DT_DIR) {
822 /* always skip "." and ".." */
823 if (name[0] == '.') {
824 if (name[1] == 0) continue;
825 if ((name[1] == '.') && (name[2] == 0)) continue;
826 }
827
828 android::base::unique_fd subfd(
829 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
830 if (subfd.get() == -1) {
831 PLOG(ERROR) << "Couldn't openat " << name;
832 result = -errno;
833 continue;
834 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800835 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
836 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700837 if (!subdirp) {
838 PLOG(ERROR) << "Couldn't fdopendir " << name;
839 result = -errno;
840 continue;
841 }
842 result = delete_dir_contents(subdirp.get());
843 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
844 PLOG(ERROR) << "Couldn't unlinkat " << name;
845 result = -errno;
846 }
847 } else {
848 if (unlinkat(dfd, name, 0) < 0) {
849 PLOG(ERROR) << "Couldn't unlinkat " << name;
850 result = -errno;
851 }
852 }
853 }
854 return result;
855}
856
857status_t DeleteDirContentsAndDir(const std::string& pathname) {
858 // Shamelessly borrowed from android::installd
859 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
860 if (!dirp) {
861 if (errno == ENOENT) {
862 return OK;
863 }
864 PLOG(ERROR) << "Failed to opendir " << pathname;
865 return -errno;
866 }
867 status_t res = delete_dir_contents(dirp.get());
868 if (res < 0) {
869 return res;
870 }
871 dirp.reset(nullptr);
872 if (rmdir(pathname.c_str()) != 0) {
873 PLOG(ERROR) << "rmdir failed on " << pathname;
874 return -errno;
875 }
876 LOG(VERBOSE) << "Success: rmdir on " << pathname;
877 return OK;
878}
879
Paul Crowley298fa322018-10-30 15:59:24 -0700880// TODO(118708649): fix duplication with init/util.h
881status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
882 android::base::Timer t;
883 while (t.duration() < timeout) {
884 struct stat sb;
885 if (stat(filename, &sb) != -1) {
886 LOG(INFO) << "wait for '" << filename << "' took " << t;
887 return 0;
888 }
889 std::this_thread::sleep_for(10ms);
890 }
891 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
892 return -1;
893}
894
Paul Crowley621d9b92018-12-07 15:36:09 -0800895bool FsyncDirectory(const std::string& dirname) {
896 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
897 if (fd == -1) {
898 PLOG(ERROR) << "Failed to open " << dirname;
899 return false;
900 }
901 if (fsync(fd) == -1) {
902 if (errno == EROFS || errno == EINVAL) {
903 PLOG(WARNING) << "Skip fsync " << dirname
904 << " on a file system does not support synchronization";
905 } else {
906 PLOG(ERROR) << "Failed to fsync " << dirname;
907 return false;
908 }
909 }
910 return true;
911}
912
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800913} // namespace vold
914} // namespace android