blob: f7cb01f427edc78d4185f5504289955047a6d3a2 [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 Crowleyc5e3a522018-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>
Jeff Sharkey3472e522017-10-06 18:02:53 -060026#include <android-base/strings.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080027#include <android-base/stringprintf.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 Sharkeyce6a9132015-04-08 21:07:21 -070032#include <mutex>
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>
36#include <stdlib.h>
37#include <sys/mount.h>
38#include <sys/types.h>
39#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070040#include <sys/sysmacros.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080041#include <sys/wait.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070042#include <sys/statvfs.h>
LuK13374d530c62018-03-06 11:31:14 +010043#include <thread>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080044
Paul Crowleyc5e3a522018-10-30 15:59:24 -070045#include <thread>
46
Jeff Sharkeydeb24052015-03-02 21:01:40 -080047#ifndef UMOUNT_NOFOLLOW
48#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
49#endif
50
Paul Crowleyc5e3a522018-10-30 15:59:24 -070051using namespace std::chrono_literals;
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070052using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070053using android::base::StringPrintf;
54
LuK13374d530c62018-03-06 11:31:14 +010055using namespace std::chrono_literals;
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) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070091 PLOG(ERROR) << "Failed to create device node for " << major(dev)
92 << ":" << minor(dev) << " 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
219static status_t readMetadata(const std::string& path, std::string* fsType,
220 std::string* fsUuid, std::string* fsLabel, bool untrusted) {
221 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
Jeff Sharkey3472e522017-10-06 18:02:53 -0600254status_t ReadMetadata(const std::string& path, std::string* fsType,
255 std::string* fsUuid, std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700256 return readMetadata(path, fsType, fsUuid, fsLabel, false);
257}
258
Jeff Sharkey3472e522017-10-06 18:02:53 -0600259status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType,
260 std::string* fsUuid, 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();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700271 char** argv = (char**) calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700272 for (size_t i = 0; i < argc; i++) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700273 argv[i] = (char*) args[i].c_str();
274 if (i == 0) {
275 LOG(VERBOSE) << args[i];
276 } else {
277 LOG(VERBOSE) << " " << args[i];
278 }
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
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700299status_t ForkExecvp(const std::vector<std::string>& args,
300 std::vector<std::string>& output) {
301 return ForkExecvp(args, output, nullptr);
302}
303
304status_t ForkExecvp(const std::vector<std::string>& args,
305 std::vector<std::string>& output, security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600306 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700307 std::string cmd;
308 for (size_t i = 0; i < args.size(); i++) {
309 cmd += args[i] + " ";
310 if (i == 0) {
311 LOG(VERBOSE) << args[i];
312 } else {
313 LOG(VERBOSE) << " " << args[i];
314 }
315 }
316 output.clear();
317
Paul Crowley82b41ff2017-10-20 08:17:54 -0700318 if (context) {
319 if (setexeccon(context)) {
320 LOG(ERROR) << "Failed to setexeccon";
321 abort();
322 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700323 }
Jeff Sharkey32ebb732017-03-27 16:18:50 -0600324 FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
Paul Crowley82b41ff2017-10-20 08:17:54 -0700325 if (context) {
326 if (setexeccon(nullptr)) {
327 LOG(ERROR) << "Failed to setexeccon";
328 abort();
329 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700330 }
331
332 if (!fp) {
333 PLOG(ERROR) << "Failed to popen " << cmd;
334 return -errno;
335 }
336 char line[1024];
337 while (fgets(line, sizeof(line), fp) != nullptr) {
338 LOG(VERBOSE) << line;
339 output.push_back(std::string(line));
340 }
341 if (pclose(fp) != 0) {
342 PLOG(ERROR) << "Failed to pclose " << cmd;
343 return -errno;
344 }
345
346 return OK;
347}
348
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700349pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
350 size_t argc = args.size();
351 char** argv = (char**) calloc(argc + 1, sizeof(char*));
352 for (size_t i = 0; i < argc; i++) {
353 argv[i] = (char*) args[i].c_str();
354 if (i == 0) {
355 LOG(VERBOSE) << args[i];
356 } else {
357 LOG(VERBOSE) << " " << args[i];
358 }
359 }
360
361 pid_t pid = fork();
362 if (pid == 0) {
363 close(STDIN_FILENO);
364 close(STDOUT_FILENO);
365 close(STDERR_FILENO);
366
367 if (execvp(argv[0], argv)) {
368 PLOG(ERROR) << "Failed to exec";
369 }
370
371 _exit(1);
372 }
373
374 if (pid == -1) {
375 PLOG(ERROR) << "Failed to exec";
376 }
377
378 free(argv);
379 return pid;
380}
381
Jeff Sharkey9c484982015-03-31 10:35:33 -0700382status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100383 out.resize(bytes);
384 return ReadRandomBytes(bytes, &out[0]);
385}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700386
Pavel Grafove2e2d302017-08-01 17:15:53 +0100387status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700388 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
389 if (fd == -1) {
390 return -errno;
391 }
392
Jeff Sharkey9c484982015-03-31 10:35:33 -0700393 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100394 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700395 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100396 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700397 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700398 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700399
400 if (bytes == 0) {
401 return OK;
402 } else {
403 return -EIO;
404 }
405}
406
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600407status_t GenerateRandomUuid(std::string& out) {
408 status_t res = ReadRandomBytes(16, out);
409 if (res == OK) {
410 out[6] &= 0x0f; /* clear version */
411 out[6] |= 0x40; /* set to version 4 */
412 out[8] &= 0x3f; /* clear variant */
413 out[8] |= 0x80; /* set to IETF variant */
414 }
415 return res;
416}
417
Jeff Sharkey9c484982015-03-31 10:35:33 -0700418status_t HexToStr(const std::string& hex, std::string& str) {
419 str.clear();
420 bool even = true;
421 char cur = 0;
422 for (size_t i = 0; i < hex.size(); i++) {
423 int val = 0;
424 switch (hex[i]) {
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 }
444
445 if (even) {
446 cur = val << 4;
447 } else {
448 cur += val;
449 str.push_back(cur);
450 cur = 0;
451 }
452 even = !even;
453 }
454 return even ? OK : -EINVAL;
455}
456
457static const char* kLookup = "0123456789abcdef";
458
459status_t StrToHex(const std::string& str, std::string& hex) {
460 hex.clear();
461 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700462 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700463 hex.push_back(kLookup[str[i] & 0x0F]);
464 }
465 return OK;
466}
467
Pavel Grafove2e2d302017-08-01 17:15:53 +0100468status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
469 hex.clear();
470 for (size_t i = 0; i < str.size(); i++) {
471 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
472 hex.push_back(kLookup[str.data()[i] & 0x0F]);
473 }
474 return OK;
475}
476
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700477status_t NormalizeHex(const std::string& in, std::string& out) {
478 std::string tmp;
479 if (HexToStr(in, tmp)) {
480 return -EINVAL;
481 }
482 return StrToHex(tmp, out);
483}
484
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700485uint64_t GetFreeBytes(const std::string& path) {
486 struct statvfs sb;
487 if (statvfs(path.c_str(), &sb) == 0) {
Jeff Sharkeya0220a52017-04-03 17:11:45 -0600488 return (uint64_t) sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700489 } else {
490 return -1;
491 }
492}
493
494// TODO: borrowed from frameworks/native/libs/diskusage/ which should
495// eventually be migrated into system/
496static int64_t stat_size(struct stat *s) {
497 int64_t blksize = s->st_blksize;
498 // count actual blocks used instead of nominal file size
499 int64_t size = s->st_blocks * 512;
500
501 if (blksize) {
502 /* round up to filesystem block size */
503 size = (size + blksize - 1) & (~(blksize - 1));
504 }
505
506 return size;
507}
508
509// TODO: borrowed from frameworks/native/libs/diskusage/ which should
510// eventually be migrated into system/
511int64_t calculate_dir_size(int dfd) {
512 int64_t size = 0;
513 struct stat s;
514 DIR *d;
515 struct dirent *de;
516
517 d = fdopendir(dfd);
518 if (d == NULL) {
519 close(dfd);
520 return 0;
521 }
522
523 while ((de = readdir(d))) {
524 const char *name = de->d_name;
525 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
526 size += stat_size(&s);
527 }
528 if (de->d_type == DT_DIR) {
529 int subfd;
530
531 /* always skip "." and ".." */
532 if (name[0] == '.') {
533 if (name[1] == 0)
534 continue;
535 if ((name[1] == '.') && (name[2] == 0))
536 continue;
537 }
538
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600539 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700540 if (subfd >= 0) {
541 size += calculate_dir_size(subfd);
542 }
543 }
544 }
545 closedir(d);
546 return size;
547}
548
549uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600550 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700551 if (dirfd < 0) {
552 PLOG(WARNING) << "Failed to open " << path;
553 return -1;
554 } else {
555 uint64_t res = calculate_dir_size(dirfd);
556 close(dirfd);
557 return res;
558 }
559}
560
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700561bool IsFilesystemSupported(const std::string& fsType) {
562 std::string supported;
563 if (!ReadFileToString(kProcFilesystems, &supported)) {
564 PLOG(ERROR) << "Failed to read supported filesystems";
565 return false;
566 }
Dan Pasanend1952662015-10-27 22:52:37 -0500567
568 /* fuse filesystems */
xyyx8772c252018-09-30 12:49:36 +0800569 supported.append("fuse\tntfs\n"
570 "fuse\texfat\n");
Dan Pasanend1952662015-10-27 22:52:37 -0500571
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700572 return supported.find(fsType + "\n") != std::string::npos;
573}
574
575status_t WipeBlockDevice(const std::string& path) {
576 status_t res = -1;
577 const char* c_path = path.c_str();
578 unsigned long nr_sec = 0;
579 unsigned long long range[2];
580
581 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
582 if (fd == -1) {
583 PLOG(ERROR) << "Failed to open " << path;
584 goto done;
585 }
586
caozhiyuan9102b0b2015-10-29 16:39:00 +0800587 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700588 PLOG(ERROR) << "Failed to determine size of " << path;
589 goto done;
590 }
591
592 range[0] = 0;
593 range[1] = (unsigned long long) nr_sec * 512;
594
595 LOG(INFO) << "About to discard " << range[1] << " on " << path;
596 if (ioctl(fd, BLKDISCARD, &range) == 0) {
597 LOG(INFO) << "Discard success on " << path;
598 res = 0;
599 } else {
600 PLOG(ERROR) << "Discard failure on " << path;
601 }
602
603done:
604 close(fd);
605 return res;
606}
607
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800608static bool isValidFilename(const std::string& name) {
609 if (name.empty() || (name == ".") || (name == "..")
610 || (name.find('/') != std::string::npos)) {
611 return false;
612 } else {
613 return true;
614 }
615}
616
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700617std::string BuildKeyPath(const std::string& partGuid) {
618 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
619}
620
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600621std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700622 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600623}
624
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800625std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700626 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700627}
628
629std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700630 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700631}
632
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600633std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700634 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600635}
636
Jeff Sharkey47695b22016-02-01 17:02:29 -0700637std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700638 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700639}
640
641std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700642 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800643}
644
Calin Juravle79f55a42016-02-17 20:14:46 +0000645// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
646std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700647 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000648}
649
Andreas Huber71cd43f2018-01-22 11:25:29 -0800650std::string BuildDataVendorCePath(userid_t userId) {
651 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
652}
653
654std::string BuildDataVendorDePath(userid_t userId) {
655 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
656}
657
Paul Crowley3b71fc52017-10-09 10:55:21 -0700658std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800659 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700660 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800661 return "/data";
662 } else {
663 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700664 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800665 }
666}
667
Paul Crowley3b71fc52017-10-09 10:55:21 -0700668std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700669 // TODO: unify with installd path generation logic
670 std::string data(BuildDataPath(volumeUuid));
671 return StringPrintf("%s/media/%u", data.c_str(), userId);
672}
673
Paul Crowley3b71fc52017-10-09 10:55:21 -0700674std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800675 // TODO: unify with installd path generation logic
676 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700677 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800678 std::string legacy = StringPrintf("%s/data", data.c_str());
679 struct stat sb;
680 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
681 /* /data/data is dir, return /data/data for legacy system */
682 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800683 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800684 }
cjbaoeb501142017-04-12 00:09:00 +0800685 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800686}
687
Paul Crowley3b71fc52017-10-09 10:55:21 -0700688std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800689 // TODO: unify with installd path generation logic
690 std::string data(BuildDataPath(volumeUuid));
691 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
692}
693
Jeff Sharkey66270a22015-06-24 11:49:24 -0700694dev_t GetDevice(const std::string& path) {
695 struct stat sb;
696 if (stat(path.c_str(), &sb)) {
697 PLOG(WARNING) << "Failed to stat " << path;
698 return 0;
699 } else {
700 return sb.st_dev;
701 }
702}
703
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600704status_t RestoreconRecursive(const std::string& path) {
705 LOG(VERBOSE) << "Starting restorecon of " << path;
706
Tom Cherryd6127ef2017-06-15 17:13:56 -0700707 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600708
Tom Cherryd6127ef2017-06-15 17:13:56 -0700709 android::base::SetProperty(kRestoreconString, "");
710 android::base::SetProperty(kRestoreconString, path);
711
712 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600713
714 LOG(VERBOSE) << "Finished restorecon of " << path;
715 return OK;
716}
717
Jeff Sharkey3472e522017-10-06 18:02:53 -0600718bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
719 // Shamelessly borrowed from android::base::Readlink()
720 result->clear();
721
722 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
723 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
724 // waste memory to just start there. We add 1 so that we can recognize
725 // whether it actually fit (rather than being truncated to 4095).
726 std::vector<char> buf(4095 + 1);
727 while (true) {
728 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
729 // Unrecoverable error?
730 if (size == -1)
731 return false;
732 // It fit! (If size == buf.size(), it may have been truncated.)
733 if (static_cast<size_t>(size) < buf.size()) {
734 result->assign(&buf[0], size);
735 return true;
736 }
737 // Double our buffer and try again.
738 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900739 }
740}
741
LuK13374d530c62018-03-06 11:31:14 +0100742bool WaitForFile(const std::string& filename,
743 const std::chrono::milliseconds relativeTimeout) {
744 auto startTime = std::chrono::steady_clock::now();
745
746 while (true) {
747 if (!access(filename.c_str(), F_OK) || errno != ENOENT) {
748 return true;
749 }
750
751 std::this_thread::sleep_for(50ms);
752
753 auto now = std::chrono::steady_clock::now();
754 auto timeElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime);
755 if (timeElapsed > relativeTimeout) return false;
756 }
757}
758
Yu Ning942d4e82016-01-08 17:36:47 +0800759bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700760 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800761}
762
Paul Crowleyc5e3a522018-10-30 15:59:24 -0700763// TODO(118708649): fix duplication with init/util.h
764status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
765 android::base::Timer t;
766 while (t.duration() < timeout) {
767 struct stat sb;
768 if (stat(filename, &sb) != -1) {
769 LOG(INFO) << "wait for '" << filename << "' took " << t;
770 return 0;
771 }
772 std::this_thread::sleep_for(10ms);
773 }
774 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
775 return -1;
776}
777
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800778} // namespace vold
779} // namespace android