blob: 484de90862dbbfe28d48e3e2b9fe7c21ff36f1ba [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 "sehandle.h"
18#include "Utils.h"
19#include "Process.h"
Keun-young Park375ac252017-08-02 17:45:48 -070020#include "VolumeManager.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>
Jeff Sharkey3472e522017-10-06 18:02:53 -060025#include <android-base/strings.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080026#include <android-base/stringprintf.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080027#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070028#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070029#include <private/android_filesystem_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080030
Jeff Sharkeyce6a9132015-04-08 21:07:21 -070031#include <mutex>
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>
35#include <stdlib.h>
36#include <sys/mount.h>
37#include <sys/types.h>
38#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070039#include <sys/sysmacros.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080040#include <sys/wait.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070041#include <sys/statvfs.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080042
43#ifndef UMOUNT_NOFOLLOW
44#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
45#endif
46
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070047using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070048using android::base::StringPrintf;
49
Jeff Sharkeydeb24052015-03-02 21:01:40 -080050namespace android {
51namespace vold {
52
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070053security_context_t sBlkidContext = nullptr;
54security_context_t sBlkidUntrustedContext = nullptr;
55security_context_t sFsckContext = nullptr;
56security_context_t sFsckUntrustedContext = nullptr;
57
Jeff Sharkey9c484982015-03-31 10:35:33 -070058static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070059static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070060
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070061static const char* kProcFilesystems = "/proc/filesystems";
62
Jeff Sharkeydeb24052015-03-02 21:01:40 -080063status_t CreateDeviceNode(const std::string& path, dev_t dev) {
64 const char* cpath = path.c_str();
65 status_t res = 0;
66
67 char* secontext = nullptr;
68 if (sehandle) {
69 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
70 setfscreatecon(secontext);
71 }
72 }
73
74 mode_t mode = 0660 | S_IFBLK;
75 if (mknod(cpath, mode, dev) < 0) {
76 if (errno != EEXIST) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070077 PLOG(ERROR) << "Failed to create device node for " << major(dev)
78 << ":" << minor(dev) << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080079 res = -errno;
80 }
81 }
82
83 if (secontext) {
84 setfscreatecon(nullptr);
85 freecon(secontext);
86 }
87
88 return res;
89}
90
91status_t DestroyDeviceNode(const std::string& path) {
92 const char* cpath = path.c_str();
93 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
94 return -errno;
95 } else {
96 return OK;
97 }
98}
99
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700100status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
101 const char* cpath = path.c_str();
102
103 char* secontext = nullptr;
104 if (sehandle) {
105 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
106 setfscreatecon(secontext);
107 }
108 }
109
110 int res = fs_prepare_dir(cpath, mode, uid, gid);
111
112 if (secontext) {
113 setfscreatecon(nullptr);
114 freecon(secontext);
115 }
116
117 if (res == 0) {
118 return OK;
119 } else {
120 return -errno;
121 }
122}
123
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800124status_t ForceUnmount(const std::string& path) {
125 const char* cpath = path.c_str();
126 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
127 return OK;
128 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700129 // Apps might still be handling eject request, so wait before
130 // we start sending signals
Keun-young Park375ac252017-08-02 17:45:48 -0700131 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700132
Jeff Sharkey3472e522017-10-06 18:02:53 -0600133 KillProcessesWithOpenFiles(path, SIGINT);
Keun-young Park375ac252017-08-02 17:45:48 -0700134 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700135 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
136 return OK;
137 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700138
Jeff Sharkey3472e522017-10-06 18:02:53 -0600139 KillProcessesWithOpenFiles(path, SIGTERM);
Keun-young Park375ac252017-08-02 17:45:48 -0700140 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800141 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
142 return OK;
143 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700144
Jeff Sharkey3472e522017-10-06 18:02:53 -0600145 KillProcessesWithOpenFiles(path, SIGKILL);
Keun-young Park375ac252017-08-02 17:45:48 -0700146 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700147 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
148 return OK;
149 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700150
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800151 return -errno;
152}
153
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700154status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600155 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700156 return OK;
157 }
Keun-young Park375ac252017-08-02 17:45:48 -0700158 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700159
Jeff Sharkey3472e522017-10-06 18:02:53 -0600160 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700161 return OK;
162 }
Keun-young Park375ac252017-08-02 17:45:48 -0700163 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700164
Jeff Sharkey3472e522017-10-06 18:02:53 -0600165 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700166 return OK;
167 }
Keun-young Park375ac252017-08-02 17:45:48 -0700168 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700169
170 // Send SIGKILL a second time to determine if we've
171 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600172 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700173 return OK;
174 }
175 PLOG(ERROR) << "Failed to kill processes using " << path;
176 return -EBUSY;
177}
178
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700179status_t BindMount(const std::string& source, const std::string& target) {
180 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
181 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
182 return -errno;
183 }
184 return OK;
185}
186
Jeff Sharkey3472e522017-10-06 18:02:53 -0600187bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
188 auto qual = key + "=\"";
189 auto start = raw.find(qual);
190 if (start > 0 && raw[start - 1] != ' ') {
191 start = raw.find(qual, start + 1);
192 }
193
194 if (start == std::string::npos) return false;
195 start += qual.length();
196
197 auto end = raw.find("\"", start);
198 if (end == std::string::npos) return false;
199
200 *value = raw.substr(start, end - start);
201 return true;
202}
203
204static status_t readMetadata(const std::string& path, std::string* fsType,
205 std::string* fsUuid, std::string* fsLabel, bool untrusted) {
206 fsType->clear();
207 fsUuid->clear();
208 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700209
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700210 std::vector<std::string> cmd;
211 cmd.push_back(kBlkidPath);
212 cmd.push_back("-c");
213 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700214 cmd.push_back("-s");
215 cmd.push_back("TYPE");
216 cmd.push_back("-s");
217 cmd.push_back("UUID");
218 cmd.push_back("-s");
219 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700220 cmd.push_back(path);
221
222 std::vector<std::string> output;
223 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
224 if (res != OK) {
225 LOG(WARNING) << "blkid failed to identify " << path;
226 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700227 }
228
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700229 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700230 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600231 FindValue(line, "TYPE", fsType);
232 FindValue(line, "UUID", fsUuid);
233 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700234 }
235
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700236 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700237}
238
Jeff Sharkey3472e522017-10-06 18:02:53 -0600239status_t ReadMetadata(const std::string& path, std::string* fsType,
240 std::string* fsUuid, std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700241 return readMetadata(path, fsType, fsUuid, fsLabel, false);
242}
243
Jeff Sharkey3472e522017-10-06 18:02:53 -0600244status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType,
245 std::string* fsUuid, std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700246 return readMetadata(path, fsType, fsUuid, fsLabel, true);
247}
248
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700249status_t ForkExecvp(const std::vector<std::string>& args) {
250 return ForkExecvp(args, nullptr);
251}
252
253status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
254 size_t argc = args.size();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700255 char** argv = (char**) calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700256 for (size_t i = 0; i < argc; i++) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700257 argv[i] = (char*) args[i].c_str();
258 if (i == 0) {
259 LOG(VERBOSE) << args[i];
260 } else {
261 LOG(VERBOSE) << " " << args[i];
262 }
263 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700264
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700265 if (setexeccon(context)) {
266 LOG(ERROR) << "Failed to setexeccon";
267 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700268 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700269 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
270 if (setexeccon(nullptr)) {
271 LOG(ERROR) << "Failed to setexeccon";
272 abort();
273 }
274
Jeff Sharkey9c484982015-03-31 10:35:33 -0700275 free(argv);
276 return res;
277}
278
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700279status_t ForkExecvp(const std::vector<std::string>& args,
280 std::vector<std::string>& output) {
281 return ForkExecvp(args, output, nullptr);
282}
283
284status_t ForkExecvp(const std::vector<std::string>& args,
285 std::vector<std::string>& output, security_context_t context) {
286 std::string cmd;
287 for (size_t i = 0; i < args.size(); i++) {
288 cmd += args[i] + " ";
289 if (i == 0) {
290 LOG(VERBOSE) << args[i];
291 } else {
292 LOG(VERBOSE) << " " << args[i];
293 }
294 }
295 output.clear();
296
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700297 if (setexeccon(context)) {
298 LOG(ERROR) << "Failed to setexeccon";
299 abort();
300 }
Jeff Sharkey32ebb732017-03-27 16:18:50 -0600301 FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700302 if (setexeccon(nullptr)) {
303 LOG(ERROR) << "Failed to setexeccon";
304 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700305 }
306
307 if (!fp) {
308 PLOG(ERROR) << "Failed to popen " << cmd;
309 return -errno;
310 }
311 char line[1024];
312 while (fgets(line, sizeof(line), fp) != nullptr) {
313 LOG(VERBOSE) << line;
314 output.push_back(std::string(line));
315 }
316 if (pclose(fp) != 0) {
317 PLOG(ERROR) << "Failed to pclose " << cmd;
318 return -errno;
319 }
320
321 return OK;
322}
323
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700324pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
325 size_t argc = args.size();
326 char** argv = (char**) calloc(argc + 1, sizeof(char*));
327 for (size_t i = 0; i < argc; i++) {
328 argv[i] = (char*) args[i].c_str();
329 if (i == 0) {
330 LOG(VERBOSE) << args[i];
331 } else {
332 LOG(VERBOSE) << " " << args[i];
333 }
334 }
335
336 pid_t pid = fork();
337 if (pid == 0) {
338 close(STDIN_FILENO);
339 close(STDOUT_FILENO);
340 close(STDERR_FILENO);
341
342 if (execvp(argv[0], argv)) {
343 PLOG(ERROR) << "Failed to exec";
344 }
345
346 _exit(1);
347 }
348
349 if (pid == -1) {
350 PLOG(ERROR) << "Failed to exec";
351 }
352
353 free(argv);
354 return pid;
355}
356
Jeff Sharkey9c484982015-03-31 10:35:33 -0700357status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100358 out.resize(bytes);
359 return ReadRandomBytes(bytes, &out[0]);
360}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700361
Pavel Grafove2e2d302017-08-01 17:15:53 +0100362status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700363 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
364 if (fd == -1) {
365 return -errno;
366 }
367
Jeff Sharkey9c484982015-03-31 10:35:33 -0700368 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100369 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700370 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100371 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700372 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700373 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700374
375 if (bytes == 0) {
376 return OK;
377 } else {
378 return -EIO;
379 }
380}
381
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600382status_t GenerateRandomUuid(std::string& out) {
383 status_t res = ReadRandomBytes(16, out);
384 if (res == OK) {
385 out[6] &= 0x0f; /* clear version */
386 out[6] |= 0x40; /* set to version 4 */
387 out[8] &= 0x3f; /* clear variant */
388 out[8] |= 0x80; /* set to IETF variant */
389 }
390 return res;
391}
392
Jeff Sharkey9c484982015-03-31 10:35:33 -0700393status_t HexToStr(const std::string& hex, std::string& str) {
394 str.clear();
395 bool even = true;
396 char cur = 0;
397 for (size_t i = 0; i < hex.size(); i++) {
398 int val = 0;
399 switch (hex[i]) {
400 case ' ': case '-': case ':': continue;
401 case 'f': case 'F': val = 15; break;
402 case 'e': case 'E': val = 14; break;
403 case 'd': case 'D': val = 13; break;
404 case 'c': case 'C': val = 12; break;
405 case 'b': case 'B': val = 11; break;
406 case 'a': case 'A': val = 10; break;
407 case '9': val = 9; break;
408 case '8': val = 8; break;
409 case '7': val = 7; break;
410 case '6': val = 6; break;
411 case '5': val = 5; break;
412 case '4': val = 4; break;
413 case '3': val = 3; break;
414 case '2': val = 2; break;
415 case '1': val = 1; break;
416 case '0': val = 0; break;
417 default: return -EINVAL;
418 }
419
420 if (even) {
421 cur = val << 4;
422 } else {
423 cur += val;
424 str.push_back(cur);
425 cur = 0;
426 }
427 even = !even;
428 }
429 return even ? OK : -EINVAL;
430}
431
432static const char* kLookup = "0123456789abcdef";
433
434status_t StrToHex(const std::string& str, std::string& hex) {
435 hex.clear();
436 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700437 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700438 hex.push_back(kLookup[str[i] & 0x0F]);
439 }
440 return OK;
441}
442
Pavel Grafove2e2d302017-08-01 17:15:53 +0100443status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
444 hex.clear();
445 for (size_t i = 0; i < str.size(); i++) {
446 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
447 hex.push_back(kLookup[str.data()[i] & 0x0F]);
448 }
449 return OK;
450}
451
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700452status_t NormalizeHex(const std::string& in, std::string& out) {
453 std::string tmp;
454 if (HexToStr(in, tmp)) {
455 return -EINVAL;
456 }
457 return StrToHex(tmp, out);
458}
459
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700460uint64_t GetFreeBytes(const std::string& path) {
461 struct statvfs sb;
462 if (statvfs(path.c_str(), &sb) == 0) {
Jeff Sharkeya0220a52017-04-03 17:11:45 -0600463 return (uint64_t) sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700464 } else {
465 return -1;
466 }
467}
468
469// TODO: borrowed from frameworks/native/libs/diskusage/ which should
470// eventually be migrated into system/
471static int64_t stat_size(struct stat *s) {
472 int64_t blksize = s->st_blksize;
473 // count actual blocks used instead of nominal file size
474 int64_t size = s->st_blocks * 512;
475
476 if (blksize) {
477 /* round up to filesystem block size */
478 size = (size + blksize - 1) & (~(blksize - 1));
479 }
480
481 return size;
482}
483
484// TODO: borrowed from frameworks/native/libs/diskusage/ which should
485// eventually be migrated into system/
486int64_t calculate_dir_size(int dfd) {
487 int64_t size = 0;
488 struct stat s;
489 DIR *d;
490 struct dirent *de;
491
492 d = fdopendir(dfd);
493 if (d == NULL) {
494 close(dfd);
495 return 0;
496 }
497
498 while ((de = readdir(d))) {
499 const char *name = de->d_name;
500 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
501 size += stat_size(&s);
502 }
503 if (de->d_type == DT_DIR) {
504 int subfd;
505
506 /* always skip "." and ".." */
507 if (name[0] == '.') {
508 if (name[1] == 0)
509 continue;
510 if ((name[1] == '.') && (name[2] == 0))
511 continue;
512 }
513
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600514 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700515 if (subfd >= 0) {
516 size += calculate_dir_size(subfd);
517 }
518 }
519 }
520 closedir(d);
521 return size;
522}
523
524uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600525 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700526 if (dirfd < 0) {
527 PLOG(WARNING) << "Failed to open " << path;
528 return -1;
529 } else {
530 uint64_t res = calculate_dir_size(dirfd);
531 close(dirfd);
532 return res;
533 }
534}
535
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700536bool IsFilesystemSupported(const std::string& fsType) {
537 std::string supported;
538 if (!ReadFileToString(kProcFilesystems, &supported)) {
539 PLOG(ERROR) << "Failed to read supported filesystems";
540 return false;
541 }
542 return supported.find(fsType + "\n") != std::string::npos;
543}
544
545status_t WipeBlockDevice(const std::string& path) {
546 status_t res = -1;
547 const char* c_path = path.c_str();
548 unsigned long nr_sec = 0;
549 unsigned long long range[2];
550
551 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
552 if (fd == -1) {
553 PLOG(ERROR) << "Failed to open " << path;
554 goto done;
555 }
556
caozhiyuan9102b0b2015-10-29 16:39:00 +0800557 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700558 PLOG(ERROR) << "Failed to determine size of " << path;
559 goto done;
560 }
561
562 range[0] = 0;
563 range[1] = (unsigned long long) nr_sec * 512;
564
565 LOG(INFO) << "About to discard " << range[1] << " on " << path;
566 if (ioctl(fd, BLKDISCARD, &range) == 0) {
567 LOG(INFO) << "Discard success on " << path;
568 res = 0;
569 } else {
570 PLOG(ERROR) << "Discard failure on " << path;
571 }
572
573done:
574 close(fd);
575 return res;
576}
577
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800578static bool isValidFilename(const std::string& name) {
579 if (name.empty() || (name == ".") || (name == "..")
580 || (name.find('/') != std::string::npos)) {
581 return false;
582 } else {
583 return true;
584 }
585}
586
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700587std::string BuildKeyPath(const std::string& partGuid) {
588 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
589}
590
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600591std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700592 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600593}
594
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800595std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700596 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700597}
598
599std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700600 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700601}
602
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600603std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700604 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600605}
606
Jeff Sharkey47695b22016-02-01 17:02:29 -0700607std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700608 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700609}
610
611std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700612 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800613}
614
Calin Juravle79f55a42016-02-17 20:14:46 +0000615// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
616std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700617 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000618}
619
Paul Crowley3b71fc52017-10-09 10:55:21 -0700620std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800621 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700622 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800623 return "/data";
624 } else {
625 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700626 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800627 }
628}
629
Paul Crowley3b71fc52017-10-09 10:55:21 -0700630std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700631 // TODO: unify with installd path generation logic
632 std::string data(BuildDataPath(volumeUuid));
633 return StringPrintf("%s/media/%u", data.c_str(), userId);
634}
635
Paul Crowley3b71fc52017-10-09 10:55:21 -0700636std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800637 // TODO: unify with installd path generation logic
638 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700639 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800640 std::string legacy = StringPrintf("%s/data", data.c_str());
641 struct stat sb;
642 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
643 /* /data/data is dir, return /data/data for legacy system */
644 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800645 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800646 }
cjbaoeb501142017-04-12 00:09:00 +0800647 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800648}
649
Paul Crowley3b71fc52017-10-09 10:55:21 -0700650std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800651 // TODO: unify with installd path generation logic
652 std::string data(BuildDataPath(volumeUuid));
653 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
654}
655
Jeff Sharkey66270a22015-06-24 11:49:24 -0700656dev_t GetDevice(const std::string& path) {
657 struct stat sb;
658 if (stat(path.c_str(), &sb)) {
659 PLOG(WARNING) << "Failed to stat " << path;
660 return 0;
661 } else {
662 return sb.st_dev;
663 }
664}
665
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600666status_t RestoreconRecursive(const std::string& path) {
667 LOG(VERBOSE) << "Starting restorecon of " << path;
668
Tom Cherryd6127ef2017-06-15 17:13:56 -0700669 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600670
Tom Cherryd6127ef2017-06-15 17:13:56 -0700671 android::base::SetProperty(kRestoreconString, "");
672 android::base::SetProperty(kRestoreconString, path);
673
674 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600675
676 LOG(VERBOSE) << "Finished restorecon of " << path;
677 return OK;
678}
679
Jeff Sharkey3472e522017-10-06 18:02:53 -0600680bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
681 // Shamelessly borrowed from android::base::Readlink()
682 result->clear();
683
684 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
685 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
686 // waste memory to just start there. We add 1 so that we can recognize
687 // whether it actually fit (rather than being truncated to 4095).
688 std::vector<char> buf(4095 + 1);
689 while (true) {
690 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
691 // Unrecoverable error?
692 if (size == -1)
693 return false;
694 // It fit! (If size == buf.size(), it may have been truncated.)
695 if (static_cast<size_t>(size) < buf.size()) {
696 result->assign(&buf[0], size);
697 return true;
698 }
699 // Double our buffer and try again.
700 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900701 }
702}
703
Yu Ning942d4e82016-01-08 17:36:47 +0800704bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700705 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800706}
707
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800708} // namespace vold
709} // namespace android