blob: 2dd9ae8b7cca0106a0a9c4eb879e068cb198857e [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"
20
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070021#include <base/file.h>
Jeff Sharkey36801cc2015-03-13 16:09:20 -070022#include <base/logging.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070023#include <base/stringprintf.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080024#include <cutils/fs.h>
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -070025#include <cutils/properties.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080026#include <private/android_filesystem_config.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070027#include <logwrap/logwrap.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080028
Jeff Sharkeyce6a9132015-04-08 21:07:21 -070029#include <mutex>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070030#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080031#include <fcntl.h>
32#include <linux/fs.h>
33#include <stdlib.h>
34#include <sys/mount.h>
35#include <sys/types.h>
36#include <sys/stat.h>
37#include <sys/wait.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070038#include <sys/statvfs.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080039
40#ifndef UMOUNT_NOFOLLOW
41#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
42#endif
43
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070044using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070045using android::base::StringPrintf;
46
Jeff Sharkeydeb24052015-03-02 21:01:40 -080047namespace android {
48namespace vold {
49
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070050security_context_t sBlkidContext = nullptr;
51security_context_t sBlkidUntrustedContext = nullptr;
52security_context_t sFsckContext = nullptr;
53security_context_t sFsckUntrustedContext = nullptr;
54
Jeff Sharkey9c484982015-03-31 10:35:33 -070055static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070056static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070057
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070058static const char* kProcFilesystems = "/proc/filesystems";
59
Jeff Sharkeydeb24052015-03-02 21:01:40 -080060status_t CreateDeviceNode(const std::string& path, dev_t dev) {
61 const char* cpath = path.c_str();
62 status_t res = 0;
63
64 char* secontext = nullptr;
65 if (sehandle) {
66 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
67 setfscreatecon(secontext);
68 }
69 }
70
71 mode_t mode = 0660 | S_IFBLK;
72 if (mknod(cpath, mode, dev) < 0) {
73 if (errno != EEXIST) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070074 PLOG(ERROR) << "Failed to create device node for " << major(dev)
75 << ":" << minor(dev) << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080076 res = -errno;
77 }
78 }
79
80 if (secontext) {
81 setfscreatecon(nullptr);
82 freecon(secontext);
83 }
84
85 return res;
86}
87
88status_t DestroyDeviceNode(const std::string& path) {
89 const char* cpath = path.c_str();
90 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
91 return -errno;
92 } else {
93 return OK;
94 }
95}
96
Jeff Sharkeyf0121c52015-04-06 14:08:45 -070097status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
98 const char* cpath = path.c_str();
99
100 char* secontext = nullptr;
101 if (sehandle) {
102 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
103 setfscreatecon(secontext);
104 }
105 }
106
107 int res = fs_prepare_dir(cpath, mode, uid, gid);
108
109 if (secontext) {
110 setfscreatecon(nullptr);
111 freecon(secontext);
112 }
113
114 if (res == 0) {
115 return OK;
116 } else {
117 return -errno;
118 }
119}
120
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800121status_t ForceUnmount(const std::string& path) {
122 const char* cpath = path.c_str();
123 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
124 return OK;
125 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700126 PLOG(WARNING) << "Failed to unmount " << path;
127
128 sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700129 Process::killProcessesWithOpenFiles(cpath, SIGINT);
130
131 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
132 return OK;
133 }
134 PLOG(WARNING) << "Failed to unmount " << path;
135
136 sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800137 Process::killProcessesWithOpenFiles(cpath, SIGTERM);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800138
139 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
140 return OK;
141 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700142 PLOG(WARNING) << "Failed to unmount " << path;
143
144 sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800145 Process::killProcessesWithOpenFiles(cpath, SIGKILL);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800146
147 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
148 return OK;
149 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700150 PLOG(ERROR) << "Failed to unmount " << path;
151
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800152 return -errno;
153}
154
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700155status_t BindMount(const std::string& source, const std::string& target) {
156 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
157 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
158 return -errno;
159 }
160 return OK;
161}
162
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700163static status_t readMetadata(const std::string& path, std::string& fsType,
164 std::string& fsUuid, std::string& fsLabel, bool untrusted) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700165 fsType.clear();
166 fsUuid.clear();
167 fsLabel.clear();
168
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700169 std::vector<std::string> cmd;
170 cmd.push_back(kBlkidPath);
171 cmd.push_back("-c");
172 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700173 cmd.push_back("-s");
174 cmd.push_back("TYPE");
175 cmd.push_back("-s");
176 cmd.push_back("UUID");
177 cmd.push_back("-s");
178 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700179 cmd.push_back(path);
180
181 std::vector<std::string> output;
182 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
183 if (res != OK) {
184 LOG(WARNING) << "blkid failed to identify " << path;
185 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700186 }
187
Jeff Sharkey9c484982015-03-31 10:35:33 -0700188 char value[128];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700189 for (auto line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700190 // Extract values from blkid output, if defined
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700191 const char* cline = line.c_str();
192 char* start = strstr(cline, "TYPE=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700193 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
194 fsType = value;
195 }
196
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700197 start = strstr(cline, "UUID=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700198 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
199 fsUuid = value;
200 }
201
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700202 start = strstr(cline, "LABEL=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700203 if (start != nullptr && sscanf(start + 6, "\"%127[^\"]\"", value) == 1) {
204 fsLabel = value;
205 }
Jeff Sharkey9c484982015-03-31 10:35:33 -0700206 }
207
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700208 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700209}
210
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700211status_t ReadMetadata(const std::string& path, std::string& fsType,
212 std::string& fsUuid, std::string& fsLabel) {
213 return readMetadata(path, fsType, fsUuid, fsLabel, false);
214}
215
216status_t ReadMetadataUntrusted(const std::string& path, std::string& fsType,
217 std::string& fsUuid, std::string& fsLabel) {
218 return readMetadata(path, fsType, fsUuid, fsLabel, true);
219}
220
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700221status_t ForkExecvp(const std::vector<std::string>& args) {
222 return ForkExecvp(args, nullptr);
223}
224
225status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
226 size_t argc = args.size();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700227 char** argv = (char**) calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700228 for (size_t i = 0; i < argc; i++) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700229 argv[i] = (char*) args[i].c_str();
230 if (i == 0) {
231 LOG(VERBOSE) << args[i];
232 } else {
233 LOG(VERBOSE) << " " << args[i];
234 }
235 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700236
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700237 if (setexeccon(context)) {
238 LOG(ERROR) << "Failed to setexeccon";
239 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700240 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700241 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
242 if (setexeccon(nullptr)) {
243 LOG(ERROR) << "Failed to setexeccon";
244 abort();
245 }
246
Jeff Sharkey9c484982015-03-31 10:35:33 -0700247 free(argv);
248 return res;
249}
250
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700251status_t ForkExecvp(const std::vector<std::string>& args,
252 std::vector<std::string>& output) {
253 return ForkExecvp(args, output, nullptr);
254}
255
256status_t ForkExecvp(const std::vector<std::string>& args,
257 std::vector<std::string>& output, security_context_t context) {
258 std::string cmd;
259 for (size_t i = 0; i < args.size(); i++) {
260 cmd += args[i] + " ";
261 if (i == 0) {
262 LOG(VERBOSE) << args[i];
263 } else {
264 LOG(VERBOSE) << " " << args[i];
265 }
266 }
267 output.clear();
268
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700269 if (setexeccon(context)) {
270 LOG(ERROR) << "Failed to setexeccon";
271 abort();
272 }
273 FILE* fp = popen(cmd.c_str(), "r");
274 if (setexeccon(nullptr)) {
275 LOG(ERROR) << "Failed to setexeccon";
276 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700277 }
278
279 if (!fp) {
280 PLOG(ERROR) << "Failed to popen " << cmd;
281 return -errno;
282 }
283 char line[1024];
284 while (fgets(line, sizeof(line), fp) != nullptr) {
285 LOG(VERBOSE) << line;
286 output.push_back(std::string(line));
287 }
288 if (pclose(fp) != 0) {
289 PLOG(ERROR) << "Failed to pclose " << cmd;
290 return -errno;
291 }
292
293 return OK;
294}
295
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700296pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
297 size_t argc = args.size();
298 char** argv = (char**) calloc(argc + 1, sizeof(char*));
299 for (size_t i = 0; i < argc; i++) {
300 argv[i] = (char*) args[i].c_str();
301 if (i == 0) {
302 LOG(VERBOSE) << args[i];
303 } else {
304 LOG(VERBOSE) << " " << args[i];
305 }
306 }
307
308 pid_t pid = fork();
309 if (pid == 0) {
310 close(STDIN_FILENO);
311 close(STDOUT_FILENO);
312 close(STDERR_FILENO);
313
314 if (execvp(argv[0], argv)) {
315 PLOG(ERROR) << "Failed to exec";
316 }
317
318 _exit(1);
319 }
320
321 if (pid == -1) {
322 PLOG(ERROR) << "Failed to exec";
323 }
324
325 free(argv);
326 return pid;
327}
328
Jeff Sharkey9c484982015-03-31 10:35:33 -0700329status_t ReadRandomBytes(size_t bytes, std::string& out) {
330 out.clear();
331
332 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
333 if (fd == -1) {
334 return -errno;
335 }
336
337 char buf[BUFSIZ];
338 size_t n;
339 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], std::min(sizeof(buf), bytes)))) > 0) {
340 out.append(buf, n);
341 bytes -= n;
342 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700343 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700344
345 if (bytes == 0) {
346 return OK;
347 } else {
348 return -EIO;
349 }
350}
351
352status_t HexToStr(const std::string& hex, std::string& str) {
353 str.clear();
354 bool even = true;
355 char cur = 0;
356 for (size_t i = 0; i < hex.size(); i++) {
357 int val = 0;
358 switch (hex[i]) {
359 case ' ': case '-': case ':': continue;
360 case 'f': case 'F': val = 15; break;
361 case 'e': case 'E': val = 14; break;
362 case 'd': case 'D': val = 13; break;
363 case 'c': case 'C': val = 12; break;
364 case 'b': case 'B': val = 11; break;
365 case 'a': case 'A': val = 10; break;
366 case '9': val = 9; break;
367 case '8': val = 8; break;
368 case '7': val = 7; break;
369 case '6': val = 6; break;
370 case '5': val = 5; break;
371 case '4': val = 4; break;
372 case '3': val = 3; break;
373 case '2': val = 2; break;
374 case '1': val = 1; break;
375 case '0': val = 0; break;
376 default: return -EINVAL;
377 }
378
379 if (even) {
380 cur = val << 4;
381 } else {
382 cur += val;
383 str.push_back(cur);
384 cur = 0;
385 }
386 even = !even;
387 }
388 return even ? OK : -EINVAL;
389}
390
391static const char* kLookup = "0123456789abcdef";
392
393status_t StrToHex(const std::string& str, std::string& hex) {
394 hex.clear();
395 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700396 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700397 hex.push_back(kLookup[str[i] & 0x0F]);
398 }
399 return OK;
400}
401
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700402status_t NormalizeHex(const std::string& in, std::string& out) {
403 std::string tmp;
404 if (HexToStr(in, tmp)) {
405 return -EINVAL;
406 }
407 return StrToHex(tmp, out);
408}
409
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700410uint64_t GetFreeBytes(const std::string& path) {
411 struct statvfs sb;
412 if (statvfs(path.c_str(), &sb) == 0) {
Oleksiy Avramchenkoe76cf532015-10-01 12:44:46 +0200413 return (uint64_t)sb.f_bfree * sb.f_bsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700414 } else {
415 return -1;
416 }
417}
418
419// TODO: borrowed from frameworks/native/libs/diskusage/ which should
420// eventually be migrated into system/
421static int64_t stat_size(struct stat *s) {
422 int64_t blksize = s->st_blksize;
423 // count actual blocks used instead of nominal file size
424 int64_t size = s->st_blocks * 512;
425
426 if (blksize) {
427 /* round up to filesystem block size */
428 size = (size + blksize - 1) & (~(blksize - 1));
429 }
430
431 return size;
432}
433
434// TODO: borrowed from frameworks/native/libs/diskusage/ which should
435// eventually be migrated into system/
436int64_t calculate_dir_size(int dfd) {
437 int64_t size = 0;
438 struct stat s;
439 DIR *d;
440 struct dirent *de;
441
442 d = fdopendir(dfd);
443 if (d == NULL) {
444 close(dfd);
445 return 0;
446 }
447
448 while ((de = readdir(d))) {
449 const char *name = de->d_name;
450 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
451 size += stat_size(&s);
452 }
453 if (de->d_type == DT_DIR) {
454 int subfd;
455
456 /* always skip "." and ".." */
457 if (name[0] == '.') {
458 if (name[1] == 0)
459 continue;
460 if ((name[1] == '.') && (name[2] == 0))
461 continue;
462 }
463
464 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
465 if (subfd >= 0) {
466 size += calculate_dir_size(subfd);
467 }
468 }
469 }
470 closedir(d);
471 return size;
472}
473
474uint64_t GetTreeBytes(const std::string& path) {
475 int dirfd = open(path.c_str(), O_DIRECTORY, O_RDONLY);
476 if (dirfd < 0) {
477 PLOG(WARNING) << "Failed to open " << path;
478 return -1;
479 } else {
480 uint64_t res = calculate_dir_size(dirfd);
481 close(dirfd);
482 return res;
483 }
484}
485
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700486bool IsFilesystemSupported(const std::string& fsType) {
487 std::string supported;
488 if (!ReadFileToString(kProcFilesystems, &supported)) {
489 PLOG(ERROR) << "Failed to read supported filesystems";
490 return false;
491 }
492 return supported.find(fsType + "\n") != std::string::npos;
493}
494
495status_t WipeBlockDevice(const std::string& path) {
496 status_t res = -1;
497 const char* c_path = path.c_str();
498 unsigned long nr_sec = 0;
499 unsigned long long range[2];
500
501 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
502 if (fd == -1) {
503 PLOG(ERROR) << "Failed to open " << path;
504 goto done;
505 }
506
caozhiyuan9102b0b2015-10-29 16:39:00 +0800507 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700508 PLOG(ERROR) << "Failed to determine size of " << path;
509 goto done;
510 }
511
512 range[0] = 0;
513 range[1] = (unsigned long long) nr_sec * 512;
514
515 LOG(INFO) << "About to discard " << range[1] << " on " << path;
516 if (ioctl(fd, BLKDISCARD, &range) == 0) {
517 LOG(INFO) << "Discard success on " << path;
518 res = 0;
519 } else {
520 PLOG(ERROR) << "Discard failure on " << path;
521 }
522
523done:
524 close(fd);
525 return res;
526}
527
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700528std::string BuildKeyPath(const std::string& partGuid) {
529 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
530}
531
Jeff Sharkey66270a22015-06-24 11:49:24 -0700532dev_t GetDevice(const std::string& path) {
533 struct stat sb;
534 if (stat(path.c_str(), &sb)) {
535 PLOG(WARNING) << "Failed to stat " << path;
536 return 0;
537 } else {
538 return sb.st_dev;
539 }
540}
541
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700542std::string DefaultFstabPath() {
543 char hardware[PROPERTY_VALUE_MAX];
544 property_get("ro.hardware", hardware, "");
545 return StringPrintf("/fstab.%s", hardware);
546}
547
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800548} // namespace vold
549} // namespace android