blob: 395a8901d17ce6d3f6bd7a16f2463addb899f618 [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) {
354 out.clear();
355
356 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
357 if (fd == -1) {
358 return -errno;
359 }
360
361 char buf[BUFSIZ];
362 size_t n;
363 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], std::min(sizeof(buf), bytes)))) > 0) {
364 out.append(buf, n);
365 bytes -= n;
366 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700367 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700368
369 if (bytes == 0) {
370 return OK;
371 } else {
372 return -EIO;
373 }
374}
375
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600376status_t GenerateRandomUuid(std::string& out) {
377 status_t res = ReadRandomBytes(16, out);
378 if (res == OK) {
379 out[6] &= 0x0f; /* clear version */
380 out[6] |= 0x40; /* set to version 4 */
381 out[8] &= 0x3f; /* clear variant */
382 out[8] |= 0x80; /* set to IETF variant */
383 }
384 return res;
385}
386
Jeff Sharkey9c484982015-03-31 10:35:33 -0700387status_t HexToStr(const std::string& hex, std::string& str) {
388 str.clear();
389 bool even = true;
390 char cur = 0;
391 for (size_t i = 0; i < hex.size(); i++) {
392 int val = 0;
393 switch (hex[i]) {
394 case ' ': case '-': case ':': continue;
395 case 'f': case 'F': val = 15; break;
396 case 'e': case 'E': val = 14; break;
397 case 'd': case 'D': val = 13; break;
398 case 'c': case 'C': val = 12; break;
399 case 'b': case 'B': val = 11; break;
400 case 'a': case 'A': val = 10; break;
401 case '9': val = 9; break;
402 case '8': val = 8; break;
403 case '7': val = 7; break;
404 case '6': val = 6; break;
405 case '5': val = 5; break;
406 case '4': val = 4; break;
407 case '3': val = 3; break;
408 case '2': val = 2; break;
409 case '1': val = 1; break;
410 case '0': val = 0; break;
411 default: return -EINVAL;
412 }
413
414 if (even) {
415 cur = val << 4;
416 } else {
417 cur += val;
418 str.push_back(cur);
419 cur = 0;
420 }
421 even = !even;
422 }
423 return even ? OK : -EINVAL;
424}
425
426static const char* kLookup = "0123456789abcdef";
427
428status_t StrToHex(const std::string& str, std::string& hex) {
429 hex.clear();
430 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700431 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700432 hex.push_back(kLookup[str[i] & 0x0F]);
433 }
434 return OK;
435}
436
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700437status_t NormalizeHex(const std::string& in, std::string& out) {
438 std::string tmp;
439 if (HexToStr(in, tmp)) {
440 return -EINVAL;
441 }
442 return StrToHex(tmp, out);
443}
444
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700445uint64_t GetFreeBytes(const std::string& path) {
446 struct statvfs sb;
447 if (statvfs(path.c_str(), &sb) == 0) {
Jeff Sharkeya0220a52017-04-03 17:11:45 -0600448 return (uint64_t) sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700449 } else {
450 return -1;
451 }
452}
453
454// TODO: borrowed from frameworks/native/libs/diskusage/ which should
455// eventually be migrated into system/
456static int64_t stat_size(struct stat *s) {
457 int64_t blksize = s->st_blksize;
458 // count actual blocks used instead of nominal file size
459 int64_t size = s->st_blocks * 512;
460
461 if (blksize) {
462 /* round up to filesystem block size */
463 size = (size + blksize - 1) & (~(blksize - 1));
464 }
465
466 return size;
467}
468
469// TODO: borrowed from frameworks/native/libs/diskusage/ which should
470// eventually be migrated into system/
471int64_t calculate_dir_size(int dfd) {
472 int64_t size = 0;
473 struct stat s;
474 DIR *d;
475 struct dirent *de;
476
477 d = fdopendir(dfd);
478 if (d == NULL) {
479 close(dfd);
480 return 0;
481 }
482
483 while ((de = readdir(d))) {
484 const char *name = de->d_name;
485 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
486 size += stat_size(&s);
487 }
488 if (de->d_type == DT_DIR) {
489 int subfd;
490
491 /* always skip "." and ".." */
492 if (name[0] == '.') {
493 if (name[1] == 0)
494 continue;
495 if ((name[1] == '.') && (name[2] == 0))
496 continue;
497 }
498
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600499 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700500 if (subfd >= 0) {
501 size += calculate_dir_size(subfd);
502 }
503 }
504 }
505 closedir(d);
506 return size;
507}
508
509uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600510 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700511 if (dirfd < 0) {
512 PLOG(WARNING) << "Failed to open " << path;
513 return -1;
514 } else {
515 uint64_t res = calculate_dir_size(dirfd);
516 close(dirfd);
517 return res;
518 }
519}
520
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700521bool IsFilesystemSupported(const std::string& fsType) {
522 std::string supported;
523 if (!ReadFileToString(kProcFilesystems, &supported)) {
524 PLOG(ERROR) << "Failed to read supported filesystems";
525 return false;
526 }
527 return supported.find(fsType + "\n") != std::string::npos;
528}
529
530status_t WipeBlockDevice(const std::string& path) {
531 status_t res = -1;
532 const char* c_path = path.c_str();
533 unsigned long nr_sec = 0;
534 unsigned long long range[2];
535
536 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
537 if (fd == -1) {
538 PLOG(ERROR) << "Failed to open " << path;
539 goto done;
540 }
541
caozhiyuan9102b0b2015-10-29 16:39:00 +0800542 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700543 PLOG(ERROR) << "Failed to determine size of " << path;
544 goto done;
545 }
546
547 range[0] = 0;
548 range[1] = (unsigned long long) nr_sec * 512;
549
550 LOG(INFO) << "About to discard " << range[1] << " on " << path;
551 if (ioctl(fd, BLKDISCARD, &range) == 0) {
552 LOG(INFO) << "Discard success on " << path;
553 res = 0;
554 } else {
555 PLOG(ERROR) << "Discard failure on " << path;
556 }
557
558done:
559 close(fd);
560 return res;
561}
562
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800563static bool isValidFilename(const std::string& name) {
564 if (name.empty() || (name == ".") || (name == "..")
565 || (name.find('/') != std::string::npos)) {
566 return false;
567 } else {
568 return true;
569 }
570}
571
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700572std::string BuildKeyPath(const std::string& partGuid) {
573 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
574}
575
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600576std::string BuildDataSystemLegacyPath(userid_t userId) {
577 return StringPrintf("%s/system/users/%u", BuildDataPath(nullptr).c_str(), userId);
578}
579
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800580std::string BuildDataSystemCePath(userid_t userId) {
Jeff Sharkey47695b22016-02-01 17:02:29 -0700581 return StringPrintf("%s/system_ce/%u", BuildDataPath(nullptr).c_str(), userId);
582}
583
584std::string BuildDataSystemDePath(userid_t userId) {
585 return StringPrintf("%s/system_de/%u", BuildDataPath(nullptr).c_str(), userId);
586}
587
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600588std::string BuildDataMiscLegacyPath(userid_t userId) {
589 return StringPrintf("%s/misc/user/%u", BuildDataPath(nullptr).c_str(), userId);
590}
591
Jeff Sharkey47695b22016-02-01 17:02:29 -0700592std::string BuildDataMiscCePath(userid_t userId) {
593 return StringPrintf("%s/misc_ce/%u", BuildDataPath(nullptr).c_str(), userId);
594}
595
596std::string BuildDataMiscDePath(userid_t userId) {
597 return StringPrintf("%s/misc_de/%u", BuildDataPath(nullptr).c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800598}
599
Calin Juravle79f55a42016-02-17 20:14:46 +0000600// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
601std::string BuildDataProfilesDePath(userid_t userId) {
602 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath(nullptr).c_str(), userId);
603}
604
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800605std::string BuildDataPath(const char* volumeUuid) {
606 // TODO: unify with installd path generation logic
607 if (volumeUuid == nullptr) {
608 return "/data";
609 } else {
610 CHECK(isValidFilename(volumeUuid));
611 return StringPrintf("/mnt/expand/%s", volumeUuid);
612 }
613}
614
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600615std::string BuildDataMediaCePath(const char* volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700616 // TODO: unify with installd path generation logic
617 std::string data(BuildDataPath(volumeUuid));
618 return StringPrintf("%s/media/%u", data.c_str(), userId);
619}
620
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600621std::string BuildDataUserCePath(const char* volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800622 // TODO: unify with installd path generation logic
623 std::string data(BuildDataPath(volumeUuid));
cjbaoeb501142017-04-12 00:09:00 +0800624 if (volumeUuid == nullptr && userId == 0) {
625 std::string legacy = StringPrintf("%s/data", data.c_str());
626 struct stat sb;
627 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
628 /* /data/data is dir, return /data/data for legacy system */
629 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800630 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800631 }
cjbaoeb501142017-04-12 00:09:00 +0800632 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800633}
634
635std::string BuildDataUserDePath(const char* volumeUuid, userid_t userId) {
636 // TODO: unify with installd path generation logic
637 std::string data(BuildDataPath(volumeUuid));
638 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
639}
640
Jeff Sharkey66270a22015-06-24 11:49:24 -0700641dev_t GetDevice(const std::string& path) {
642 struct stat sb;
643 if (stat(path.c_str(), &sb)) {
644 PLOG(WARNING) << "Failed to stat " << path;
645 return 0;
646 } else {
647 return sb.st_dev;
648 }
649}
650
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600651status_t RestoreconRecursive(const std::string& path) {
652 LOG(VERBOSE) << "Starting restorecon of " << path;
653
Tom Cherryd6127ef2017-06-15 17:13:56 -0700654 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600655
Tom Cherryd6127ef2017-06-15 17:13:56 -0700656 android::base::SetProperty(kRestoreconString, "");
657 android::base::SetProperty(kRestoreconString, path);
658
659 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600660
661 LOG(VERBOSE) << "Finished restorecon of " << path;
662 return OK;
663}
664
Daichi Hirono10d34882016-01-29 14:33:51 +0900665status_t SaneReadLinkAt(int dirfd, const char* path, char* buf, size_t bufsiz) {
666 ssize_t len = readlinkat(dirfd, path, buf, bufsiz);
667 if (len < 0) {
668 return -1;
669 } else if (len == (ssize_t) bufsiz) {
670 return -1;
671 } else {
672 buf[len] = '\0';
673 return 0;
674 }
675}
676
Yu Ning942d4e82016-01-08 17:36:47 +0800677bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700678 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800679}
680
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800681} // namespace vold
682} // namespace android