blob: 1f6ff21bd87eb74540d14292056d882c3c35de39 [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>
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
Paul Crowley56292ef2017-10-20 08:07:53 -070058bool sSleepOnUnmount = true;
59
Jeff Sharkey9c484982015-03-31 10:35:33 -070060static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070061static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070062
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070063static const char* kProcFilesystems = "/proc/filesystems";
64
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060065// Lock used to protect process-level SELinux changes from racing with each
66// other between multiple threads.
67static std::mutex kSecurityLock;
68
Jeff Sharkeydeb24052015-03-02 21:01:40 -080069status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060070 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080071 const char* cpath = path.c_str();
72 status_t res = 0;
73
74 char* secontext = nullptr;
75 if (sehandle) {
76 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
77 setfscreatecon(secontext);
78 }
79 }
80
81 mode_t mode = 0660 | S_IFBLK;
82 if (mknod(cpath, mode, dev) < 0) {
83 if (errno != EEXIST) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070084 PLOG(ERROR) << "Failed to create device node for " << major(dev)
85 << ":" << minor(dev) << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080086 res = -errno;
87 }
88 }
89
90 if (secontext) {
91 setfscreatecon(nullptr);
92 freecon(secontext);
93 }
94
95 return res;
96}
97
98status_t DestroyDeviceNode(const std::string& path) {
99 const char* cpath = path.c_str();
100 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
101 return -errno;
102 } else {
103 return OK;
104 }
105}
106
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700107status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600108 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700109 const char* cpath = path.c_str();
110
111 char* secontext = nullptr;
112 if (sehandle) {
113 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
114 setfscreatecon(secontext);
115 }
116 }
117
118 int res = fs_prepare_dir(cpath, mode, uid, gid);
119
120 if (secontext) {
121 setfscreatecon(nullptr);
122 freecon(secontext);
123 }
124
125 if (res == 0) {
126 return OK;
127 } else {
128 return -errno;
129 }
130}
131
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800132status_t ForceUnmount(const std::string& path) {
133 const char* cpath = path.c_str();
134 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
135 return OK;
136 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700137 // Apps might still be handling eject request, so wait before
138 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700139 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700140
Jeff Sharkey3472e522017-10-06 18:02:53 -0600141 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700142 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700143 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
144 return OK;
145 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700146
Jeff Sharkey3472e522017-10-06 18:02:53 -0600147 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700148 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800149 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
150 return OK;
151 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700152
Jeff Sharkey3472e522017-10-06 18:02:53 -0600153 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700154 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700155 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
156 return OK;
157 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700158
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800159 return -errno;
160}
161
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700162status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600163 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700164 return OK;
165 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700166 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700167
Jeff Sharkey3472e522017-10-06 18:02:53 -0600168 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700169 return OK;
170 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700171 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700172
Jeff Sharkey3472e522017-10-06 18:02:53 -0600173 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700174 return OK;
175 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700176 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700177
178 // Send SIGKILL a second time to determine if we've
179 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600180 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700181 return OK;
182 }
183 PLOG(ERROR) << "Failed to kill processes using " << path;
184 return -EBUSY;
185}
186
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700187status_t BindMount(const std::string& source, const std::string& target) {
188 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
189 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
190 return -errno;
191 }
192 return OK;
193}
194
Jeff Sharkey3472e522017-10-06 18:02:53 -0600195bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
196 auto qual = key + "=\"";
197 auto start = raw.find(qual);
198 if (start > 0 && raw[start - 1] != ' ') {
199 start = raw.find(qual, start + 1);
200 }
201
202 if (start == std::string::npos) return false;
203 start += qual.length();
204
205 auto end = raw.find("\"", start);
206 if (end == std::string::npos) return false;
207
208 *value = raw.substr(start, end - start);
209 return true;
210}
211
212static status_t readMetadata(const std::string& path, std::string* fsType,
213 std::string* fsUuid, std::string* fsLabel, bool untrusted) {
214 fsType->clear();
215 fsUuid->clear();
216 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700217
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700218 std::vector<std::string> cmd;
219 cmd.push_back(kBlkidPath);
220 cmd.push_back("-c");
221 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700222 cmd.push_back("-s");
223 cmd.push_back("TYPE");
224 cmd.push_back("-s");
225 cmd.push_back("UUID");
226 cmd.push_back("-s");
227 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700228 cmd.push_back(path);
229
230 std::vector<std::string> output;
231 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
232 if (res != OK) {
233 LOG(WARNING) << "blkid failed to identify " << path;
234 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700235 }
236
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700237 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700238 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600239 FindValue(line, "TYPE", fsType);
240 FindValue(line, "UUID", fsUuid);
241 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700242 }
243
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700244 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700245}
246
Jeff Sharkey3472e522017-10-06 18:02:53 -0600247status_t ReadMetadata(const std::string& path, std::string* fsType,
248 std::string* fsUuid, std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700249 return readMetadata(path, fsType, fsUuid, fsLabel, false);
250}
251
Jeff Sharkey3472e522017-10-06 18:02:53 -0600252status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType,
253 std::string* fsUuid, std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700254 return readMetadata(path, fsType, fsUuid, fsLabel, true);
255}
256
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700257status_t ForkExecvp(const std::vector<std::string>& args) {
258 return ForkExecvp(args, nullptr);
259}
260
261status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600262 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700263 size_t argc = args.size();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700264 char** argv = (char**) calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700265 for (size_t i = 0; i < argc; i++) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700266 argv[i] = (char*) args[i].c_str();
267 if (i == 0) {
268 LOG(VERBOSE) << args[i];
269 } else {
270 LOG(VERBOSE) << " " << args[i];
271 }
272 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700273
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700274 if (setexeccon(context)) {
275 LOG(ERROR) << "Failed to setexeccon";
276 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700277 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700278 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
279 if (setexeccon(nullptr)) {
280 LOG(ERROR) << "Failed to setexeccon";
281 abort();
282 }
283
Jeff Sharkey9c484982015-03-31 10:35:33 -0700284 free(argv);
285 return res;
286}
287
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700288status_t ForkExecvp(const std::vector<std::string>& args,
289 std::vector<std::string>& output) {
290 return ForkExecvp(args, output, nullptr);
291}
292
293status_t ForkExecvp(const std::vector<std::string>& args,
294 std::vector<std::string>& output, security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600295 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700296 std::string cmd;
297 for (size_t i = 0; i < args.size(); i++) {
298 cmd += args[i] + " ";
299 if (i == 0) {
300 LOG(VERBOSE) << args[i];
301 } else {
302 LOG(VERBOSE) << " " << args[i];
303 }
304 }
305 output.clear();
306
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700307 if (setexeccon(context)) {
308 LOG(ERROR) << "Failed to setexeccon";
309 abort();
310 }
Jeff Sharkey32ebb732017-03-27 16:18:50 -0600311 FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700312 if (setexeccon(nullptr)) {
313 LOG(ERROR) << "Failed to setexeccon";
314 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700315 }
316
317 if (!fp) {
318 PLOG(ERROR) << "Failed to popen " << cmd;
319 return -errno;
320 }
321 char line[1024];
322 while (fgets(line, sizeof(line), fp) != nullptr) {
323 LOG(VERBOSE) << line;
324 output.push_back(std::string(line));
325 }
326 if (pclose(fp) != 0) {
327 PLOG(ERROR) << "Failed to pclose " << cmd;
328 return -errno;
329 }
330
331 return OK;
332}
333
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700334pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
335 size_t argc = args.size();
336 char** argv = (char**) calloc(argc + 1, sizeof(char*));
337 for (size_t i = 0; i < argc; i++) {
338 argv[i] = (char*) args[i].c_str();
339 if (i == 0) {
340 LOG(VERBOSE) << args[i];
341 } else {
342 LOG(VERBOSE) << " " << args[i];
343 }
344 }
345
346 pid_t pid = fork();
347 if (pid == 0) {
348 close(STDIN_FILENO);
349 close(STDOUT_FILENO);
350 close(STDERR_FILENO);
351
352 if (execvp(argv[0], argv)) {
353 PLOG(ERROR) << "Failed to exec";
354 }
355
356 _exit(1);
357 }
358
359 if (pid == -1) {
360 PLOG(ERROR) << "Failed to exec";
361 }
362
363 free(argv);
364 return pid;
365}
366
Jeff Sharkey9c484982015-03-31 10:35:33 -0700367status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100368 out.resize(bytes);
369 return ReadRandomBytes(bytes, &out[0]);
370}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700371
Pavel Grafove2e2d302017-08-01 17:15:53 +0100372status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700373 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
374 if (fd == -1) {
375 return -errno;
376 }
377
Jeff Sharkey9c484982015-03-31 10:35:33 -0700378 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100379 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700380 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100381 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700382 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700383 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700384
385 if (bytes == 0) {
386 return OK;
387 } else {
388 return -EIO;
389 }
390}
391
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600392status_t GenerateRandomUuid(std::string& out) {
393 status_t res = ReadRandomBytes(16, out);
394 if (res == OK) {
395 out[6] &= 0x0f; /* clear version */
396 out[6] |= 0x40; /* set to version 4 */
397 out[8] &= 0x3f; /* clear variant */
398 out[8] |= 0x80; /* set to IETF variant */
399 }
400 return res;
401}
402
Jeff Sharkey9c484982015-03-31 10:35:33 -0700403status_t HexToStr(const std::string& hex, std::string& str) {
404 str.clear();
405 bool even = true;
406 char cur = 0;
407 for (size_t i = 0; i < hex.size(); i++) {
408 int val = 0;
409 switch (hex[i]) {
410 case ' ': case '-': case ':': continue;
411 case 'f': case 'F': val = 15; break;
412 case 'e': case 'E': val = 14; break;
413 case 'd': case 'D': val = 13; break;
414 case 'c': case 'C': val = 12; break;
415 case 'b': case 'B': val = 11; break;
416 case 'a': case 'A': val = 10; break;
417 case '9': val = 9; break;
418 case '8': val = 8; break;
419 case '7': val = 7; break;
420 case '6': val = 6; break;
421 case '5': val = 5; break;
422 case '4': val = 4; break;
423 case '3': val = 3; break;
424 case '2': val = 2; break;
425 case '1': val = 1; break;
426 case '0': val = 0; break;
427 default: return -EINVAL;
428 }
429
430 if (even) {
431 cur = val << 4;
432 } else {
433 cur += val;
434 str.push_back(cur);
435 cur = 0;
436 }
437 even = !even;
438 }
439 return even ? OK : -EINVAL;
440}
441
442static const char* kLookup = "0123456789abcdef";
443
444status_t StrToHex(const std::string& str, std::string& hex) {
445 hex.clear();
446 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700447 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700448 hex.push_back(kLookup[str[i] & 0x0F]);
449 }
450 return OK;
451}
452
Pavel Grafove2e2d302017-08-01 17:15:53 +0100453status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
454 hex.clear();
455 for (size_t i = 0; i < str.size(); i++) {
456 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
457 hex.push_back(kLookup[str.data()[i] & 0x0F]);
458 }
459 return OK;
460}
461
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700462status_t NormalizeHex(const std::string& in, std::string& out) {
463 std::string tmp;
464 if (HexToStr(in, tmp)) {
465 return -EINVAL;
466 }
467 return StrToHex(tmp, out);
468}
469
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700470uint64_t GetFreeBytes(const std::string& path) {
471 struct statvfs sb;
472 if (statvfs(path.c_str(), &sb) == 0) {
Jeff Sharkeya0220a52017-04-03 17:11:45 -0600473 return (uint64_t) sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700474 } else {
475 return -1;
476 }
477}
478
479// TODO: borrowed from frameworks/native/libs/diskusage/ which should
480// eventually be migrated into system/
481static int64_t stat_size(struct stat *s) {
482 int64_t blksize = s->st_blksize;
483 // count actual blocks used instead of nominal file size
484 int64_t size = s->st_blocks * 512;
485
486 if (blksize) {
487 /* round up to filesystem block size */
488 size = (size + blksize - 1) & (~(blksize - 1));
489 }
490
491 return size;
492}
493
494// TODO: borrowed from frameworks/native/libs/diskusage/ which should
495// eventually be migrated into system/
496int64_t calculate_dir_size(int dfd) {
497 int64_t size = 0;
498 struct stat s;
499 DIR *d;
500 struct dirent *de;
501
502 d = fdopendir(dfd);
503 if (d == NULL) {
504 close(dfd);
505 return 0;
506 }
507
508 while ((de = readdir(d))) {
509 const char *name = de->d_name;
510 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
511 size += stat_size(&s);
512 }
513 if (de->d_type == DT_DIR) {
514 int subfd;
515
516 /* always skip "." and ".." */
517 if (name[0] == '.') {
518 if (name[1] == 0)
519 continue;
520 if ((name[1] == '.') && (name[2] == 0))
521 continue;
522 }
523
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600524 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700525 if (subfd >= 0) {
526 size += calculate_dir_size(subfd);
527 }
528 }
529 }
530 closedir(d);
531 return size;
532}
533
534uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600535 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700536 if (dirfd < 0) {
537 PLOG(WARNING) << "Failed to open " << path;
538 return -1;
539 } else {
540 uint64_t res = calculate_dir_size(dirfd);
541 close(dirfd);
542 return res;
543 }
544}
545
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700546bool IsFilesystemSupported(const std::string& fsType) {
547 std::string supported;
548 if (!ReadFileToString(kProcFilesystems, &supported)) {
549 PLOG(ERROR) << "Failed to read supported filesystems";
550 return false;
551 }
552 return supported.find(fsType + "\n") != std::string::npos;
553}
554
555status_t WipeBlockDevice(const std::string& path) {
556 status_t res = -1;
557 const char* c_path = path.c_str();
558 unsigned long nr_sec = 0;
559 unsigned long long range[2];
560
561 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
562 if (fd == -1) {
563 PLOG(ERROR) << "Failed to open " << path;
564 goto done;
565 }
566
caozhiyuan9102b0b2015-10-29 16:39:00 +0800567 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700568 PLOG(ERROR) << "Failed to determine size of " << path;
569 goto done;
570 }
571
572 range[0] = 0;
573 range[1] = (unsigned long long) nr_sec * 512;
574
575 LOG(INFO) << "About to discard " << range[1] << " on " << path;
576 if (ioctl(fd, BLKDISCARD, &range) == 0) {
577 LOG(INFO) << "Discard success on " << path;
578 res = 0;
579 } else {
580 PLOG(ERROR) << "Discard failure on " << path;
581 }
582
583done:
584 close(fd);
585 return res;
586}
587
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800588static bool isValidFilename(const std::string& name) {
589 if (name.empty() || (name == ".") || (name == "..")
590 || (name.find('/') != std::string::npos)) {
591 return false;
592 } else {
593 return true;
594 }
595}
596
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700597std::string BuildKeyPath(const std::string& partGuid) {
598 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
599}
600
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600601std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700602 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600603}
604
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800605std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700606 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700607}
608
609std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700610 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700611}
612
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600613std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700614 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600615}
616
Jeff Sharkey47695b22016-02-01 17:02:29 -0700617std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700618 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700619}
620
621std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700622 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800623}
624
Calin Juravle79f55a42016-02-17 20:14:46 +0000625// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
626std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700627 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000628}
629
Paul Crowley3b71fc52017-10-09 10:55:21 -0700630std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800631 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700632 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800633 return "/data";
634 } else {
635 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700636 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800637 }
638}
639
Paul Crowley3b71fc52017-10-09 10:55:21 -0700640std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700641 // TODO: unify with installd path generation logic
642 std::string data(BuildDataPath(volumeUuid));
643 return StringPrintf("%s/media/%u", data.c_str(), userId);
644}
645
Paul Crowley3b71fc52017-10-09 10:55:21 -0700646std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800647 // TODO: unify with installd path generation logic
648 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700649 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800650 std::string legacy = StringPrintf("%s/data", data.c_str());
651 struct stat sb;
652 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
653 /* /data/data is dir, return /data/data for legacy system */
654 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800655 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800656 }
cjbaoeb501142017-04-12 00:09:00 +0800657 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800658}
659
Paul Crowley3b71fc52017-10-09 10:55:21 -0700660std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800661 // TODO: unify with installd path generation logic
662 std::string data(BuildDataPath(volumeUuid));
663 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
664}
665
Jeff Sharkey66270a22015-06-24 11:49:24 -0700666dev_t GetDevice(const std::string& path) {
667 struct stat sb;
668 if (stat(path.c_str(), &sb)) {
669 PLOG(WARNING) << "Failed to stat " << path;
670 return 0;
671 } else {
672 return sb.st_dev;
673 }
674}
675
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600676status_t RestoreconRecursive(const std::string& path) {
677 LOG(VERBOSE) << "Starting restorecon of " << path;
678
Tom Cherryd6127ef2017-06-15 17:13:56 -0700679 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600680
Tom Cherryd6127ef2017-06-15 17:13:56 -0700681 android::base::SetProperty(kRestoreconString, "");
682 android::base::SetProperty(kRestoreconString, path);
683
684 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600685
686 LOG(VERBOSE) << "Finished restorecon of " << path;
687 return OK;
688}
689
Jeff Sharkey3472e522017-10-06 18:02:53 -0600690bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
691 // Shamelessly borrowed from android::base::Readlink()
692 result->clear();
693
694 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
695 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
696 // waste memory to just start there. We add 1 so that we can recognize
697 // whether it actually fit (rather than being truncated to 4095).
698 std::vector<char> buf(4095 + 1);
699 while (true) {
700 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
701 // Unrecoverable error?
702 if (size == -1)
703 return false;
704 // It fit! (If size == buf.size(), it may have been truncated.)
705 if (static_cast<size_t>(size) < buf.size()) {
706 result->assign(&buf[0], size);
707 return true;
708 }
709 // Double our buffer and try again.
710 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900711 }
712}
713
Yu Ning942d4e82016-01-08 17:36:47 +0800714bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700715 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800716}
717
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800718} // namespace vold
719} // namespace android