blob: 102c09af196a2adef351d4de94422649b8757937 [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>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080025#include <android-base/stringprintf.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080026#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070027#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070028#include <private/android_filesystem_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080029
Jeff Sharkeyce6a9132015-04-08 21:07:21 -070030#include <mutex>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070031#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080032#include <fcntl.h>
33#include <linux/fs.h>
34#include <stdlib.h>
35#include <sys/mount.h>
36#include <sys/types.h>
37#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070038#include <sys/sysmacros.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080039#include <sys/wait.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070040#include <sys/statvfs.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080041
42#ifndef UMOUNT_NOFOLLOW
43#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
44#endif
45
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070046using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070047using android::base::StringPrintf;
48
Jeff Sharkeydeb24052015-03-02 21:01:40 -080049namespace android {
50namespace vold {
51
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070052security_context_t sBlkidContext = nullptr;
53security_context_t sBlkidUntrustedContext = nullptr;
54security_context_t sFsckContext = nullptr;
55security_context_t sFsckUntrustedContext = nullptr;
56
Jeff Sharkey9c484982015-03-31 10:35:33 -070057static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070058static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070059
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070060static const char* kProcFilesystems = "/proc/filesystems";
61
Jeff Sharkeydeb24052015-03-02 21:01:40 -080062status_t CreateDeviceNode(const std::string& path, dev_t dev) {
63 const char* cpath = path.c_str();
64 status_t res = 0;
65
66 char* secontext = nullptr;
67 if (sehandle) {
68 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
69 setfscreatecon(secontext);
70 }
71 }
72
73 mode_t mode = 0660 | S_IFBLK;
74 if (mknod(cpath, mode, dev) < 0) {
75 if (errno != EEXIST) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070076 PLOG(ERROR) << "Failed to create device node for " << major(dev)
77 << ":" << minor(dev) << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080078 res = -errno;
79 }
80 }
81
82 if (secontext) {
83 setfscreatecon(nullptr);
84 freecon(secontext);
85 }
86
87 return res;
88}
89
90status_t DestroyDeviceNode(const std::string& path) {
91 const char* cpath = path.c_str();
92 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
93 return -errno;
94 } else {
95 return OK;
96 }
97}
98
Jeff Sharkeyf0121c52015-04-06 14:08:45 -070099status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
100 const char* cpath = path.c_str();
101
102 char* secontext = nullptr;
103 if (sehandle) {
104 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
105 setfscreatecon(secontext);
106 }
107 }
108
109 int res = fs_prepare_dir(cpath, mode, uid, gid);
110
111 if (secontext) {
112 setfscreatecon(nullptr);
113 freecon(secontext);
114 }
115
116 if (res == 0) {
117 return OK;
118 } else {
119 return -errno;
120 }
121}
122
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800123status_t ForceUnmount(const std::string& path) {
124 const char* cpath = path.c_str();
125 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
126 return OK;
127 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700128 // Apps might still be handling eject request, so wait before
129 // we start sending signals
Keun-young Park375ac252017-08-02 17:45:48 -0700130 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700131
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700132 Process::killProcessesWithOpenFiles(cpath, SIGINT);
Keun-young Park375ac252017-08-02 17:45:48 -0700133 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700134 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
135 return OK;
136 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700137
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800138 Process::killProcessesWithOpenFiles(cpath, SIGTERM);
Keun-young Park375ac252017-08-02 17:45:48 -0700139 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800140 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
141 return OK;
142 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700143
144 Process::killProcessesWithOpenFiles(cpath, SIGKILL);
Keun-young Park375ac252017-08-02 17:45:48 -0700145 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700146 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
147 return OK;
148 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700149
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800150 return -errno;
151}
152
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700153status_t KillProcessesUsingPath(const std::string& path) {
154 const char* cpath = path.c_str();
155 if (Process::killProcessesWithOpenFiles(cpath, SIGINT) == 0) {
156 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
160 if (Process::killProcessesWithOpenFiles(cpath, SIGTERM) == 0) {
161 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
165 if (Process::killProcessesWithOpenFiles(cpath, SIGKILL) == 0) {
166 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
172 if (Process::killProcessesWithOpenFiles(cpath, SIGKILL) == 0) {
173 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 Sharkey95c87cc2015-04-01 11:54:32 -0700187static status_t readMetadata(const std::string& path, std::string& fsType,
188 std::string& fsUuid, std::string& fsLabel, bool untrusted) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700189 fsType.clear();
190 fsUuid.clear();
191 fsLabel.clear();
192
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700193 std::vector<std::string> cmd;
194 cmd.push_back(kBlkidPath);
195 cmd.push_back("-c");
196 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700197 cmd.push_back("-s");
198 cmd.push_back("TYPE");
199 cmd.push_back("-s");
200 cmd.push_back("UUID");
201 cmd.push_back("-s");
202 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700203 cmd.push_back(path);
204
205 std::vector<std::string> output;
206 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
207 if (res != OK) {
208 LOG(WARNING) << "blkid failed to identify " << path;
209 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700210 }
211
Jeff Sharkey9c484982015-03-31 10:35:33 -0700212 char value[128];
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700213 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700214 // Extract values from blkid output, if defined
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700215 const char* cline = line.c_str();
Dan Austin49ab5f92016-03-24 12:26:39 -0700216 const char* start = strstr(cline, "TYPE=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700217 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
218 fsType = value;
219 }
220
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700221 start = strstr(cline, "UUID=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700222 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
223 fsUuid = value;
224 }
225
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700226 start = strstr(cline, "LABEL=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700227 if (start != nullptr && sscanf(start + 6, "\"%127[^\"]\"", value) == 1) {
228 fsLabel = value;
229 }
Jeff Sharkey9c484982015-03-31 10:35:33 -0700230 }
231
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700232 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700233}
234
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700235status_t ReadMetadata(const std::string& path, std::string& fsType,
236 std::string& fsUuid, std::string& fsLabel) {
237 return readMetadata(path, fsType, fsUuid, fsLabel, false);
238}
239
240status_t ReadMetadataUntrusted(const std::string& path, std::string& fsType,
241 std::string& fsUuid, std::string& fsLabel) {
242 return readMetadata(path, fsType, fsUuid, fsLabel, true);
243}
244
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700245status_t ForkExecvp(const std::vector<std::string>& args) {
246 return ForkExecvp(args, nullptr);
247}
248
249status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
250 size_t argc = args.size();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700251 char** argv = (char**) calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700252 for (size_t i = 0; i < argc; i++) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700253 argv[i] = (char*) args[i].c_str();
254 if (i == 0) {
255 LOG(VERBOSE) << args[i];
256 } else {
257 LOG(VERBOSE) << " " << args[i];
258 }
259 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700260
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700261 if (setexeccon(context)) {
262 LOG(ERROR) << "Failed to setexeccon";
263 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700264 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700265 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
266 if (setexeccon(nullptr)) {
267 LOG(ERROR) << "Failed to setexeccon";
268 abort();
269 }
270
Jeff Sharkey9c484982015-03-31 10:35:33 -0700271 free(argv);
272 return res;
273}
274
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700275status_t ForkExecvp(const std::vector<std::string>& args,
276 std::vector<std::string>& output) {
277 return ForkExecvp(args, output, nullptr);
278}
279
280status_t ForkExecvp(const std::vector<std::string>& args,
281 std::vector<std::string>& output, security_context_t context) {
282 std::string cmd;
283 for (size_t i = 0; i < args.size(); i++) {
284 cmd += args[i] + " ";
285 if (i == 0) {
286 LOG(VERBOSE) << args[i];
287 } else {
288 LOG(VERBOSE) << " " << args[i];
289 }
290 }
291 output.clear();
292
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700293 if (setexeccon(context)) {
294 LOG(ERROR) << "Failed to setexeccon";
295 abort();
296 }
Jeff Sharkey32ebb732017-03-27 16:18:50 -0600297 FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700298 if (setexeccon(nullptr)) {
299 LOG(ERROR) << "Failed to setexeccon";
300 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700301 }
302
303 if (!fp) {
304 PLOG(ERROR) << "Failed to popen " << cmd;
305 return -errno;
306 }
307 char line[1024];
308 while (fgets(line, sizeof(line), fp) != nullptr) {
309 LOG(VERBOSE) << line;
310 output.push_back(std::string(line));
311 }
312 if (pclose(fp) != 0) {
313 PLOG(ERROR) << "Failed to pclose " << cmd;
314 return -errno;
315 }
316
317 return OK;
318}
319
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700320pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
321 size_t argc = args.size();
322 char** argv = (char**) calloc(argc + 1, sizeof(char*));
323 for (size_t i = 0; i < argc; i++) {
324 argv[i] = (char*) args[i].c_str();
325 if (i == 0) {
326 LOG(VERBOSE) << args[i];
327 } else {
328 LOG(VERBOSE) << " " << args[i];
329 }
330 }
331
332 pid_t pid = fork();
333 if (pid == 0) {
334 close(STDIN_FILENO);
335 close(STDOUT_FILENO);
336 close(STDERR_FILENO);
337
338 if (execvp(argv[0], argv)) {
339 PLOG(ERROR) << "Failed to exec";
340 }
341
342 _exit(1);
343 }
344
345 if (pid == -1) {
346 PLOG(ERROR) << "Failed to exec";
347 }
348
349 free(argv);
350 return pid;
351}
352
Jeff Sharkey9c484982015-03-31 10:35:33 -0700353status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100354 out.resize(bytes);
355 return ReadRandomBytes(bytes, &out[0]);
356}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700357
Pavel Grafove2e2d302017-08-01 17:15:53 +0100358status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700359 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
360 if (fd == -1) {
361 return -errno;
362 }
363
Jeff Sharkey9c484982015-03-31 10:35:33 -0700364 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100365 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700366 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100367 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700368 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700369 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700370
371 if (bytes == 0) {
372 return OK;
373 } else {
374 return -EIO;
375 }
376}
377
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600378status_t GenerateRandomUuid(std::string& out) {
379 status_t res = ReadRandomBytes(16, out);
380 if (res == OK) {
381 out[6] &= 0x0f; /* clear version */
382 out[6] |= 0x40; /* set to version 4 */
383 out[8] &= 0x3f; /* clear variant */
384 out[8] |= 0x80; /* set to IETF variant */
385 }
386 return res;
387}
388
Jeff Sharkey9c484982015-03-31 10:35:33 -0700389status_t HexToStr(const std::string& hex, std::string& str) {
390 str.clear();
391 bool even = true;
392 char cur = 0;
393 for (size_t i = 0; i < hex.size(); i++) {
394 int val = 0;
395 switch (hex[i]) {
396 case ' ': case '-': case ':': continue;
397 case 'f': case 'F': val = 15; break;
398 case 'e': case 'E': val = 14; break;
399 case 'd': case 'D': val = 13; break;
400 case 'c': case 'C': val = 12; break;
401 case 'b': case 'B': val = 11; break;
402 case 'a': case 'A': val = 10; break;
403 case '9': val = 9; break;
404 case '8': val = 8; break;
405 case '7': val = 7; break;
406 case '6': val = 6; break;
407 case '5': val = 5; break;
408 case '4': val = 4; break;
409 case '3': val = 3; break;
410 case '2': val = 2; break;
411 case '1': val = 1; break;
412 case '0': val = 0; break;
413 default: return -EINVAL;
414 }
415
416 if (even) {
417 cur = val << 4;
418 } else {
419 cur += val;
420 str.push_back(cur);
421 cur = 0;
422 }
423 even = !even;
424 }
425 return even ? OK : -EINVAL;
426}
427
428static const char* kLookup = "0123456789abcdef";
429
430status_t StrToHex(const std::string& str, std::string& hex) {
431 hex.clear();
432 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700433 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700434 hex.push_back(kLookup[str[i] & 0x0F]);
435 }
436 return OK;
437}
438
Pavel Grafove2e2d302017-08-01 17:15:53 +0100439status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
440 hex.clear();
441 for (size_t i = 0; i < str.size(); i++) {
442 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
443 hex.push_back(kLookup[str.data()[i] & 0x0F]);
444 }
445 return OK;
446}
447
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700448status_t NormalizeHex(const std::string& in, std::string& out) {
449 std::string tmp;
450 if (HexToStr(in, tmp)) {
451 return -EINVAL;
452 }
453 return StrToHex(tmp, out);
454}
455
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700456uint64_t GetFreeBytes(const std::string& path) {
457 struct statvfs sb;
458 if (statvfs(path.c_str(), &sb) == 0) {
Jeff Sharkeya0220a52017-04-03 17:11:45 -0600459 return (uint64_t) sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700460 } else {
461 return -1;
462 }
463}
464
465// TODO: borrowed from frameworks/native/libs/diskusage/ which should
466// eventually be migrated into system/
467static int64_t stat_size(struct stat *s) {
468 int64_t blksize = s->st_blksize;
469 // count actual blocks used instead of nominal file size
470 int64_t size = s->st_blocks * 512;
471
472 if (blksize) {
473 /* round up to filesystem block size */
474 size = (size + blksize - 1) & (~(blksize - 1));
475 }
476
477 return size;
478}
479
480// TODO: borrowed from frameworks/native/libs/diskusage/ which should
481// eventually be migrated into system/
482int64_t calculate_dir_size(int dfd) {
483 int64_t size = 0;
484 struct stat s;
485 DIR *d;
486 struct dirent *de;
487
488 d = fdopendir(dfd);
489 if (d == NULL) {
490 close(dfd);
491 return 0;
492 }
493
494 while ((de = readdir(d))) {
495 const char *name = de->d_name;
496 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
497 size += stat_size(&s);
498 }
499 if (de->d_type == DT_DIR) {
500 int subfd;
501
502 /* always skip "." and ".." */
503 if (name[0] == '.') {
504 if (name[1] == 0)
505 continue;
506 if ((name[1] == '.') && (name[2] == 0))
507 continue;
508 }
509
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600510 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700511 if (subfd >= 0) {
512 size += calculate_dir_size(subfd);
513 }
514 }
515 }
516 closedir(d);
517 return size;
518}
519
520uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600521 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700522 if (dirfd < 0) {
523 PLOG(WARNING) << "Failed to open " << path;
524 return -1;
525 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700526 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700527 }
528}
529
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700530bool IsFilesystemSupported(const std::string& fsType) {
531 std::string supported;
532 if (!ReadFileToString(kProcFilesystems, &supported)) {
533 PLOG(ERROR) << "Failed to read supported filesystems";
534 return false;
535 }
536 return supported.find(fsType + "\n") != std::string::npos;
537}
538
539status_t WipeBlockDevice(const std::string& path) {
540 status_t res = -1;
541 const char* c_path = path.c_str();
542 unsigned long nr_sec = 0;
543 unsigned long long range[2];
544
545 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
546 if (fd == -1) {
547 PLOG(ERROR) << "Failed to open " << path;
548 goto done;
549 }
550
caozhiyuan9102b0b2015-10-29 16:39:00 +0800551 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700552 PLOG(ERROR) << "Failed to determine size of " << path;
553 goto done;
554 }
555
556 range[0] = 0;
557 range[1] = (unsigned long long) nr_sec * 512;
558
559 LOG(INFO) << "About to discard " << range[1] << " on " << path;
560 if (ioctl(fd, BLKDISCARD, &range) == 0) {
561 LOG(INFO) << "Discard success on " << path;
562 res = 0;
563 } else {
564 PLOG(ERROR) << "Discard failure on " << path;
565 }
566
567done:
568 close(fd);
569 return res;
570}
571
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800572static bool isValidFilename(const std::string& name) {
573 if (name.empty() || (name == ".") || (name == "..")
574 || (name.find('/') != std::string::npos)) {
575 return false;
576 } else {
577 return true;
578 }
579}
580
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700581std::string BuildKeyPath(const std::string& partGuid) {
582 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
583}
584
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600585std::string BuildDataSystemLegacyPath(userid_t userId) {
586 return StringPrintf("%s/system/users/%u", BuildDataPath(nullptr).c_str(), userId);
587}
588
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800589std::string BuildDataSystemCePath(userid_t userId) {
Jeff Sharkey47695b22016-02-01 17:02:29 -0700590 return StringPrintf("%s/system_ce/%u", BuildDataPath(nullptr).c_str(), userId);
591}
592
593std::string BuildDataSystemDePath(userid_t userId) {
594 return StringPrintf("%s/system_de/%u", BuildDataPath(nullptr).c_str(), userId);
595}
596
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600597std::string BuildDataMiscLegacyPath(userid_t userId) {
598 return StringPrintf("%s/misc/user/%u", BuildDataPath(nullptr).c_str(), userId);
599}
600
Jeff Sharkey47695b22016-02-01 17:02:29 -0700601std::string BuildDataMiscCePath(userid_t userId) {
602 return StringPrintf("%s/misc_ce/%u", BuildDataPath(nullptr).c_str(), userId);
603}
604
605std::string BuildDataMiscDePath(userid_t userId) {
606 return StringPrintf("%s/misc_de/%u", BuildDataPath(nullptr).c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800607}
608
Calin Juravle79f55a42016-02-17 20:14:46 +0000609// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
610std::string BuildDataProfilesDePath(userid_t userId) {
611 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath(nullptr).c_str(), userId);
612}
613
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800614std::string BuildDataPath(const char* volumeUuid) {
615 // TODO: unify with installd path generation logic
616 if (volumeUuid == nullptr) {
617 return "/data";
618 } else {
619 CHECK(isValidFilename(volumeUuid));
620 return StringPrintf("/mnt/expand/%s", volumeUuid);
621 }
622}
623
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600624std::string BuildDataMediaCePath(const char* volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700625 // TODO: unify with installd path generation logic
626 std::string data(BuildDataPath(volumeUuid));
627 return StringPrintf("%s/media/%u", data.c_str(), userId);
628}
629
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600630std::string BuildDataUserCePath(const char* volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800631 // TODO: unify with installd path generation logic
632 std::string data(BuildDataPath(volumeUuid));
cjbaoeb501142017-04-12 00:09:00 +0800633 if (volumeUuid == nullptr && userId == 0) {
634 std::string legacy = StringPrintf("%s/data", data.c_str());
635 struct stat sb;
636 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
637 /* /data/data is dir, return /data/data for legacy system */
638 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800639 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800640 }
cjbaoeb501142017-04-12 00:09:00 +0800641 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800642}
643
644std::string BuildDataUserDePath(const char* volumeUuid, userid_t userId) {
645 // TODO: unify with installd path generation logic
646 std::string data(BuildDataPath(volumeUuid));
647 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
648}
649
Jeff Sharkey66270a22015-06-24 11:49:24 -0700650dev_t GetDevice(const std::string& path) {
651 struct stat sb;
652 if (stat(path.c_str(), &sb)) {
653 PLOG(WARNING) << "Failed to stat " << path;
654 return 0;
655 } else {
656 return sb.st_dev;
657 }
658}
659
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600660status_t RestoreconRecursive(const std::string& path) {
661 LOG(VERBOSE) << "Starting restorecon of " << path;
662
Tom Cherryd6127ef2017-06-15 17:13:56 -0700663 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600664
Tom Cherryd6127ef2017-06-15 17:13:56 -0700665 android::base::SetProperty(kRestoreconString, "");
666 android::base::SetProperty(kRestoreconString, path);
667
668 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600669
670 LOG(VERBOSE) << "Finished restorecon of " << path;
671 return OK;
672}
673
Daichi Hirono10d34882016-01-29 14:33:51 +0900674status_t SaneReadLinkAt(int dirfd, const char* path, char* buf, size_t bufsiz) {
675 ssize_t len = readlinkat(dirfd, path, buf, bufsiz);
676 if (len < 0) {
677 return -1;
678 } else if (len == (ssize_t) bufsiz) {
679 return -1;
680 } else {
681 buf[len] = '\0';
682 return 0;
683 }
684}
685
Yu Ning942d4e82016-01-08 17:36:47 +0800686bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700687 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800688}
689
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800690} // namespace vold
691} // namespace android