blob: 667d2778248802209d61870a82165bda2dd50882 [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 + "=\"";
205 auto start = raw.find(qual);
206 if (start > 0 && raw[start - 1] != ' ') {
207 start = raw.find(qual, start + 1);
208 }
209
210 if (start == std::string::npos) return false;
211 start += qual.length();
212
213 auto end = raw.find("\"", start);
214 if (end == std::string::npos) return false;
215
216 *value = raw.substr(start, end - start);
217 return true;
218}
219
Paul Crowley14c8c072018-09-18 13:30:21 -0700220static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
221 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600222 fsType->clear();
223 fsUuid->clear();
224 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700225
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700226 std::vector<std::string> cmd;
227 cmd.push_back(kBlkidPath);
228 cmd.push_back("-c");
229 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700230 cmd.push_back("-s");
231 cmd.push_back("TYPE");
232 cmd.push_back("-s");
233 cmd.push_back("UUID");
234 cmd.push_back("-s");
235 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700236 cmd.push_back(path);
237
238 std::vector<std::string> output;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800239 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700240 if (res != OK) {
241 LOG(WARNING) << "blkid failed to identify " << path;
242 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700243 }
244
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700245 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700246 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600247 FindValue(line, "TYPE", fsType);
248 FindValue(line, "UUID", fsUuid);
249 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700250 }
251
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700252 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700253}
254
Paul Crowley14c8c072018-09-18 13:30:21 -0700255status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
256 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700257 return readMetadata(path, fsType, fsUuid, fsLabel, false);
258}
259
Paul Crowley14c8c072018-09-18 13:30:21 -0700260status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
261 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700262 return readMetadata(path, fsType, fsUuid, fsLabel, true);
263}
264
Paul Crowleyde2d6202018-11-30 11:43:47 -0800265static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
266 std::vector<const char*> argv;
267 argv.reserve(args.size() + 1);
268 for (const auto& arg : args) {
269 if (argv.empty()) {
270 LOG(DEBUG) << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700271 } else {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800272 LOG(DEBUG) << " " << arg;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700273 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800274 argv.emplace_back(arg.data());
Jeff Sharkey9c484982015-03-31 10:35:33 -0700275 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800276 argv.emplace_back(nullptr);
277 return argv;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700278}
279
Paul Crowleyde2d6202018-11-30 11:43:47 -0800280static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
281 android::base::unique_fd ufd) {
282 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700283 if (!fp) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800284 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700285 return -errno;
286 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800287 if (output) output->clear();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700288 char line[1024];
Paul Crowleyde2d6202018-11-30 11:43:47 -0800289 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700290 LOG(DEBUG) << line;
Paul Crowleyde2d6202018-11-30 11:43:47 -0800291 if (output) output->emplace_back(line);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700292 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800293 return OK;
294}
295
296status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
297 security_context_t context) {
298 auto argv = ConvertToArgv(args);
299
Paul Crowleye6d76632018-11-30 11:43:47 -0800300 android::base::unique_fd pipe_read, pipe_write;
301 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
302 PLOG(ERROR) << "Pipe in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800303 return -errno;
304 }
Paul Crowleyde2d6202018-11-30 11:43:47 -0800305
306 pid_t pid = fork();
307 if (pid == 0) {
308 if (context) {
309 if (setexeccon(context)) {
Paul Crowleye6d76632018-11-30 11:43:47 -0800310 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800311 abort();
312 }
313 }
314 pipe_read.reset();
Paul Crowleybe857bf2018-12-07 12:23:25 -0800315 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
316 PLOG(ERROR) << "dup2 in ForkExecvp";
317 _exit(EXIT_FAILURE);
318 }
Paul Crowleye6d76632018-11-30 11:43:47 -0800319 pipe_write.reset();
Paul Crowleyde2d6202018-11-30 11:43:47 -0800320 execvp(argv[0], const_cast<char**>(argv.data()));
Paul Crowleye6d76632018-11-30 11:43:47 -0800321 PLOG(ERROR) << "exec in ForkExecvp";
Paul Crowleyde2d6202018-11-30 11:43:47 -0800322 _exit(EXIT_FAILURE);
323 }
324 if (pid == -1) {
325 PLOG(ERROR) << "fork in ForkExecvp";
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700326 return -errno;
327 }
328
Paul Crowleyde2d6202018-11-30 11:43:47 -0800329 pipe_write.reset();
330 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
331 if (st != 0) return st;
332
333 int status;
334 if (waitpid(pid, &status, 0) == -1) {
335 PLOG(ERROR) << "waitpid in ForkExecvp";
336 return -errno;
337 }
338 if (!WIFEXITED(status)) {
339 LOG(ERROR) << "Process did not exit normally, status: " << status;
340 return -ECHILD;
341 }
342 if (WEXITSTATUS(status)) {
343 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
344 return WEXITSTATUS(status);
345 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700346 return OK;
347}
348
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700349pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800350 auto argv = ConvertToArgv(args);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700351
352 pid_t pid = fork();
353 if (pid == 0) {
354 close(STDIN_FILENO);
355 close(STDOUT_FILENO);
356 close(STDERR_FILENO);
357
Paul Crowleyde2d6202018-11-30 11:43:47 -0800358 execvp(argv[0], const_cast<char**>(argv.data()));
359 PLOG(ERROR) << "exec in ForkExecvpAsync";
360 _exit(EXIT_FAILURE);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700361 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700362 if (pid == -1) {
Paul Crowleyde2d6202018-11-30 11:43:47 -0800363 PLOG(ERROR) << "fork in ForkExecvpAsync";
364 return -1;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700365 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700366 return pid;
367}
368
Jeff Sharkey9c484982015-03-31 10:35:33 -0700369status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100370 out.resize(bytes);
371 return ReadRandomBytes(bytes, &out[0]);
372}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700373
Pavel Grafove2e2d302017-08-01 17:15:53 +0100374status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700375 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
376 if (fd == -1) {
377 return -errno;
378 }
379
Jeff Sharkey9c484982015-03-31 10:35:33 -0700380 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100381 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700382 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100383 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700384 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700385 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700386
387 if (bytes == 0) {
388 return OK;
389 } else {
390 return -EIO;
391 }
392}
393
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600394status_t GenerateRandomUuid(std::string& out) {
395 status_t res = ReadRandomBytes(16, out);
396 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700397 out[6] &= 0x0f; /* clear version */
398 out[6] |= 0x40; /* set to version 4 */
399 out[8] &= 0x3f; /* clear variant */
400 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600401 }
402 return res;
403}
404
Jeff Sharkey9c484982015-03-31 10:35:33 -0700405status_t HexToStr(const std::string& hex, std::string& str) {
406 str.clear();
407 bool even = true;
408 char cur = 0;
409 for (size_t i = 0; i < hex.size(); i++) {
410 int val = 0;
411 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700412 // clang-format off
413 case ' ': case '-': case ':': continue;
414 case 'f': case 'F': val = 15; break;
415 case 'e': case 'E': val = 14; break;
416 case 'd': case 'D': val = 13; break;
417 case 'c': case 'C': val = 12; break;
418 case 'b': case 'B': val = 11; break;
419 case 'a': case 'A': val = 10; break;
420 case '9': val = 9; break;
421 case '8': val = 8; break;
422 case '7': val = 7; break;
423 case '6': val = 6; break;
424 case '5': val = 5; break;
425 case '4': val = 4; break;
426 case '3': val = 3; break;
427 case '2': val = 2; break;
428 case '1': val = 1; break;
429 case '0': val = 0; break;
430 default: return -EINVAL;
431 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700432 }
433
434 if (even) {
435 cur = val << 4;
436 } else {
437 cur += val;
438 str.push_back(cur);
439 cur = 0;
440 }
441 even = !even;
442 }
443 return even ? OK : -EINVAL;
444}
445
446static const char* kLookup = "0123456789abcdef";
447
448status_t StrToHex(const std::string& str, std::string& hex) {
449 hex.clear();
450 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700451 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700452 hex.push_back(kLookup[str[i] & 0x0F]);
453 }
454 return OK;
455}
456
Pavel Grafove2e2d302017-08-01 17:15:53 +0100457status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
458 hex.clear();
459 for (size_t i = 0; i < str.size(); i++) {
460 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
461 hex.push_back(kLookup[str.data()[i] & 0x0F]);
462 }
463 return OK;
464}
465
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700466status_t NormalizeHex(const std::string& in, std::string& out) {
467 std::string tmp;
468 if (HexToStr(in, tmp)) {
469 return -EINVAL;
470 }
471 return StrToHex(tmp, out);
472}
473
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200474status_t GetBlockDevSize(int fd, uint64_t* size) {
475 if (ioctl(fd, BLKGETSIZE64, size)) {
476 return -errno;
477 }
478
479 return OK;
480}
481
482status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
483 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
484 status_t res = OK;
485
486 if (fd < 0) {
487 return -errno;
488 }
489
490 res = GetBlockDevSize(fd, size);
491
492 close(fd);
493
494 return res;
495}
496
497status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
498 uint64_t size;
499 status_t res = GetBlockDevSize(path, &size);
500
501 if (res != OK) {
502 return res;
503 }
504
505 *nr_sec = size / 512;
506
507 return OK;
508}
509
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700510uint64_t GetFreeBytes(const std::string& path) {
511 struct statvfs sb;
512 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700513 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700514 } else {
515 return -1;
516 }
517}
518
519// TODO: borrowed from frameworks/native/libs/diskusage/ which should
520// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700521static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700522 int64_t blksize = s->st_blksize;
523 // count actual blocks used instead of nominal file size
524 int64_t size = s->st_blocks * 512;
525
526 if (blksize) {
527 /* round up to filesystem block size */
528 size = (size + blksize - 1) & (~(blksize - 1));
529 }
530
531 return size;
532}
533
534// TODO: borrowed from frameworks/native/libs/diskusage/ which should
535// eventually be migrated into system/
536int64_t calculate_dir_size(int dfd) {
537 int64_t size = 0;
538 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700539 DIR* d;
540 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700541
542 d = fdopendir(dfd);
543 if (d == NULL) {
544 close(dfd);
545 return 0;
546 }
547
548 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700549 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700550 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
551 size += stat_size(&s);
552 }
553 if (de->d_type == DT_DIR) {
554 int subfd;
555
556 /* always skip "." and ".." */
557 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700558 if (name[1] == 0) continue;
559 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700560 }
561
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600562 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700563 if (subfd >= 0) {
564 size += calculate_dir_size(subfd);
565 }
566 }
567 }
568 closedir(d);
569 return size;
570}
571
572uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600573 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700574 if (dirfd < 0) {
575 PLOG(WARNING) << "Failed to open " << path;
576 return -1;
577 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700578 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700579 }
580}
581
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700582bool IsFilesystemSupported(const std::string& fsType) {
583 std::string supported;
584 if (!ReadFileToString(kProcFilesystems, &supported)) {
585 PLOG(ERROR) << "Failed to read supported filesystems";
586 return false;
587 }
588 return supported.find(fsType + "\n") != std::string::npos;
589}
590
591status_t WipeBlockDevice(const std::string& path) {
592 status_t res = -1;
593 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200594 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700595
596 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
597 if (fd == -1) {
598 PLOG(ERROR) << "Failed to open " << path;
599 goto done;
600 }
601
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200602 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700603 PLOG(ERROR) << "Failed to determine size of " << path;
604 goto done;
605 }
606
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700607 LOG(INFO) << "About to discard " << range[1] << " on " << path;
608 if (ioctl(fd, BLKDISCARD, &range) == 0) {
609 LOG(INFO) << "Discard success on " << path;
610 res = 0;
611 } else {
612 PLOG(ERROR) << "Discard failure on " << path;
613 }
614
615done:
616 close(fd);
617 return res;
618}
619
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800620static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700621 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800622 return false;
623 } else {
624 return true;
625 }
626}
627
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700628std::string BuildKeyPath(const std::string& partGuid) {
629 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
630}
631
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600632std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700633 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600634}
635
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800636std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700637 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700638}
639
640std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700641 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700642}
643
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600644std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700645 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600646}
647
Jeff Sharkey47695b22016-02-01 17:02:29 -0700648std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700649 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700650}
651
652std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700653 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800654}
655
Calin Juravle79f55a42016-02-17 20:14:46 +0000656// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
657std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700658 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000659}
660
Andreas Huber71cd43f2018-01-22 11:25:29 -0800661std::string BuildDataVendorCePath(userid_t userId) {
662 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
663}
664
665std::string BuildDataVendorDePath(userid_t userId) {
666 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
667}
668
Paul Crowley3b71fc52017-10-09 10:55:21 -0700669std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800670 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700671 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800672 return "/data";
673 } else {
674 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700675 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800676 }
677}
678
Paul Crowley3b71fc52017-10-09 10:55:21 -0700679std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700680 // TODO: unify with installd path generation logic
681 std::string data(BuildDataPath(volumeUuid));
682 return StringPrintf("%s/media/%u", data.c_str(), userId);
683}
684
Paul Crowley3b71fc52017-10-09 10:55:21 -0700685std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800686 // TODO: unify with installd path generation logic
687 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700688 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800689 std::string legacy = StringPrintf("%s/data", data.c_str());
690 struct stat sb;
691 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
692 /* /data/data is dir, return /data/data for legacy system */
693 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800694 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800695 }
cjbaoeb501142017-04-12 00:09:00 +0800696 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800697}
698
Paul Crowley3b71fc52017-10-09 10:55:21 -0700699std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800700 // TODO: unify with installd path generation logic
701 std::string data(BuildDataPath(volumeUuid));
702 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
703}
704
Jeff Sharkey66270a22015-06-24 11:49:24 -0700705dev_t GetDevice(const std::string& path) {
706 struct stat sb;
707 if (stat(path.c_str(), &sb)) {
708 PLOG(WARNING) << "Failed to stat " << path;
709 return 0;
710 } else {
711 return sb.st_dev;
712 }
713}
714
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600715status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700716 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600717
Tom Cherryd6127ef2017-06-15 17:13:56 -0700718 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600719
Tom Cherryd6127ef2017-06-15 17:13:56 -0700720 android::base::SetProperty(kRestoreconString, "");
721 android::base::SetProperty(kRestoreconString, path);
722
723 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600724
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700725 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600726 return OK;
727}
728
Jeff Sharkey3472e522017-10-06 18:02:53 -0600729bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
730 // Shamelessly borrowed from android::base::Readlink()
731 result->clear();
732
733 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
734 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
735 // waste memory to just start there. We add 1 so that we can recognize
736 // whether it actually fit (rather than being truncated to 4095).
737 std::vector<char> buf(4095 + 1);
738 while (true) {
739 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
740 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700741 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600742 // It fit! (If size == buf.size(), it may have been truncated.)
743 if (static_cast<size_t>(size) < buf.size()) {
744 result->assign(&buf[0], size);
745 return true;
746 }
747 // Double our buffer and try again.
748 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900749 }
750}
751
Yu Ning942d4e82016-01-08 17:36:47 +0800752bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700753 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800754}
755
Sudheer Shanka295fb242019-01-16 23:04:07 -0800756static status_t findMountPointsWithPrefix(const std::string& prefix,
757 std::list<std::string>& mountPoints) {
758 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
759 // when the prefix is /foo/bar
760 std::string prefixWithSlash(prefix);
761 if (prefix.back() != '/') {
762 android::base::StringAppendF(&prefixWithSlash, "/");
763 }
764
765 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
766 if (!mnts) {
767 PLOG(ERROR) << "Unable to open /proc/mounts";
768 return -errno;
769 }
770
771 // Some volumes can be stacked on each other, so force unmount in
772 // reverse order to give us the best chance of success.
773 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
774 while ((mnt = getmntent(mnts.get())) != nullptr) {
775 auto mountPoint = std::string(mnt->mnt_dir) + "/";
776 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
777 mountPoints.push_front(mountPoint);
778 }
779 }
780 return OK;
781}
782
783// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
784status_t UnmountTreeWithPrefix(const std::string& prefix) {
785 std::list<std::string> toUnmount;
786 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
787 if (result < 0) {
788 return result;
789 }
790 for (const auto& path : toUnmount) {
791 if (umount2(path.c_str(), MNT_DETACH)) {
792 PLOG(ERROR) << "Failed to unmount " << path;
793 result = -errno;
794 }
795 }
796 return result;
797}
798
799status_t UnmountTree(const std::string& mountPoint) {
800 if (umount2(mountPoint.c_str(), MNT_DETACH)) {
801 PLOG(ERROR) << "Failed to unmount " << mountPoint;
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700802 return -errno;
803 }
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700804 return OK;
805}
806
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700807static status_t delete_dir_contents(DIR* dir) {
808 // Shamelessly borrowed from android::installd
809 int dfd = dirfd(dir);
810 if (dfd < 0) {
811 return -errno;
812 }
813
814 status_t result;
815 struct dirent* de;
816 while ((de = readdir(dir))) {
817 const char* name = de->d_name;
818 if (de->d_type == DT_DIR) {
819 /* always skip "." and ".." */
820 if (name[0] == '.') {
821 if (name[1] == 0) continue;
822 if ((name[1] == '.') && (name[2] == 0)) continue;
823 }
824
825 android::base::unique_fd subfd(
826 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
827 if (subfd.get() == -1) {
828 PLOG(ERROR) << "Couldn't openat " << name;
829 result = -errno;
830 continue;
831 }
Josh Gaoe3c32e02018-11-05 13:47:28 -0800832 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
833 android::base::Fdopendir(std::move(subfd)), closedir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700834 if (!subdirp) {
835 PLOG(ERROR) << "Couldn't fdopendir " << name;
836 result = -errno;
837 continue;
838 }
839 result = delete_dir_contents(subdirp.get());
840 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
841 PLOG(ERROR) << "Couldn't unlinkat " << name;
842 result = -errno;
843 }
844 } else {
845 if (unlinkat(dfd, name, 0) < 0) {
846 PLOG(ERROR) << "Couldn't unlinkat " << name;
847 result = -errno;
848 }
849 }
850 }
851 return result;
852}
853
854status_t DeleteDirContentsAndDir(const std::string& pathname) {
855 // Shamelessly borrowed from android::installd
856 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
857 if (!dirp) {
858 if (errno == ENOENT) {
859 return OK;
860 }
861 PLOG(ERROR) << "Failed to opendir " << pathname;
862 return -errno;
863 }
864 status_t res = delete_dir_contents(dirp.get());
865 if (res < 0) {
866 return res;
867 }
868 dirp.reset(nullptr);
869 if (rmdir(pathname.c_str()) != 0) {
870 PLOG(ERROR) << "rmdir failed on " << pathname;
871 return -errno;
872 }
873 LOG(VERBOSE) << "Success: rmdir on " << pathname;
874 return OK;
875}
876
Paul Crowley298fa322018-10-30 15:59:24 -0700877// TODO(118708649): fix duplication with init/util.h
878status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
879 android::base::Timer t;
880 while (t.duration() < timeout) {
881 struct stat sb;
882 if (stat(filename, &sb) != -1) {
883 LOG(INFO) << "wait for '" << filename << "' took " << t;
884 return 0;
885 }
886 std::this_thread::sleep_for(10ms);
887 }
888 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
889 return -1;
890}
891
Paul Crowley621d9b92018-12-07 15:36:09 -0800892bool FsyncDirectory(const std::string& dirname) {
893 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
894 if (fd == -1) {
895 PLOG(ERROR) << "Failed to open " << dirname;
896 return false;
897 }
898 if (fsync(fd) == -1) {
899 if (errno == EROFS || errno == EINVAL) {
900 PLOG(WARNING) << "Skip fsync " << dirname
901 << " on a file system does not support synchronization";
902 } else {
903 PLOG(ERROR) << "Failed to fsync " << dirname;
904 return false;
905 }
906 }
907 return true;
908}
909
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800910} // namespace vold
911} // namespace android