summaryrefslogtreecommitdiff
path: root/Utils.cpp (plain)
blob: 550a45616a937cb72aca31a8a9ea8d2af21509f8
1/*
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
17#include "Utils.h"
18#include "Process.h"
19
20#include <android-base/file.h>
21#include <android-base/logging.h>
22#include <android-base/stringprintf.h>
23#include <cutils/fs.h>
24#include <cutils/properties.h>
25#include <private/android_filesystem_config.h>
26#include <logwrap/logwrap.h>
27
28#include <mutex>
29#include <dirent.h>
30#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>
37#include <sys/statvfs.h>
38#include <sys/sysmacros.h>
39#include <stdio.h>
40#include <unistd.h>
41#include <string.h>
42
43
44#include "ext2fs/ext2fs.h"
45#include "blkid/blkid.h"
46
47#ifndef UMOUNT_NOFOLLOW
48#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
49#endif
50
51using android::base::ReadFileToString;
52using android::base::StringPrintf;
53
54namespace android {
55namespace droidvold {
56
57security_context_t sBlkidUntrustedContext = nullptr;
58
59static const char* kBlkidPath = "/system/bin/blkid";
60static const char* kKeyPath = "/data/misc/vold";
61
62static const char* kProcFilesystems = "/proc/filesystems";
63
64status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
65 const char* cpath = path.c_str();
66 int res = fs_prepare_dir(cpath, mode, uid, gid);
67
68 if (res == 0) {
69 return OK;
70 } else {
71 return -errno;
72 }
73}
74
75status_t ForceUnmount(const std::string& path) {
76 const char* cpath = path.c_str();
77 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
78 return OK;
79 }
80 // Apps might still be handling eject request, so wait before
81 // we start sending signals
82 sleep(5);
83
84 Process::killProcessesWithOpenFiles(cpath, SIGINT);
85 sleep(5);
86 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
87 return OK;
88 }
89
90 Process::killProcessesWithOpenFiles(cpath, SIGTERM);
91 sleep(5);
92 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
93 return OK;
94 }
95
96 Process::killProcessesWithOpenFiles(cpath, SIGKILL);
97 sleep(5);
98 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
99 return OK;
100 }
101
102 return -errno;
103}
104
105status_t KillProcessesUsingPath(const std::string& path) {
106 const char* cpath = path.c_str();
107 if (Process::killProcessesWithOpenFiles(cpath, SIGINT) == 0) {
108 return OK;
109 }
110 sleep(5);
111
112 if (Process::killProcessesWithOpenFiles(cpath, SIGTERM) == 0) {
113 return OK;
114 }
115 sleep(5);
116
117 if (Process::killProcessesWithOpenFiles(cpath, SIGKILL) == 0) {
118 return OK;
119 }
120 sleep(5);
121
122 // Send SIGKILL a second time to determine if we've
123 // actually killed everyone with open files
124 if (Process::killProcessesWithOpenFiles(cpath, SIGKILL) == 0) {
125 return OK;
126 }
127 PLOG(ERROR) << "Failed to kill processes using " << path;
128 return -EBUSY;
129}
130
131status_t BindMount(const std::string& source, const std::string& target) {
132 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
133 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
134 return -errno;
135 }
136 return OK;
137}
138
139status_t ReadPartMetadata(const std::string& path, std::string& fsType,
140 std::string& fsUuid, std::string& fsLabel) {
141 blkid_cache cache = NULL;
142 const char *devices = path.c_str();
143
144 if (blkid_get_cache(&cache, "/dev/null") < 0) {
145 PLOG(ERROR) << "blkid get cache failed path=" << path;
146 blkid_put_cache(cache);
147 return -errno;
148 }
149
150 blkid_dev dev = blkid_get_dev(cache, devices, BLKID_DEV_NORMAL);
151 if (dev) {
152 blkid_tag_iterate iter;
153 const char *type, *value;
154
155 iter = blkid_tag_iterate_begin(dev);
156 while (blkid_tag_next(iter, &type, &value) == 0) {
157 LOG(DEBUG) << "type=" << type << " value=" << value;
158
159 if (!strcmp(type, "TYPE")) {
160 fsType = StringPrintf("%s", value);
161 } else if (!strcmp(type, "UUID")) {
162 fsUuid = StringPrintf("%s", value);
163 } else if (!strcmp(type, "LABEL")) {
164 fsLabel = StringPrintf("%s", value);
165 }
166 }
167 blkid_tag_iterate_end(iter);
168 }
169
170 return OK;
171}
172
173
174status_t ForkExecvp(const std::vector<std::string>& args) {
175 return ForkExecvp(args, nullptr);
176}
177
178status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
179 size_t argc = args.size();
180 char** argv = (char**) calloc(argc, sizeof(char*));
181 for (size_t i = 0; i < argc; i++) {
182 argv[i] = (char*) args[i].c_str();
183 if (i == 0) {
184 LOG(VERBOSE) << args[i];
185 } else {
186 LOG(VERBOSE) << " " << args[i];
187 }
188 }
189
190 if (setexeccon(context)) {
191 LOG(ERROR) << "Failed to setexeccon";
192 abort();
193 }
194 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
195 if (setexeccon(nullptr)) {
196 LOG(ERROR) << "Failed to setexeccon";
197 abort();
198 }
199
200 free(argv);
201 return res;
202}
203
204status_t ForkExecvp(const std::vector<std::string>& args,
205 std::vector<std::string>& output) {
206 return ForkExecvp(args, output, nullptr);
207}
208
209status_t ForkExecvp(const std::vector<std::string>& args,
210 std::vector<std::string>& output, security_context_t context) {
211 std::string cmd;
212 for (size_t i = 0; i < args.size(); i++) {
213 cmd += args[i] + " ";
214 if (i == 0) {
215 LOG(VERBOSE) << args[i];
216 } else {
217 LOG(VERBOSE) << " " << args[i];
218 }
219 }
220 output.clear();
221
222 if (setexeccon(context)) {
223 LOG(ERROR) << "Failed to setexeccon";
224 abort();
225 }
226 FILE* fp = popen(cmd.c_str(), "r");
227 if (setexeccon(nullptr)) {
228 LOG(ERROR) << "Failed to setexeccon";
229 abort();
230 }
231
232 if (!fp) {
233 PLOG(ERROR) << "Failed to popen " << cmd;
234 return -errno;
235 }
236 char line[1024];
237 while (fgets(line, sizeof(line), fp) != nullptr) {
238 LOG(VERBOSE) << line;
239 output.push_back(std::string(line));
240 }
241 if (pclose(fp) != 0) {
242 PLOG(ERROR) << "Failed to pclose " << cmd;
243 return -errno;
244 }
245
246 return OK;
247}
248
249pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
250 size_t argc = args.size();
251 char** argv = (char**) calloc(argc + 1, sizeof(char*));
252 for (size_t i = 0; i < argc; i++) {
253 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 }
260
261 pid_t pid = fork();
262 if (pid == 0) {
263 close(STDIN_FILENO);
264 close(STDOUT_FILENO);
265 close(STDERR_FILENO);
266
267 if (execvp(argv[0], argv)) {
268 PLOG(ERROR) << "Failed to exec";
269 }
270
271 _exit(1);
272 }
273
274 if (pid == -1) {
275 PLOG(ERROR) << "Failed to exec";
276 }
277
278 free(argv);
279 return pid;
280}
281
282status_t ReadRandomBytes(size_t bytes, std::string& out) {
283 out.clear();
284
285 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
286 if (fd == -1) {
287 return -errno;
288 }
289
290 char buf[BUFSIZ];
291 size_t n;
292 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], std::min(sizeof(buf), bytes)))) > 0) {
293 out.append(buf, n);
294 bytes -= n;
295 }
296 close(fd);
297
298 if (bytes == 0) {
299 return OK;
300 } else {
301 return -EIO;
302 }
303}
304
305status_t HexToStr(const std::string& hex, std::string& str) {
306 str.clear();
307 bool even = true;
308 char cur = 0;
309 for (size_t i = 0; i < hex.size(); i++) {
310 int val = 0;
311 switch (hex[i]) {
312 case ' ': case '-': case ':': continue;
313 case 'f': case 'F': val = 15; break;
314 case 'e': case 'E': val = 14; break;
315 case 'd': case 'D': val = 13; break;
316 case 'c': case 'C': val = 12; break;
317 case 'b': case 'B': val = 11; break;
318 case 'a': case 'A': val = 10; break;
319 case '9': val = 9; break;
320 case '8': val = 8; break;
321 case '7': val = 7; break;
322 case '6': val = 6; break;
323 case '5': val = 5; break;
324 case '4': val = 4; break;
325 case '3': val = 3; break;
326 case '2': val = 2; break;
327 case '1': val = 1; break;
328 case '0': val = 0; break;
329 default: return -EINVAL;
330 }
331
332 if (even) {
333 cur = val << 4;
334 } else {
335 cur += val;
336 str.push_back(cur);
337 cur = 0;
338 }
339 even = !even;
340 }
341 return even ? OK : -EINVAL;
342}
343
344static const char* kLookup = "0123456789abcdef";
345
346status_t StrToHex(const std::string& str, std::string& hex) {
347 hex.clear();
348 for (size_t i = 0; i < str.size(); i++) {
349 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
350 hex.push_back(kLookup[str[i] & 0x0F]);
351 }
352 return OK;
353}
354
355status_t NormalizeHex(const std::string& in, std::string& out) {
356 std::string tmp;
357 if (HexToStr(in, tmp)) {
358 return -EINVAL;
359 }
360 return StrToHex(tmp, out);
361}
362
363uint64_t GetFreeBytes(const std::string& path) {
364 struct statvfs sb;
365 if (statvfs(path.c_str(), &sb) == 0) {
366 return (uint64_t)sb.f_bfree * sb.f_bsize;
367 } else {
368 return -1;
369 }
370}
371
372// TODO: borrowed from frameworks/native/libs/diskusage/ which should
373// eventually be migrated into system/
374static int64_t stat_size(struct stat *s) {
375 int64_t blksize = s->st_blksize;
376 // count actual blocks used instead of nominal file size
377 int64_t size = s->st_blocks * 512;
378
379 if (blksize) {
380 /* round up to filesystem block size */
381 size = (size + blksize - 1) & (~(blksize - 1));
382 }
383
384 return size;
385}
386
387// TODO: borrowed from frameworks/native/libs/diskusage/ which should
388// eventually be migrated into system/
389int64_t calculate_dir_size(int dfd) {
390 int64_t size = 0;
391 struct stat s;
392 DIR *d;
393 struct dirent *de;
394
395 d = fdopendir(dfd);
396 if (d == NULL) {
397 close(dfd);
398 return 0;
399 }
400
401 while ((de = readdir(d))) {
402 const char *name = de->d_name;
403 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
404 size += stat_size(&s);
405 }
406 if (de->d_type == DT_DIR) {
407 int subfd;
408
409 /* always skip "." and ".." */
410 if (name[0] == '.') {
411 if (name[1] == 0)
412 continue;
413 if ((name[1] == '.') && (name[2] == 0))
414 continue;
415 }
416
417 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
418 if (subfd >= 0) {
419 size += calculate_dir_size(subfd);
420 }
421 }
422 }
423 closedir(d);
424 return size;
425}
426
427uint64_t GetTreeBytes(const std::string& path) {
428 int dirfd = open(path.c_str(), O_DIRECTORY, O_RDONLY);
429 if (dirfd < 0) {
430 PLOG(WARNING) << "Failed to open " << path;
431 return -1;
432 } else {
433 uint64_t res = calculate_dir_size(dirfd);
434 close(dirfd);
435 return res;
436 }
437}
438
439bool IsFilesystemSupported(const std::string& fsType) {
440 std::string supported;
441 if (!ReadFileToString(kProcFilesystems, &supported)) {
442 PLOG(ERROR) << "Failed to read supported filesystems";
443 return false;
444 }
445 return supported.find(fsType + "\n") != std::string::npos;
446}
447
448status_t WipeBlockDevice(const std::string& path) {
449 status_t res = -1;
450 const char* c_path = path.c_str();
451 unsigned long nr_sec = 0;
452 unsigned long long range[2];
453
454 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
455 if (fd == -1) {
456 PLOG(ERROR) << "Failed to open " << path;
457 goto done;
458 }
459
460 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
461 PLOG(ERROR) << "Failed to determine size of " << path;
462 goto done;
463 }
464
465 range[0] = 0;
466 range[1] = (unsigned long long) nr_sec * 512;
467
468 LOG(INFO) << "About to discard " << range[1] << " on " << path;
469 if (ioctl(fd, BLKDISCARD, &range) == 0) {
470 LOG(INFO) << "Discard success on " << path;
471 res = 0;
472 } else {
473 PLOG(ERROR) << "Discard failure on " << path;
474 }
475
476done:
477 close(fd);
478 return res;
479}
480
481std::string BuildDataUserDePath(const char* volumeUuid, userid_t userId) {
482 // TODO: unify with installd path generation logic
483 std::string data(BuildDataPath(volumeUuid));
484 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
485}
486
487dev_t GetDevice(const std::string& path) {
488 struct stat sb;
489 if (stat(path.c_str(), &sb)) {
490 PLOG(WARNING) << "Failed to stat " << path;
491 return 0;
492 } else {
493 return sb.st_dev;
494 }
495}
496
497std::string DefaultFstabPath() {
498 char hardware[PROPERTY_VALUE_MAX];
499 property_get("ro.hardware", hardware, "");
500 return StringPrintf("/fstab.%s", hardware);
501}
502
503status_t RestoreconRecursive(const std::string& path) {
504 LOG(VERBOSE) << "Starting restorecon of " << path;
505
506 // TODO: find a cleaner way of waiting for restorecon to finish
507 const char* cpath = path.c_str();
508 property_set("selinux.restorecon_recursive", "");
509 property_set("selinux.restorecon_recursive", cpath);
510
511 char value[PROPERTY_VALUE_MAX];
512 while (true) {
513 property_get("selinux.restorecon_recursive", value, "");
514 if (strcmp(cpath, value) == 0) {
515 break;
516 }
517 usleep(100000); // 100ms
518 }
519
520 LOG(VERBOSE) << "Finished restorecon of " << path;
521 return OK;
522}
523
524status_t SaneReadLinkAt(int dirfd, const char* path, char* buf, size_t bufsiz) {
525 ssize_t len = readlinkat(dirfd, path, buf, bufsiz);
526 if (len < 0) {
527 return -1;
528 } else if (len == (ssize_t) bufsiz) {
529 return -1;
530 } else {
531 buf[len] = '\0';
532 return 0;
533 }
534}
535
536ScopedFd::ScopedFd(int fd) : fd_(fd) {}
537
538ScopedFd::~ScopedFd() {
539 close(fd_);
540}
541
542ScopedDir::ScopedDir(DIR* dir) : dir_(dir) {}
543
544ScopedDir::~ScopedDir() {
545 if (dir_ != nullptr) {
546 closedir(dir_);
547 }
548}
549
550bool IsRunningInEmulator() {
551 return property_get_bool("ro.kernel.qemu", 0);
552}
553
554status_t readBlockDevMajorAndMinor(
555 const std::string& devPath,
556 std::string& major, std::string& minor) {
557 major.clear();
558 minor.clear();
559
560 std::vector<std::string> cmd;
561 cmd.push_back("/system/bin/ls");
562 cmd.push_back("-l");
563 cmd.push_back(devPath);
564
565 std::vector<std::string> output;
566 status_t res = ForkExecvp(cmd, output);
567 if (res != OK) {
568 LOG(WARNING) << "failed to identify ls -l " << devPath;
569 return res;
570 }
571
572 // Extract values from output
573 // brw------- root root 179, 1 2015-01-01 00:00 mmcblk0p1
574 char value[128];
575 for (auto line : output) {
576 int count = sscanf(line.c_str(), "%3s", value);
577 if (count == 1 && !strcmp(value, "brw")) { // block device
578 char f[128], s[128];
579 if (sscanf(line.c_str(), "%[^','],%s", f, s) == 2) { // split ','
580 minor = s;
581 char *cline = strdup(f);
582 char *str = strtok(cline, " ");
583 char buf[25];
584 while (str != nullptr) {
585 if (sscanf(str, "%[1-9]", buf) == 1) {
586 major = buf;
587 }
588 str = strtok(nullptr, " ");
589 }
590 }
591 }
592 }
593
594 return OK;
595}
596
597// Get physical device path (such as /dev/block/sda) by kernel event sys path
598status_t GetPhysicalDevice(
599 const std::string& sysPath, std::string& physicalDev) {
600 int iPos = sysPath.find("/block/");
601 if (iPos < 0) {
602 LOG(WARNING) << "can't find \"/block/\" in " << sysPath;
603 return -1;
604 }
605
606 physicalDev = StringPrintf("/dev/block/%s", sysPath.substr(iPos + 7).c_str());
607 if (access(physicalDev.c_str(), F_OK)) {
608 LOG(INFO) << "physical dev: " << physicalDev + " doesn't exist";
609 return -1;
610 }
611
612 return OK;
613}
614
615// /sys//devices/d0072000.sd/mmc_host/sd/sd:0007/block/mmcblk0
616// /sys//devices/dwc2_b/usb1/1-1/1-1.2/1-1.2:1.0/host0/target0:0:0/0:0:0:0/block/sda
617status_t GetLogicalPartitionDevice(
618 const dev_t device, const std::string& sysPath, std::string& logicalPartitionDev) {
619 std::string physicalDev;
620 const unsigned int kMajorBlockMmc = 179;
621 const unsigned int kMaxNumOfPartition = 31;
622
623 // logical partition dev's major & minor
624 unsigned int devMajor = major(device);
625 unsigned int devMinor = minor(device);
626
627 if (GetPhysicalDevice(sysPath, physicalDev) != OK) {
628 return -1;
629 }
630
631 LOG(INFO) << "physical dev: " << physicalDev <<
632 ", logical partition dev's major: " << devMajor << ", minor: " << devMinor;
633
634 // For now, assume that MMC devices are SD, and that
635 // everything else is USB
636 std::string lpDev;
637 std::string major, minor;
638 for (unsigned int i = 1; i <= kMaxNumOfPartition; i ++) {
639 if (devMajor == kMajorBlockMmc) { // SD
640 lpDev = StringPrintf("%sp%d", physicalDev.c_str(), i);
641 } else { // USB
642 lpDev = StringPrintf("%s%d", physicalDev.c_str(), i);
643 }
644
645 if (!access(lpDev.c_str(), F_OK) &&
646 readBlockDevMajorAndMinor(lpDev, major, minor) == OK &&
647 (int)devMajor == atoi(major.c_str()) &&
648 (int)devMinor == atoi(minor.c_str())) {
649 logicalPartitionDev = lpDev;
650 LOG(INFO) << "find logical partition dev: " << logicalPartitionDev;
651 break;
652 }
653 }
654
655 return OK;
656}
657
658// Such as /dev/block/sda is used, return true,otherwise false
659// just true,saved sda to physicalDevName
660bool IsJustPhysicalDevice(
661 const std::string& sysPath, std::string& physicalDevName) {
662 std::string major, minor;
663 std::string physicalDev;
664 std::string logicalPartitionDev;
665 const unsigned int kMajorBlockMmc = 179;
666
667 if (GetPhysicalDevice(sysPath, physicalDev) == OK) {
668 std::vector<std::string> cmd;
669 cmd.push_back(kBlkidPath);
670 cmd.push_back("-c");
671 cmd.push_back("/dev/null");
672 cmd.push_back("-s");
673 cmd.push_back("TYPE");
674 cmd.push_back("-s");
675 cmd.push_back("UUID");
676 cmd.push_back("-s");
677 cmd.push_back("LABEL");
678 cmd.push_back(physicalDev);
679
680 std::vector<std::string> output;
681 status_t res = ForkExecvp(cmd, output, sBlkidUntrustedContext);
682 if (res != OK) {
683 LOG(WARNING) << "failed to identify blkid " << physicalDev;
684 return false;
685 }
686
687 char value[128];
688 for (auto line : output) {
689 // Extract values from blkid output, if defined
690 const char* cline = line.c_str();
691 if (!strncmp(cline, physicalDev.c_str(), strlen(physicalDev.c_str()))) {
692 if (readBlockDevMajorAndMinor(physicalDev, major, minor) == OK) {
693 logicalPartitionDev = (atoi(major.c_str()) == kMajorBlockMmc) ?
694 StringPrintf("%sp1", physicalDev.c_str()) :
695 StringPrintf("%s1", physicalDev.c_str());
696 if (access(logicalPartitionDev.c_str(), F_OK)) {
697 // And logical partition device doesn't exist,
698 // we're sure physical device is used.
699 // length /dev/block/ = 11,such as sda or mmcblk0,
700 // we get as physical device name.
701 physicalDevName = StringPrintf("%s", physicalDev.substr(11).c_str());
702 return true;
703 }
704 }
705 }
706 }
707 }
708
709 return false;
710}
711
712} // namespace vold
713} // namespace android
714