blob: 04c395632272ad01ffe88a8b06c62427eacfe32e [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 Crowleycfe39722018-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>
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>
Paul Crowleycfe39722018-10-30 15:59:24 -070044
Sudheer Shanka89ddf992018-09-25 14:22:07 -070045#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070046#include <mutex>
Paul Crowleycfe39722018-10-30 15:59:24 -070047#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080048
49#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070050#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080051#endif
52
Paul Crowleycfe39722018-10-30 15:59:24 -070053using namespace std::chrono_literals;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070054using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070055using android::base::StringPrintf;
56
Jeff Sharkeydeb24052015-03-02 21:01:40 -080057namespace android {
58namespace vold {
59
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070060security_context_t sBlkidContext = nullptr;
61security_context_t sBlkidUntrustedContext = nullptr;
62security_context_t sFsckContext = nullptr;
63security_context_t sFsckUntrustedContext = nullptr;
64
Paul Crowley56292ef2017-10-20 08:07:53 -070065bool sSleepOnUnmount = true;
66
Jeff Sharkey9c484982015-03-31 10:35:33 -070067static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070068static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070069
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070070static const char* kProcFilesystems = "/proc/filesystems";
71
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060072// Lock used to protect process-level SELinux changes from racing with each
73// other between multiple threads.
74static std::mutex kSecurityLock;
75
Jeff Sharkeydeb24052015-03-02 21:01:40 -080076status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060077 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080078 const char* cpath = path.c_str();
79 status_t res = 0;
80
81 char* secontext = nullptr;
82 if (sehandle) {
83 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
84 setfscreatecon(secontext);
85 }
86 }
87
88 mode_t mode = 0660 | S_IFBLK;
89 if (mknod(cpath, mode, dev) < 0) {
90 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070091 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
92 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080093 res = -errno;
94 }
95 }
96
97 if (secontext) {
98 setfscreatecon(nullptr);
99 freecon(secontext);
100 }
101
102 return res;
103}
104
105status_t DestroyDeviceNode(const std::string& path) {
106 const char* cpath = path.c_str();
107 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
108 return -errno;
109 } else {
110 return OK;
111 }
112}
113
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700114status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600115 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700116 const char* cpath = path.c_str();
117
118 char* secontext = nullptr;
119 if (sehandle) {
120 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
121 setfscreatecon(secontext);
122 }
123 }
124
125 int res = fs_prepare_dir(cpath, mode, uid, gid);
126
127 if (secontext) {
128 setfscreatecon(nullptr);
129 freecon(secontext);
130 }
131
132 if (res == 0) {
133 return OK;
134 } else {
135 return -errno;
136 }
137}
138
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800139status_t ForceUnmount(const std::string& path) {
140 const char* cpath = path.c_str();
141 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
142 return OK;
143 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700144 // Apps might still be handling eject request, so wait before
145 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700146 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700147
Jeff Sharkey3472e522017-10-06 18:02:53 -0600148 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700149 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700150 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
151 return OK;
152 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700153
Jeff Sharkey3472e522017-10-06 18:02:53 -0600154 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700155 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800156 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
157 return OK;
158 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700159
Jeff Sharkey3472e522017-10-06 18:02:53 -0600160 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700161 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700162 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
163 return OK;
164 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700165
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800166 return -errno;
167}
168
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700169status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600170 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700171 return OK;
172 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700173 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700174
Jeff Sharkey3472e522017-10-06 18:02:53 -0600175 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700176 return OK;
177 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700178 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700179
Jeff Sharkey3472e522017-10-06 18:02:53 -0600180 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700181 return OK;
182 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700183 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700184
185 // Send SIGKILL a second time to determine if we've
186 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600187 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700188 return OK;
189 }
190 PLOG(ERROR) << "Failed to kill processes using " << path;
191 return -EBUSY;
192}
193
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700194status_t BindMount(const std::string& source, const std::string& target) {
195 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
196 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
197 return -errno;
198 }
199 return OK;
200}
201
Jeff Sharkey3472e522017-10-06 18:02:53 -0600202bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
203 auto qual = key + "=\"";
204 auto start = raw.find(qual);
205 if (start > 0 && raw[start - 1] != ' ') {
206 start = raw.find(qual, start + 1);
207 }
208
209 if (start == std::string::npos) return false;
210 start += qual.length();
211
212 auto end = raw.find("\"", start);
213 if (end == std::string::npos) return false;
214
215 *value = raw.substr(start, end - start);
216 return true;
217}
218
Paul Crowley14c8c072018-09-18 13:30:21 -0700219static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
220 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600221 fsType->clear();
222 fsUuid->clear();
223 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700224
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700225 std::vector<std::string> cmd;
226 cmd.push_back(kBlkidPath);
227 cmd.push_back("-c");
228 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700229 cmd.push_back("-s");
230 cmd.push_back("TYPE");
231 cmd.push_back("-s");
232 cmd.push_back("UUID");
233 cmd.push_back("-s");
234 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700235 cmd.push_back(path);
236
237 std::vector<std::string> output;
238 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
239 if (res != OK) {
240 LOG(WARNING) << "blkid failed to identify " << path;
241 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700242 }
243
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700244 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700245 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600246 FindValue(line, "TYPE", fsType);
247 FindValue(line, "UUID", fsUuid);
248 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700249 }
250
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700251 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700252}
253
Paul Crowley14c8c072018-09-18 13:30:21 -0700254status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
255 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700256 return readMetadata(path, fsType, fsUuid, fsLabel, false);
257}
258
Paul Crowley14c8c072018-09-18 13:30:21 -0700259status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
260 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700261 return readMetadata(path, fsType, fsUuid, fsLabel, true);
262}
263
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700264status_t ForkExecvp(const std::vector<std::string>& args) {
265 return ForkExecvp(args, nullptr);
266}
267
268status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600269 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700270 size_t argc = args.size();
Paul Crowley14c8c072018-09-18 13:30:21 -0700271 char** argv = (char**)calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700272 for (size_t i = 0; i < argc; i++) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700273 argv[i] = (char*)args[i].c_str();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700274 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700275 LOG(DEBUG) << args[i];
Jeff Sharkey9c484982015-03-31 10:35:33 -0700276 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700277 LOG(DEBUG) << " " << args[i];
Jeff Sharkey9c484982015-03-31 10:35:33 -0700278 }
279 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700280
Paul Crowley82b41ff2017-10-20 08:17:54 -0700281 if (context) {
282 if (setexeccon(context)) {
283 LOG(ERROR) << "Failed to setexeccon";
284 abort();
285 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700286 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700287 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
Paul Crowley82b41ff2017-10-20 08:17:54 -0700288 if (context) {
289 if (setexeccon(nullptr)) {
290 LOG(ERROR) << "Failed to setexeccon";
291 abort();
292 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700293 }
294
Jeff Sharkey9c484982015-03-31 10:35:33 -0700295 free(argv);
296 return res;
297}
298
Paul Crowley14c8c072018-09-18 13:30:21 -0700299status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700300 return ForkExecvp(args, output, nullptr);
301}
302
Paul Crowley14c8c072018-09-18 13:30:21 -0700303status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output,
304 security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600305 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700306 std::string cmd;
307 for (size_t i = 0; i < args.size(); i++) {
308 cmd += args[i] + " ";
309 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700310 LOG(DEBUG) << args[i];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700311 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700312 LOG(DEBUG) << " " << args[i];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700313 }
314 }
315 output.clear();
316
Paul Crowley82b41ff2017-10-20 08:17:54 -0700317 if (context) {
318 if (setexeccon(context)) {
319 LOG(ERROR) << "Failed to setexeccon";
320 abort();
321 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700322 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700323 FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
Paul Crowley82b41ff2017-10-20 08:17:54 -0700324 if (context) {
325 if (setexeccon(nullptr)) {
326 LOG(ERROR) << "Failed to setexeccon";
327 abort();
328 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700329 }
330
331 if (!fp) {
332 PLOG(ERROR) << "Failed to popen " << cmd;
333 return -errno;
334 }
335 char line[1024];
336 while (fgets(line, sizeof(line), fp) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700337 LOG(DEBUG) << line;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700338 output.push_back(std::string(line));
339 }
340 if (pclose(fp) != 0) {
341 PLOG(ERROR) << "Failed to pclose " << cmd;
342 return -errno;
343 }
344
345 return OK;
346}
347
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700348pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
349 size_t argc = args.size();
Paul Crowley14c8c072018-09-18 13:30:21 -0700350 char** argv = (char**)calloc(argc + 1, sizeof(char*));
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700351 for (size_t i = 0; i < argc; i++) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700352 argv[i] = (char*)args[i].c_str();
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700353 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700354 LOG(DEBUG) << args[i];
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700355 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700356 LOG(DEBUG) << " " << args[i];
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700357 }
358 }
359
360 pid_t pid = fork();
361 if (pid == 0) {
362 close(STDIN_FILENO);
363 close(STDOUT_FILENO);
364 close(STDERR_FILENO);
365
366 if (execvp(argv[0], argv)) {
367 PLOG(ERROR) << "Failed to exec";
368 }
369
370 _exit(1);
371 }
372
373 if (pid == -1) {
374 PLOG(ERROR) << "Failed to exec";
375 }
376
377 free(argv);
378 return pid;
379}
380
Jeff Sharkey9c484982015-03-31 10:35:33 -0700381status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100382 out.resize(bytes);
383 return ReadRandomBytes(bytes, &out[0]);
384}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700385
Pavel Grafove2e2d302017-08-01 17:15:53 +0100386status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700387 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
388 if (fd == -1) {
389 return -errno;
390 }
391
Jeff Sharkey9c484982015-03-31 10:35:33 -0700392 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100393 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700394 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100395 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700396 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700397 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700398
399 if (bytes == 0) {
400 return OK;
401 } else {
402 return -EIO;
403 }
404}
405
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600406status_t GenerateRandomUuid(std::string& out) {
407 status_t res = ReadRandomBytes(16, out);
408 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700409 out[6] &= 0x0f; /* clear version */
410 out[6] |= 0x40; /* set to version 4 */
411 out[8] &= 0x3f; /* clear variant */
412 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600413 }
414 return res;
415}
416
Jeff Sharkey9c484982015-03-31 10:35:33 -0700417status_t HexToStr(const std::string& hex, std::string& str) {
418 str.clear();
419 bool even = true;
420 char cur = 0;
421 for (size_t i = 0; i < hex.size(); i++) {
422 int val = 0;
423 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700424 // clang-format off
425 case ' ': case '-': case ':': continue;
426 case 'f': case 'F': val = 15; break;
427 case 'e': case 'E': val = 14; break;
428 case 'd': case 'D': val = 13; break;
429 case 'c': case 'C': val = 12; break;
430 case 'b': case 'B': val = 11; break;
431 case 'a': case 'A': val = 10; break;
432 case '9': val = 9; break;
433 case '8': val = 8; break;
434 case '7': val = 7; break;
435 case '6': val = 6; break;
436 case '5': val = 5; break;
437 case '4': val = 4; break;
438 case '3': val = 3; break;
439 case '2': val = 2; break;
440 case '1': val = 1; break;
441 case '0': val = 0; break;
442 default: return -EINVAL;
443 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700444 }
445
446 if (even) {
447 cur = val << 4;
448 } else {
449 cur += val;
450 str.push_back(cur);
451 cur = 0;
452 }
453 even = !even;
454 }
455 return even ? OK : -EINVAL;
456}
457
458static const char* kLookup = "0123456789abcdef";
459
460status_t StrToHex(const std::string& str, std::string& hex) {
461 hex.clear();
462 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700463 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700464 hex.push_back(kLookup[str[i] & 0x0F]);
465 }
466 return OK;
467}
468
Pavel Grafove2e2d302017-08-01 17:15:53 +0100469status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
470 hex.clear();
471 for (size_t i = 0; i < str.size(); i++) {
472 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
473 hex.push_back(kLookup[str.data()[i] & 0x0F]);
474 }
475 return OK;
476}
477
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700478status_t NormalizeHex(const std::string& in, std::string& out) {
479 std::string tmp;
480 if (HexToStr(in, tmp)) {
481 return -EINVAL;
482 }
483 return StrToHex(tmp, out);
484}
485
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200486status_t GetBlockDevSize(int fd, uint64_t* size) {
487 if (ioctl(fd, BLKGETSIZE64, size)) {
488 return -errno;
489 }
490
491 return OK;
492}
493
494status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
495 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
496 status_t res = OK;
497
498 if (fd < 0) {
499 return -errno;
500 }
501
502 res = GetBlockDevSize(fd, size);
503
504 close(fd);
505
506 return res;
507}
508
509status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
510 uint64_t size;
511 status_t res = GetBlockDevSize(path, &size);
512
513 if (res != OK) {
514 return res;
515 }
516
517 *nr_sec = size / 512;
518
519 return OK;
520}
521
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700522uint64_t GetFreeBytes(const std::string& path) {
523 struct statvfs sb;
524 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700525 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700526 } else {
527 return -1;
528 }
529}
530
531// TODO: borrowed from frameworks/native/libs/diskusage/ which should
532// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700533static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700534 int64_t blksize = s->st_blksize;
535 // count actual blocks used instead of nominal file size
536 int64_t size = s->st_blocks * 512;
537
538 if (blksize) {
539 /* round up to filesystem block size */
540 size = (size + blksize - 1) & (~(blksize - 1));
541 }
542
543 return size;
544}
545
546// TODO: borrowed from frameworks/native/libs/diskusage/ which should
547// eventually be migrated into system/
548int64_t calculate_dir_size(int dfd) {
549 int64_t size = 0;
550 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700551 DIR* d;
552 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700553
554 d = fdopendir(dfd);
555 if (d == NULL) {
556 close(dfd);
557 return 0;
558 }
559
560 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700561 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700562 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
563 size += stat_size(&s);
564 }
565 if (de->d_type == DT_DIR) {
566 int subfd;
567
568 /* always skip "." and ".." */
569 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700570 if (name[1] == 0) continue;
571 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700572 }
573
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600574 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700575 if (subfd >= 0) {
576 size += calculate_dir_size(subfd);
577 }
578 }
579 }
580 closedir(d);
581 return size;
582}
583
584uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600585 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700586 if (dirfd < 0) {
587 PLOG(WARNING) << "Failed to open " << path;
588 return -1;
589 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700590 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700591 }
592}
593
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700594bool IsFilesystemSupported(const std::string& fsType) {
595 std::string supported;
596 if (!ReadFileToString(kProcFilesystems, &supported)) {
597 PLOG(ERROR) << "Failed to read supported filesystems";
598 return false;
599 }
600 return supported.find(fsType + "\n") != std::string::npos;
601}
602
603status_t WipeBlockDevice(const std::string& path) {
604 status_t res = -1;
605 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200606 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700607
608 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
609 if (fd == -1) {
610 PLOG(ERROR) << "Failed to open " << path;
611 goto done;
612 }
613
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200614 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700615 PLOG(ERROR) << "Failed to determine size of " << path;
616 goto done;
617 }
618
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700619 LOG(INFO) << "About to discard " << range[1] << " on " << path;
620 if (ioctl(fd, BLKDISCARD, &range) == 0) {
621 LOG(INFO) << "Discard success on " << path;
622 res = 0;
623 } else {
624 PLOG(ERROR) << "Discard failure on " << path;
625 }
626
627done:
628 close(fd);
629 return res;
630}
631
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800632static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700633 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800634 return false;
635 } else {
636 return true;
637 }
638}
639
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700640std::string BuildKeyPath(const std::string& partGuid) {
641 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
642}
643
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600644std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700645 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600646}
647
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800648std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700649 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700650}
651
652std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700653 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700654}
655
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600656std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700657 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600658}
659
Jeff Sharkey47695b22016-02-01 17:02:29 -0700660std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700661 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700662}
663
664std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700665 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800666}
667
Calin Juravle79f55a42016-02-17 20:14:46 +0000668// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
669std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700670 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000671}
672
Andreas Huber71cd43f2018-01-22 11:25:29 -0800673std::string BuildDataVendorCePath(userid_t userId) {
674 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
675}
676
677std::string BuildDataVendorDePath(userid_t userId) {
678 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
679}
680
Paul Crowley3b71fc52017-10-09 10:55:21 -0700681std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800682 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700683 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800684 return "/data";
685 } else {
686 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700687 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800688 }
689}
690
Paul Crowley3b71fc52017-10-09 10:55:21 -0700691std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700692 // TODO: unify with installd path generation logic
693 std::string data(BuildDataPath(volumeUuid));
694 return StringPrintf("%s/media/%u", data.c_str(), userId);
695}
696
Paul Crowley3b71fc52017-10-09 10:55:21 -0700697std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800698 // TODO: unify with installd path generation logic
699 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700700 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800701 std::string legacy = StringPrintf("%s/data", data.c_str());
702 struct stat sb;
703 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
704 /* /data/data is dir, return /data/data for legacy system */
705 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800706 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800707 }
cjbaoeb501142017-04-12 00:09:00 +0800708 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800709}
710
Paul Crowley3b71fc52017-10-09 10:55:21 -0700711std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800712 // TODO: unify with installd path generation logic
713 std::string data(BuildDataPath(volumeUuid));
714 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
715}
716
Jeff Sharkey66270a22015-06-24 11:49:24 -0700717dev_t GetDevice(const std::string& path) {
718 struct stat sb;
719 if (stat(path.c_str(), &sb)) {
720 PLOG(WARNING) << "Failed to stat " << path;
721 return 0;
722 } else {
723 return sb.st_dev;
724 }
725}
726
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600727status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700728 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600729
Tom Cherryd6127ef2017-06-15 17:13:56 -0700730 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600731
Tom Cherryd6127ef2017-06-15 17:13:56 -0700732 android::base::SetProperty(kRestoreconString, "");
733 android::base::SetProperty(kRestoreconString, path);
734
735 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600736
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700737 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600738 return OK;
739}
740
Jeff Sharkey3472e522017-10-06 18:02:53 -0600741bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
742 // Shamelessly borrowed from android::base::Readlink()
743 result->clear();
744
745 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
746 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
747 // waste memory to just start there. We add 1 so that we can recognize
748 // whether it actually fit (rather than being truncated to 4095).
749 std::vector<char> buf(4095 + 1);
750 while (true) {
751 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
752 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700753 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600754 // It fit! (If size == buf.size(), it may have been truncated.)
755 if (static_cast<size_t>(size) < buf.size()) {
756 result->assign(&buf[0], size);
757 return true;
758 }
759 // Double our buffer and try again.
760 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900761 }
762}
763
Yu Ning942d4e82016-01-08 17:36:47 +0800764bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700765 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800766}
767
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700768status_t UnmountTree(const std::string& prefix) {
769 FILE* fp = setmntent("/proc/mounts", "r");
770 if (fp == NULL) {
771 PLOG(ERROR) << "Failed to open /proc/mounts";
772 return -errno;
773 }
774
775 // Some volumes can be stacked on each other, so force unmount in
776 // reverse order to give us the best chance of success.
777 std::list<std::string> toUnmount;
778 mntent* mentry;
779 while ((mentry = getmntent(fp)) != NULL) {
780 auto test = std::string(mentry->mnt_dir) + "/";
781 if (android::base::StartsWith(test, prefix)) {
782 toUnmount.push_front(test);
783 }
784 }
785 endmntent(fp);
786
787 for (const auto& path : toUnmount) {
788 if (umount2(path.c_str(), MNT_DETACH)) {
789 PLOG(ERROR) << "Failed to unmount " << path;
790 }
791 }
792 return OK;
793}
794
Paul Crowleycfe39722018-10-30 15:59:24 -0700795// TODO(118708649): fix duplication with init/util.h
796status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
797 android::base::Timer t;
798 while (t.duration() < timeout) {
799 struct stat sb;
800 if (stat(filename, &sb) != -1) {
801 LOG(INFO) << "wait for '" << filename << "' took " << t;
802 return 0;
803 }
804 std::this_thread::sleep_for(10ms);
805 }
806 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
807 return -1;
808}
809
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800810} // namespace vold
811} // namespace android