blob: d348f711814e65abb14af4431c2920447aecd918 [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
Elliott Hughes7e128fb2015-12-04 15:50:53 -080022#include <android-base/file.h>
23#include <android-base/logging.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070024#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080025#include <android-base/stringprintf.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070026#include <android-base/strings.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070027#include <android-base/unique_fd.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080028#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070029#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070030#include <private/android_filesystem_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080031
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070032#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080033#include <fcntl.h>
34#include <linux/fs.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070035#include <mntent.h>
36#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080037#include <stdlib.h>
38#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080039#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070040#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070041#include <sys/sysmacros.h>
42#include <sys/types.h>
43#include <sys/wait.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070044#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070045#include <mutex>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080046
47#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070048#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080049#endif
50
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070051using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070052using android::base::StringPrintf;
53
Jeff Sharkeydeb24052015-03-02 21:01:40 -080054namespace android {
55namespace vold {
56
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070057security_context_t sBlkidContext = nullptr;
58security_context_t sBlkidUntrustedContext = nullptr;
59security_context_t sFsckContext = nullptr;
60security_context_t sFsckUntrustedContext = nullptr;
61
Paul Crowley56292ef2017-10-20 08:07:53 -070062bool sSleepOnUnmount = true;
63
Jeff Sharkey9c484982015-03-31 10:35:33 -070064static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070065static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070066
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070067static const char* kProcFilesystems = "/proc/filesystems";
68
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060069// Lock used to protect process-level SELinux changes from racing with each
70// other between multiple threads.
71static std::mutex kSecurityLock;
72
Jeff Sharkeydeb24052015-03-02 21:01:40 -080073status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060074 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080075 const char* cpath = path.c_str();
76 status_t res = 0;
77
78 char* secontext = nullptr;
79 if (sehandle) {
80 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
81 setfscreatecon(secontext);
82 }
83 }
84
85 mode_t mode = 0660 | S_IFBLK;
86 if (mknod(cpath, mode, dev) < 0) {
87 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070088 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
89 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080090 res = -errno;
91 }
92 }
93
94 if (secontext) {
95 setfscreatecon(nullptr);
96 freecon(secontext);
97 }
98
99 return res;
100}
101
102status_t DestroyDeviceNode(const std::string& path) {
103 const char* cpath = path.c_str();
104 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
105 return -errno;
106 } else {
107 return OK;
108 }
109}
110
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700111status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600112 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700113 const char* cpath = path.c_str();
114
115 char* secontext = nullptr;
116 if (sehandle) {
117 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
118 setfscreatecon(secontext);
119 }
120 }
121
122 int res = fs_prepare_dir(cpath, mode, uid, gid);
123
124 if (secontext) {
125 setfscreatecon(nullptr);
126 freecon(secontext);
127 }
128
129 if (res == 0) {
130 return OK;
131 } else {
132 return -errno;
133 }
134}
135
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800136status_t ForceUnmount(const std::string& path) {
137 const char* cpath = path.c_str();
138 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
139 return OK;
140 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700141 // Apps might still be handling eject request, so wait before
142 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700143 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700144
Jeff Sharkey3472e522017-10-06 18:02:53 -0600145 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700146 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700147 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
148 return OK;
149 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700150
Jeff Sharkey3472e522017-10-06 18:02:53 -0600151 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700152 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800153 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
154 return OK;
155 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700156
Jeff Sharkey3472e522017-10-06 18:02:53 -0600157 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700158 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700159 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
160 return OK;
161 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700162
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800163 return -errno;
164}
165
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700166status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600167 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700168 return OK;
169 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700170 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700171
Jeff Sharkey3472e522017-10-06 18:02:53 -0600172 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700173 return OK;
174 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700175 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700176
Jeff Sharkey3472e522017-10-06 18:02:53 -0600177 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700178 return OK;
179 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700180 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700181
182 // Send SIGKILL a second time to determine if we've
183 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600184 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700185 return OK;
186 }
187 PLOG(ERROR) << "Failed to kill processes using " << path;
188 return -EBUSY;
189}
190
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700191status_t BindMount(const std::string& source, const std::string& target) {
192 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
193 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
194 return -errno;
195 }
196 return OK;
197}
198
Jeff Sharkey3472e522017-10-06 18:02:53 -0600199bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
200 auto qual = key + "=\"";
201 auto start = raw.find(qual);
202 if (start > 0 && raw[start - 1] != ' ') {
203 start = raw.find(qual, start + 1);
204 }
205
206 if (start == std::string::npos) return false;
207 start += qual.length();
208
209 auto end = raw.find("\"", start);
210 if (end == std::string::npos) return false;
211
212 *value = raw.substr(start, end - start);
213 return true;
214}
215
Paul Crowley14c8c072018-09-18 13:30:21 -0700216static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
217 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600218 fsType->clear();
219 fsUuid->clear();
220 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700221
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700222 std::vector<std::string> cmd;
223 cmd.push_back(kBlkidPath);
224 cmd.push_back("-c");
225 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700226 cmd.push_back("-s");
227 cmd.push_back("TYPE");
228 cmd.push_back("-s");
229 cmd.push_back("UUID");
230 cmd.push_back("-s");
231 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700232 cmd.push_back(path);
233
234 std::vector<std::string> output;
235 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
236 if (res != OK) {
237 LOG(WARNING) << "blkid failed to identify " << path;
238 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700239 }
240
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700241 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700242 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600243 FindValue(line, "TYPE", fsType);
244 FindValue(line, "UUID", fsUuid);
245 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700246 }
247
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700248 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700249}
250
Paul Crowley14c8c072018-09-18 13:30:21 -0700251status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
252 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700253 return readMetadata(path, fsType, fsUuid, fsLabel, false);
254}
255
Paul Crowley14c8c072018-09-18 13:30:21 -0700256status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
257 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700258 return readMetadata(path, fsType, fsUuid, fsLabel, true);
259}
260
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700261status_t ForkExecvp(const std::vector<std::string>& args) {
262 return ForkExecvp(args, nullptr);
263}
264
265status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600266 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700267 size_t argc = args.size();
Paul Crowley14c8c072018-09-18 13:30:21 -0700268 char** argv = (char**)calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700269 for (size_t i = 0; i < argc; i++) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700270 argv[i] = (char*)args[i].c_str();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700271 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700272 LOG(DEBUG) << args[i];
Jeff Sharkey9c484982015-03-31 10:35:33 -0700273 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700274 LOG(DEBUG) << " " << args[i];
Jeff Sharkey9c484982015-03-31 10:35:33 -0700275 }
276 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700277
Paul Crowley82b41ff2017-10-20 08:17:54 -0700278 if (context) {
279 if (setexeccon(context)) {
280 LOG(ERROR) << "Failed to setexeccon";
281 abort();
282 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700283 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700284 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
Paul Crowley82b41ff2017-10-20 08:17:54 -0700285 if (context) {
286 if (setexeccon(nullptr)) {
287 LOG(ERROR) << "Failed to setexeccon";
288 abort();
289 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700290 }
291
Jeff Sharkey9c484982015-03-31 10:35:33 -0700292 free(argv);
293 return res;
294}
295
Paul Crowley14c8c072018-09-18 13:30:21 -0700296status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700297 return ForkExecvp(args, output, nullptr);
298}
299
Paul Crowley14c8c072018-09-18 13:30:21 -0700300status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output,
301 security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600302 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700303 std::string cmd;
304 for (size_t i = 0; i < args.size(); i++) {
305 cmd += args[i] + " ";
306 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700307 LOG(DEBUG) << args[i];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700308 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700309 LOG(DEBUG) << " " << args[i];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700310 }
311 }
312 output.clear();
313
Paul Crowley82b41ff2017-10-20 08:17:54 -0700314 if (context) {
315 if (setexeccon(context)) {
316 LOG(ERROR) << "Failed to setexeccon";
317 abort();
318 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700319 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700320 FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
Paul Crowley82b41ff2017-10-20 08:17:54 -0700321 if (context) {
322 if (setexeccon(nullptr)) {
323 LOG(ERROR) << "Failed to setexeccon";
324 abort();
325 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700326 }
327
328 if (!fp) {
329 PLOG(ERROR) << "Failed to popen " << cmd;
330 return -errno;
331 }
332 char line[1024];
333 while (fgets(line, sizeof(line), fp) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700334 LOG(DEBUG) << line;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700335 output.push_back(std::string(line));
336 }
337 if (pclose(fp) != 0) {
338 PLOG(ERROR) << "Failed to pclose " << cmd;
339 return -errno;
340 }
341
342 return OK;
343}
344
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700345pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
346 size_t argc = args.size();
Paul Crowley14c8c072018-09-18 13:30:21 -0700347 char** argv = (char**)calloc(argc + 1, sizeof(char*));
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700348 for (size_t i = 0; i < argc; i++) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700349 argv[i] = (char*)args[i].c_str();
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700350 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700351 LOG(DEBUG) << args[i];
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700352 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700353 LOG(DEBUG) << " " << args[i];
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700354 }
355 }
356
357 pid_t pid = fork();
358 if (pid == 0) {
359 close(STDIN_FILENO);
360 close(STDOUT_FILENO);
361 close(STDERR_FILENO);
362
363 if (execvp(argv[0], argv)) {
364 PLOG(ERROR) << "Failed to exec";
365 }
366
367 _exit(1);
368 }
369
370 if (pid == -1) {
371 PLOG(ERROR) << "Failed to exec";
372 }
373
374 free(argv);
375 return pid;
376}
377
Jeff Sharkey9c484982015-03-31 10:35:33 -0700378status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100379 out.resize(bytes);
380 return ReadRandomBytes(bytes, &out[0]);
381}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700382
Pavel Grafove2e2d302017-08-01 17:15:53 +0100383status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700384 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
385 if (fd == -1) {
386 return -errno;
387 }
388
Jeff Sharkey9c484982015-03-31 10:35:33 -0700389 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100390 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700391 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100392 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700393 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700394 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700395
396 if (bytes == 0) {
397 return OK;
398 } else {
399 return -EIO;
400 }
401}
402
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600403status_t GenerateRandomUuid(std::string& out) {
404 status_t res = ReadRandomBytes(16, out);
405 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700406 out[6] &= 0x0f; /* clear version */
407 out[6] |= 0x40; /* set to version 4 */
408 out[8] &= 0x3f; /* clear variant */
409 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600410 }
411 return res;
412}
413
Jeff Sharkey9c484982015-03-31 10:35:33 -0700414status_t HexToStr(const std::string& hex, std::string& str) {
415 str.clear();
416 bool even = true;
417 char cur = 0;
418 for (size_t i = 0; i < hex.size(); i++) {
419 int val = 0;
420 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700421 // clang-format off
422 case ' ': case '-': case ':': continue;
423 case 'f': case 'F': val = 15; break;
424 case 'e': case 'E': val = 14; break;
425 case 'd': case 'D': val = 13; break;
426 case 'c': case 'C': val = 12; break;
427 case 'b': case 'B': val = 11; break;
428 case 'a': case 'A': val = 10; break;
429 case '9': val = 9; break;
430 case '8': val = 8; break;
431 case '7': val = 7; break;
432 case '6': val = 6; break;
433 case '5': val = 5; break;
434 case '4': val = 4; break;
435 case '3': val = 3; break;
436 case '2': val = 2; break;
437 case '1': val = 1; break;
438 case '0': val = 0; break;
439 default: return -EINVAL;
440 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700441 }
442
443 if (even) {
444 cur = val << 4;
445 } else {
446 cur += val;
447 str.push_back(cur);
448 cur = 0;
449 }
450 even = !even;
451 }
452 return even ? OK : -EINVAL;
453}
454
455static const char* kLookup = "0123456789abcdef";
456
457status_t StrToHex(const std::string& str, std::string& hex) {
458 hex.clear();
459 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700460 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700461 hex.push_back(kLookup[str[i] & 0x0F]);
462 }
463 return OK;
464}
465
Pavel Grafove2e2d302017-08-01 17:15:53 +0100466status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
467 hex.clear();
468 for (size_t i = 0; i < str.size(); i++) {
469 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
470 hex.push_back(kLookup[str.data()[i] & 0x0F]);
471 }
472 return OK;
473}
474
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700475status_t NormalizeHex(const std::string& in, std::string& out) {
476 std::string tmp;
477 if (HexToStr(in, tmp)) {
478 return -EINVAL;
479 }
480 return StrToHex(tmp, out);
481}
482
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200483status_t GetBlockDevSize(int fd, uint64_t* size) {
484 if (ioctl(fd, BLKGETSIZE64, size)) {
485 return -errno;
486 }
487
488 return OK;
489}
490
491status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
492 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
493 status_t res = OK;
494
495 if (fd < 0) {
496 return -errno;
497 }
498
499 res = GetBlockDevSize(fd, size);
500
501 close(fd);
502
503 return res;
504}
505
506status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
507 uint64_t size;
508 status_t res = GetBlockDevSize(path, &size);
509
510 if (res != OK) {
511 return res;
512 }
513
514 *nr_sec = size / 512;
515
516 return OK;
517}
518
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700519uint64_t GetFreeBytes(const std::string& path) {
520 struct statvfs sb;
521 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700522 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700523 } else {
524 return -1;
525 }
526}
527
528// TODO: borrowed from frameworks/native/libs/diskusage/ which should
529// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700530static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700531 int64_t blksize = s->st_blksize;
532 // count actual blocks used instead of nominal file size
533 int64_t size = s->st_blocks * 512;
534
535 if (blksize) {
536 /* round up to filesystem block size */
537 size = (size + blksize - 1) & (~(blksize - 1));
538 }
539
540 return size;
541}
542
543// TODO: borrowed from frameworks/native/libs/diskusage/ which should
544// eventually be migrated into system/
545int64_t calculate_dir_size(int dfd) {
546 int64_t size = 0;
547 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700548 DIR* d;
549 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700550
551 d = fdopendir(dfd);
552 if (d == NULL) {
553 close(dfd);
554 return 0;
555 }
556
557 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700558 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700559 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
560 size += stat_size(&s);
561 }
562 if (de->d_type == DT_DIR) {
563 int subfd;
564
565 /* always skip "." and ".." */
566 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700567 if (name[1] == 0) continue;
568 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700569 }
570
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600571 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700572 if (subfd >= 0) {
573 size += calculate_dir_size(subfd);
574 }
575 }
576 }
577 closedir(d);
578 return size;
579}
580
581uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600582 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700583 if (dirfd < 0) {
584 PLOG(WARNING) << "Failed to open " << path;
585 return -1;
586 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700587 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700588 }
589}
590
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700591bool IsFilesystemSupported(const std::string& fsType) {
592 std::string supported;
593 if (!ReadFileToString(kProcFilesystems, &supported)) {
594 PLOG(ERROR) << "Failed to read supported filesystems";
595 return false;
596 }
597 return supported.find(fsType + "\n") != std::string::npos;
598}
599
600status_t WipeBlockDevice(const std::string& path) {
601 status_t res = -1;
602 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200603 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700604
605 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
606 if (fd == -1) {
607 PLOG(ERROR) << "Failed to open " << path;
608 goto done;
609 }
610
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200611 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700612 PLOG(ERROR) << "Failed to determine size of " << path;
613 goto done;
614 }
615
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700616 LOG(INFO) << "About to discard " << range[1] << " on " << path;
617 if (ioctl(fd, BLKDISCARD, &range) == 0) {
618 LOG(INFO) << "Discard success on " << path;
619 res = 0;
620 } else {
621 PLOG(ERROR) << "Discard failure on " << path;
622 }
623
624done:
625 close(fd);
626 return res;
627}
628
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800629static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700630 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800631 return false;
632 } else {
633 return true;
634 }
635}
636
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700637std::string BuildKeyPath(const std::string& partGuid) {
638 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
639}
640
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600641std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700642 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600643}
644
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800645std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700646 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700647}
648
649std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700650 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700651}
652
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600653std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700654 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600655}
656
Jeff Sharkey47695b22016-02-01 17:02:29 -0700657std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700658 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700659}
660
661std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700662 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800663}
664
Calin Juravle79f55a42016-02-17 20:14:46 +0000665// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
666std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700667 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000668}
669
Andreas Huber71cd43f2018-01-22 11:25:29 -0800670std::string BuildDataVendorCePath(userid_t userId) {
671 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
672}
673
674std::string BuildDataVendorDePath(userid_t userId) {
675 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
676}
677
Paul Crowley3b71fc52017-10-09 10:55:21 -0700678std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800679 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700680 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800681 return "/data";
682 } else {
683 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700684 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800685 }
686}
687
Paul Crowley3b71fc52017-10-09 10:55:21 -0700688std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700689 // TODO: unify with installd path generation logic
690 std::string data(BuildDataPath(volumeUuid));
691 return StringPrintf("%s/media/%u", data.c_str(), userId);
692}
693
Paul Crowley3b71fc52017-10-09 10:55:21 -0700694std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800695 // TODO: unify with installd path generation logic
696 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700697 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800698 std::string legacy = StringPrintf("%s/data", data.c_str());
699 struct stat sb;
700 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
701 /* /data/data is dir, return /data/data for legacy system */
702 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800703 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800704 }
cjbaoeb501142017-04-12 00:09:00 +0800705 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800706}
707
Paul Crowley3b71fc52017-10-09 10:55:21 -0700708std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800709 // TODO: unify with installd path generation logic
710 std::string data(BuildDataPath(volumeUuid));
711 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
712}
713
Jeff Sharkey66270a22015-06-24 11:49:24 -0700714dev_t GetDevice(const std::string& path) {
715 struct stat sb;
716 if (stat(path.c_str(), &sb)) {
717 PLOG(WARNING) << "Failed to stat " << path;
718 return 0;
719 } else {
720 return sb.st_dev;
721 }
722}
723
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600724status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700725 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600726
Tom Cherryd6127ef2017-06-15 17:13:56 -0700727 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600728
Tom Cherryd6127ef2017-06-15 17:13:56 -0700729 android::base::SetProperty(kRestoreconString, "");
730 android::base::SetProperty(kRestoreconString, path);
731
732 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600733
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700734 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600735 return OK;
736}
737
Jeff Sharkey3472e522017-10-06 18:02:53 -0600738bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
739 // Shamelessly borrowed from android::base::Readlink()
740 result->clear();
741
742 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
743 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
744 // waste memory to just start there. We add 1 so that we can recognize
745 // whether it actually fit (rather than being truncated to 4095).
746 std::vector<char> buf(4095 + 1);
747 while (true) {
748 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
749 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700750 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600751 // It fit! (If size == buf.size(), it may have been truncated.)
752 if (static_cast<size_t>(size) < buf.size()) {
753 result->assign(&buf[0], size);
754 return true;
755 }
756 // Double our buffer and try again.
757 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900758 }
759}
760
Yu Ning942d4e82016-01-08 17:36:47 +0800761bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700762 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800763}
764
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700765status_t UnmountTree(const std::string& prefix) {
766 FILE* fp = setmntent("/proc/mounts", "r");
767 if (fp == NULL) {
768 PLOG(ERROR) << "Failed to open /proc/mounts";
769 return -errno;
770 }
771
772 // Some volumes can be stacked on each other, so force unmount in
773 // reverse order to give us the best chance of success.
774 std::list<std::string> toUnmount;
775 mntent* mentry;
776 while ((mentry = getmntent(fp)) != NULL) {
777 auto test = std::string(mentry->mnt_dir) + "/";
778 if (android::base::StartsWith(test, prefix)) {
779 toUnmount.push_front(test);
780 }
781 }
782 endmntent(fp);
783
784 for (const auto& path : toUnmount) {
785 if (umount2(path.c_str(), MNT_DETACH)) {
786 PLOG(ERROR) << "Failed to unmount " << path;
787 }
788 }
789 return OK;
790}
791
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700792static status_t delete_dir_contents(DIR* dir) {
793 // Shamelessly borrowed from android::installd
794 int dfd = dirfd(dir);
795 if (dfd < 0) {
796 return -errno;
797 }
798
799 status_t result;
800 struct dirent* de;
801 while ((de = readdir(dir))) {
802 const char* name = de->d_name;
803 if (de->d_type == DT_DIR) {
804 /* always skip "." and ".." */
805 if (name[0] == '.') {
806 if (name[1] == 0) continue;
807 if ((name[1] == '.') && (name[2] == 0)) continue;
808 }
809
810 android::base::unique_fd subfd(
811 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
812 if (subfd.get() == -1) {
813 PLOG(ERROR) << "Couldn't openat " << name;
814 result = -errno;
815 continue;
816 }
817 std::unique_ptr<DIR, decltype(&closedir)> subdirp(fdopendir(subfd), closedir);
818 if (!subdirp) {
819 PLOG(ERROR) << "Couldn't fdopendir " << name;
820 result = -errno;
821 continue;
822 }
823 result = delete_dir_contents(subdirp.get());
824 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
825 PLOG(ERROR) << "Couldn't unlinkat " << name;
826 result = -errno;
827 }
828 } else {
829 if (unlinkat(dfd, name, 0) < 0) {
830 PLOG(ERROR) << "Couldn't unlinkat " << name;
831 result = -errno;
832 }
833 }
834 }
835 return result;
836}
837
838status_t DeleteDirContentsAndDir(const std::string& pathname) {
839 // Shamelessly borrowed from android::installd
840 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
841 if (!dirp) {
842 if (errno == ENOENT) {
843 return OK;
844 }
845 PLOG(ERROR) << "Failed to opendir " << pathname;
846 return -errno;
847 }
848 status_t res = delete_dir_contents(dirp.get());
849 if (res < 0) {
850 return res;
851 }
852 dirp.reset(nullptr);
853 if (rmdir(pathname.c_str()) != 0) {
854 PLOG(ERROR) << "rmdir failed on " << pathname;
855 return -errno;
856 }
857 LOG(VERBOSE) << "Success: rmdir on " << pathname;
858 return OK;
859}
860
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800861} // namespace vold
862} // namespace android