blob: ec9c906dac939b80c2225aa59cb1ddc795696a8f [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 Sharkeydeb24052015-03-02 21:01:40 -080025#include <private/android_filesystem_config.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070026#include <logwrap/logwrap.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080027
Jeff Sharkeyce6a9132015-04-08 21:07:21 -070028#include <mutex>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070029#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080030#include <fcntl.h>
31#include <linux/fs.h>
32#include <stdlib.h>
33#include <sys/mount.h>
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/wait.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070037#include <sys/statvfs.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080038
39#ifndef UMOUNT_NOFOLLOW
40#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
41#endif
42
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070043using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070044using android::base::StringPrintf;
45
Jeff Sharkeydeb24052015-03-02 21:01:40 -080046namespace android {
47namespace vold {
48
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070049security_context_t sBlkidContext = nullptr;
50security_context_t sBlkidUntrustedContext = nullptr;
51security_context_t sFsckContext = nullptr;
52security_context_t sFsckUntrustedContext = nullptr;
53
Jeff Sharkey9c484982015-03-31 10:35:33 -070054static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070055static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070056
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070057static const char* kProcFilesystems = "/proc/filesystems";
58
Jeff Sharkeydeb24052015-03-02 21:01:40 -080059status_t CreateDeviceNode(const std::string& path, dev_t dev) {
60 const char* cpath = path.c_str();
61 status_t res = 0;
62
63 char* secontext = nullptr;
64 if (sehandle) {
65 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
66 setfscreatecon(secontext);
67 }
68 }
69
70 mode_t mode = 0660 | S_IFBLK;
71 if (mknod(cpath, mode, dev) < 0) {
72 if (errno != EEXIST) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070073 PLOG(ERROR) << "Failed to create device node for " << major(dev)
74 << ":" << minor(dev) << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080075 res = -errno;
76 }
77 }
78
79 if (secontext) {
80 setfscreatecon(nullptr);
81 freecon(secontext);
82 }
83
84 return res;
85}
86
87status_t DestroyDeviceNode(const std::string& path) {
88 const char* cpath = path.c_str();
89 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
90 return -errno;
91 } else {
92 return OK;
93 }
94}
95
Jeff Sharkeyf0121c52015-04-06 14:08:45 -070096status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
97 const char* cpath = path.c_str();
98
99 char* secontext = nullptr;
100 if (sehandle) {
101 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
102 setfscreatecon(secontext);
103 }
104 }
105
106 int res = fs_prepare_dir(cpath, mode, uid, gid);
107
108 if (secontext) {
109 setfscreatecon(nullptr);
110 freecon(secontext);
111 }
112
113 if (res == 0) {
114 return OK;
115 } else {
116 return -errno;
117 }
118}
119
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800120status_t ForceUnmount(const std::string& path) {
121 const char* cpath = path.c_str();
122 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
123 return OK;
124 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700125 PLOG(WARNING) << "Failed to unmount " << path;
126
127 sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700128 Process::killProcessesWithOpenFiles(cpath, SIGINT);
129
130 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
131 return OK;
132 }
133 PLOG(WARNING) << "Failed to unmount " << path;
134
135 sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800136 Process::killProcessesWithOpenFiles(cpath, SIGTERM);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800137
138 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
139 return OK;
140 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700141 PLOG(WARNING) << "Failed to unmount " << path;
142
143 sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800144 Process::killProcessesWithOpenFiles(cpath, SIGKILL);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800145
146 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
147 return OK;
148 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700149 PLOG(ERROR) << "Failed to unmount " << path;
150
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800151 return -errno;
152}
153
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700154status_t BindMount(const std::string& source, const std::string& target) {
155 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
156 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
157 return -errno;
158 }
159 return OK;
160}
161
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700162static status_t readMetadata(const std::string& path, std::string& fsType,
163 std::string& fsUuid, std::string& fsLabel, bool untrusted) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700164 fsType.clear();
165 fsUuid.clear();
166 fsLabel.clear();
167
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700168 std::vector<std::string> cmd;
169 cmd.push_back(kBlkidPath);
170 cmd.push_back("-c");
171 cmd.push_back("/dev/null");
172 cmd.push_back(path);
173
174 std::vector<std::string> output;
175 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
176 if (res != OK) {
177 LOG(WARNING) << "blkid failed to identify " << path;
178 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700179 }
180
Jeff Sharkey9c484982015-03-31 10:35:33 -0700181 char value[128];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700182 for (auto line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700183 // Extract values from blkid output, if defined
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700184 const char* cline = line.c_str();
185 char* start = strstr(cline, "TYPE=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700186 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
187 fsType = value;
188 }
189
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700190 start = strstr(cline, "UUID=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700191 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
192 fsUuid = value;
193 }
194
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700195 start = strstr(cline, "LABEL=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700196 if (start != nullptr && sscanf(start + 6, "\"%127[^\"]\"", value) == 1) {
197 fsLabel = value;
198 }
Jeff Sharkey9c484982015-03-31 10:35:33 -0700199 }
200
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700201 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700202}
203
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700204status_t ReadMetadata(const std::string& path, std::string& fsType,
205 std::string& fsUuid, std::string& fsLabel) {
206 return readMetadata(path, fsType, fsUuid, fsLabel, false);
207}
208
209status_t ReadMetadataUntrusted(const std::string& path, std::string& fsType,
210 std::string& fsUuid, std::string& fsLabel) {
211 return readMetadata(path, fsType, fsUuid, fsLabel, true);
212}
213
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700214status_t ForkExecvp(const std::vector<std::string>& args) {
215 return ForkExecvp(args, nullptr);
216}
217
218status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
219 size_t argc = args.size();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700220 char** argv = (char**) calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700221 for (size_t i = 0; i < argc; i++) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700222 argv[i] = (char*) args[i].c_str();
223 if (i == 0) {
224 LOG(VERBOSE) << args[i];
225 } else {
226 LOG(VERBOSE) << " " << args[i];
227 }
228 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700229
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700230 if (setexeccon(context)) {
231 LOG(ERROR) << "Failed to setexeccon";
232 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700233 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700234 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
235 if (setexeccon(nullptr)) {
236 LOG(ERROR) << "Failed to setexeccon";
237 abort();
238 }
239
Jeff Sharkey9c484982015-03-31 10:35:33 -0700240 free(argv);
241 return res;
242}
243
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700244status_t ForkExecvp(const std::vector<std::string>& args,
245 std::vector<std::string>& output) {
246 return ForkExecvp(args, output, nullptr);
247}
248
249status_t ForkExecvp(const std::vector<std::string>& args,
250 std::vector<std::string>& output, security_context_t context) {
251 std::string cmd;
252 for (size_t i = 0; i < args.size(); i++) {
253 cmd += args[i] + " ";
254 if (i == 0) {
255 LOG(VERBOSE) << args[i];
256 } else {
257 LOG(VERBOSE) << " " << args[i];
258 }
259 }
260 output.clear();
261
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700262 if (setexeccon(context)) {
263 LOG(ERROR) << "Failed to setexeccon";
264 abort();
265 }
266 FILE* fp = popen(cmd.c_str(), "r");
267 if (setexeccon(nullptr)) {
268 LOG(ERROR) << "Failed to setexeccon";
269 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700270 }
271
272 if (!fp) {
273 PLOG(ERROR) << "Failed to popen " << cmd;
274 return -errno;
275 }
276 char line[1024];
277 while (fgets(line, sizeof(line), fp) != nullptr) {
278 LOG(VERBOSE) << line;
279 output.push_back(std::string(line));
280 }
281 if (pclose(fp) != 0) {
282 PLOG(ERROR) << "Failed to pclose " << cmd;
283 return -errno;
284 }
285
286 return OK;
287}
288
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700289pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
290 size_t argc = args.size();
291 char** argv = (char**) calloc(argc + 1, sizeof(char*));
292 for (size_t i = 0; i < argc; i++) {
293 argv[i] = (char*) args[i].c_str();
294 if (i == 0) {
295 LOG(VERBOSE) << args[i];
296 } else {
297 LOG(VERBOSE) << " " << args[i];
298 }
299 }
300
301 pid_t pid = fork();
302 if (pid == 0) {
303 close(STDIN_FILENO);
304 close(STDOUT_FILENO);
305 close(STDERR_FILENO);
306
307 if (execvp(argv[0], argv)) {
308 PLOG(ERROR) << "Failed to exec";
309 }
310
311 _exit(1);
312 }
313
314 if (pid == -1) {
315 PLOG(ERROR) << "Failed to exec";
316 }
317
318 free(argv);
319 return pid;
320}
321
Jeff Sharkey9c484982015-03-31 10:35:33 -0700322status_t ReadRandomBytes(size_t bytes, std::string& out) {
323 out.clear();
324
325 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
326 if (fd == -1) {
327 return -errno;
328 }
329
330 char buf[BUFSIZ];
331 size_t n;
332 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], std::min(sizeof(buf), bytes)))) > 0) {
333 out.append(buf, n);
334 bytes -= n;
335 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700336 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700337
338 if (bytes == 0) {
339 return OK;
340 } else {
341 return -EIO;
342 }
343}
344
345status_t HexToStr(const std::string& hex, std::string& str) {
346 str.clear();
347 bool even = true;
348 char cur = 0;
349 for (size_t i = 0; i < hex.size(); i++) {
350 int val = 0;
351 switch (hex[i]) {
352 case ' ': case '-': case ':': continue;
353 case 'f': case 'F': val = 15; break;
354 case 'e': case 'E': val = 14; break;
355 case 'd': case 'D': val = 13; break;
356 case 'c': case 'C': val = 12; break;
357 case 'b': case 'B': val = 11; break;
358 case 'a': case 'A': val = 10; break;
359 case '9': val = 9; break;
360 case '8': val = 8; break;
361 case '7': val = 7; break;
362 case '6': val = 6; break;
363 case '5': val = 5; break;
364 case '4': val = 4; break;
365 case '3': val = 3; break;
366 case '2': val = 2; break;
367 case '1': val = 1; break;
368 case '0': val = 0; break;
369 default: return -EINVAL;
370 }
371
372 if (even) {
373 cur = val << 4;
374 } else {
375 cur += val;
376 str.push_back(cur);
377 cur = 0;
378 }
379 even = !even;
380 }
381 return even ? OK : -EINVAL;
382}
383
384static const char* kLookup = "0123456789abcdef";
385
386status_t StrToHex(const std::string& str, std::string& hex) {
387 hex.clear();
388 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700389 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700390 hex.push_back(kLookup[str[i] & 0x0F]);
391 }
392 return OK;
393}
394
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700395status_t NormalizeHex(const std::string& in, std::string& out) {
396 std::string tmp;
397 if (HexToStr(in, tmp)) {
398 return -EINVAL;
399 }
400 return StrToHex(tmp, out);
401}
402
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700403uint64_t GetFreeBytes(const std::string& path) {
404 struct statvfs sb;
405 if (statvfs(path.c_str(), &sb) == 0) {
406 return sb.f_bfree * sb.f_bsize;
407 } else {
408 return -1;
409 }
410}
411
412// TODO: borrowed from frameworks/native/libs/diskusage/ which should
413// eventually be migrated into system/
414static int64_t stat_size(struct stat *s) {
415 int64_t blksize = s->st_blksize;
416 // count actual blocks used instead of nominal file size
417 int64_t size = s->st_blocks * 512;
418
419 if (blksize) {
420 /* round up to filesystem block size */
421 size = (size + blksize - 1) & (~(blksize - 1));
422 }
423
424 return size;
425}
426
427// TODO: borrowed from frameworks/native/libs/diskusage/ which should
428// eventually be migrated into system/
429int64_t calculate_dir_size(int dfd) {
430 int64_t size = 0;
431 struct stat s;
432 DIR *d;
433 struct dirent *de;
434
435 d = fdopendir(dfd);
436 if (d == NULL) {
437 close(dfd);
438 return 0;
439 }
440
441 while ((de = readdir(d))) {
442 const char *name = de->d_name;
443 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
444 size += stat_size(&s);
445 }
446 if (de->d_type == DT_DIR) {
447 int subfd;
448
449 /* always skip "." and ".." */
450 if (name[0] == '.') {
451 if (name[1] == 0)
452 continue;
453 if ((name[1] == '.') && (name[2] == 0))
454 continue;
455 }
456
457 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
458 if (subfd >= 0) {
459 size += calculate_dir_size(subfd);
460 }
461 }
462 }
463 closedir(d);
464 return size;
465}
466
467uint64_t GetTreeBytes(const std::string& path) {
468 int dirfd = open(path.c_str(), O_DIRECTORY, O_RDONLY);
469 if (dirfd < 0) {
470 PLOG(WARNING) << "Failed to open " << path;
471 return -1;
472 } else {
473 uint64_t res = calculate_dir_size(dirfd);
474 close(dirfd);
475 return res;
476 }
477}
478
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700479bool IsFilesystemSupported(const std::string& fsType) {
480 std::string supported;
481 if (!ReadFileToString(kProcFilesystems, &supported)) {
482 PLOG(ERROR) << "Failed to read supported filesystems";
483 return false;
484 }
485 return supported.find(fsType + "\n") != std::string::npos;
486}
487
488status_t WipeBlockDevice(const std::string& path) {
489 status_t res = -1;
490 const char* c_path = path.c_str();
491 unsigned long nr_sec = 0;
492 unsigned long long range[2];
493
494 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
495 if (fd == -1) {
496 PLOG(ERROR) << "Failed to open " << path;
497 goto done;
498 }
499
500 if ((ioctl(fd, BLKGETSIZE, nr_sec)) == -1) {
501 PLOG(ERROR) << "Failed to determine size of " << path;
502 goto done;
503 }
504
505 range[0] = 0;
506 range[1] = (unsigned long long) nr_sec * 512;
507
508 LOG(INFO) << "About to discard " << range[1] << " on " << path;
509 if (ioctl(fd, BLKDISCARD, &range) == 0) {
510 LOG(INFO) << "Discard success on " << path;
511 res = 0;
512 } else {
513 PLOG(ERROR) << "Discard failure on " << path;
514 }
515
516done:
517 close(fd);
518 return res;
519}
520
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700521std::string BuildKeyPath(const std::string& partGuid) {
522 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
523}
524
Jeff Sharkey66270a22015-06-24 11:49:24 -0700525dev_t GetDevice(const std::string& path) {
526 struct stat sb;
527 if (stat(path.c_str(), &sb)) {
528 PLOG(WARNING) << "Failed to stat " << path;
529 return 0;
530 } else {
531 return sb.st_dev;
532 }
533}
534
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800535} // namespace vold
536} // namespace android