Utils.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. #include "Utils.h"
  17. #include "Process.h"
  18. #include "sehandle.h"
  19. #include <android-base/chrono_utils.h>
  20. #include <android-base/file.h>
  21. #include <android-base/logging.h>
  22. #include <android-base/properties.h>
  23. #include <android-base/stringprintf.h>
  24. #include <android-base/strings.h>
  25. #include <android-base/unique_fd.h>
  26. #include <cutils/fs.h>
  27. #include <logwrap/logwrap.h>
  28. #include <private/android_filesystem_config.h>
  29. #include <dirent.h>
  30. #include <fcntl.h>
  31. #include <linux/fs.h>
  32. #include <mntent.h>
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <unistd.h>
  36. #include <sys/mount.h>
  37. #include <sys/stat.h>
  38. #include <sys/statvfs.h>
  39. #include <sys/sysmacros.h>
  40. #include <sys/types.h>
  41. #include <sys/wait.h>
  42. #include <list>
  43. #include <mutex>
  44. #include <thread>
  45. #ifndef UMOUNT_NOFOLLOW
  46. #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
  47. #endif
  48. using namespace std::chrono_literals;
  49. using android::base::ReadFileToString;
  50. using android::base::StringPrintf;
  51. namespace android {
  52. namespace vold {
  53. security_context_t sBlkidContext = nullptr;
  54. security_context_t sBlkidUntrustedContext = nullptr;
  55. security_context_t sFsckContext = nullptr;
  56. security_context_t sFsckUntrustedContext = nullptr;
  57. bool sSleepOnUnmount = true;
  58. static const char* kBlkidPath = "/system/bin/blkid";
  59. static const char* kKeyPath = "/data/misc/vold";
  60. static const char* kProcFilesystems = "/proc/filesystems";
  61. // Lock used to protect process-level SELinux changes from racing with each
  62. // other between multiple threads.
  63. static std::mutex kSecurityLock;
  64. status_t CreateDeviceNode(const std::string& path, dev_t dev) {
  65. std::lock_guard<std::mutex> lock(kSecurityLock);
  66. const char* cpath = path.c_str();
  67. status_t res = 0;
  68. char* secontext = nullptr;
  69. if (sehandle) {
  70. if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
  71. setfscreatecon(secontext);
  72. }
  73. }
  74. mode_t mode = 0660 | S_IFBLK;
  75. if (mknod(cpath, mode, dev) < 0) {
  76. if (errno != EEXIST) {
  77. PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
  78. << " at " << path;
  79. res = -errno;
  80. }
  81. }
  82. if (secontext) {
  83. setfscreatecon(nullptr);
  84. freecon(secontext);
  85. }
  86. return res;
  87. }
  88. status_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. status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
  97. std::lock_guard<std::mutex> lock(kSecurityLock);
  98. const char* cpath = path.c_str();
  99. char* secontext = nullptr;
  100. if (sehandle) {
  101. if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
  102. setfscreatecon(secontext);
  103. }
  104. }
  105. int res = fs_prepare_dir(cpath, mode, uid, gid);
  106. if (secontext) {
  107. setfscreatecon(nullptr);
  108. freecon(secontext);
  109. }
  110. if (res == 0) {
  111. return OK;
  112. } else {
  113. return -errno;
  114. }
  115. }
  116. status_t ForceUnmount(const std::string& path) {
  117. const char* cpath = path.c_str();
  118. if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
  119. return OK;
  120. }
  121. // Apps might still be handling eject request, so wait before
  122. // we start sending signals
  123. if (sSleepOnUnmount) sleep(5);
  124. KillProcessesWithOpenFiles(path, SIGINT);
  125. if (sSleepOnUnmount) sleep(5);
  126. if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
  127. return OK;
  128. }
  129. KillProcessesWithOpenFiles(path, SIGTERM);
  130. if (sSleepOnUnmount) sleep(5);
  131. if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
  132. return OK;
  133. }
  134. KillProcessesWithOpenFiles(path, SIGKILL);
  135. if (sSleepOnUnmount) sleep(5);
  136. if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
  137. return OK;
  138. }
  139. return -errno;
  140. }
  141. status_t KillProcessesUsingPath(const std::string& path) {
  142. if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
  143. return OK;
  144. }
  145. if (sSleepOnUnmount) sleep(5);
  146. if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
  147. return OK;
  148. }
  149. if (sSleepOnUnmount) sleep(5);
  150. if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
  151. return OK;
  152. }
  153. if (sSleepOnUnmount) sleep(5);
  154. // Send SIGKILL a second time to determine if we've
  155. // actually killed everyone with open files
  156. if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
  157. return OK;
  158. }
  159. PLOG(ERROR) << "Failed to kill processes using " << path;
  160. return -EBUSY;
  161. }
  162. status_t BindMount(const std::string& source, const std::string& target) {
  163. if (UnmountTree(target) < 0) {
  164. return -errno;
  165. }
  166. if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
  167. PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
  168. return -errno;
  169. }
  170. return OK;
  171. }
  172. status_t Symlink(const std::string& target, const std::string& linkpath) {
  173. if (Unlink(linkpath) < 0) {
  174. return -errno;
  175. }
  176. if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
  177. PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
  178. return -errno;
  179. }
  180. return OK;
  181. }
  182. status_t Unlink(const std::string& linkpath) {
  183. if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
  184. PLOG(ERROR) << "Failed to unlink " << linkpath;
  185. return -errno;
  186. }
  187. return OK;
  188. }
  189. status_t CreateDir(const std::string& dir, mode_t mode) {
  190. struct stat sb;
  191. if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
  192. if (S_ISDIR(sb.st_mode)) {
  193. return OK;
  194. } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
  195. PLOG(ERROR) << "Failed to unlink " << dir;
  196. return -errno;
  197. }
  198. } else if (errno != ENOENT) {
  199. PLOG(ERROR) << "Failed to stat " << dir;
  200. return -errno;
  201. }
  202. if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
  203. PLOG(ERROR) << "Failed to mkdir " << dir;
  204. return -errno;
  205. }
  206. return OK;
  207. }
  208. bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
  209. auto qual = key + "=\"";
  210. size_t start = 0;
  211. while (true) {
  212. start = raw.find(qual, start);
  213. if (start == std::string::npos) return false;
  214. if (start == 0 || raw[start - 1] == ' ') {
  215. break;
  216. }
  217. start += 1;
  218. }
  219. start += qual.length();
  220. auto end = raw.find("\"", start);
  221. if (end == std::string::npos) return false;
  222. *value = raw.substr(start, end - start);
  223. return true;
  224. }
  225. static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
  226. std::string* fsLabel, bool untrusted) {
  227. fsType->clear();
  228. fsUuid->clear();
  229. fsLabel->clear();
  230. std::vector<std::string> cmd;
  231. cmd.push_back(kBlkidPath);
  232. cmd.push_back("-c");
  233. cmd.push_back("/dev/null");
  234. cmd.push_back("-s");
  235. cmd.push_back("TYPE");
  236. cmd.push_back("-s");
  237. cmd.push_back("UUID");
  238. cmd.push_back("-s");
  239. cmd.push_back("LABEL");
  240. cmd.push_back(path);
  241. std::vector<std::string> output;
  242. status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
  243. if (res != OK) {
  244. LOG(WARNING) << "blkid failed to identify " << path;
  245. return res;
  246. }
  247. for (const auto& line : output) {
  248. // Extract values from blkid output, if defined
  249. FindValue(line, "TYPE", fsType);
  250. FindValue(line, "UUID", fsUuid);
  251. FindValue(line, "LABEL", fsLabel);
  252. }
  253. return OK;
  254. }
  255. status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
  256. std::string* fsLabel) {
  257. return readMetadata(path, fsType, fsUuid, fsLabel, false);
  258. }
  259. status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
  260. std::string* fsLabel) {
  261. return readMetadata(path, fsType, fsUuid, fsLabel, true);
  262. }
  263. static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
  264. std::vector<const char*> argv;
  265. argv.reserve(args.size() + 1);
  266. for (const auto& arg : args) {
  267. if (argv.empty()) {
  268. LOG(DEBUG) << arg;
  269. } else {
  270. LOG(DEBUG) << " " << arg;
  271. }
  272. argv.emplace_back(arg.data());
  273. }
  274. argv.emplace_back(nullptr);
  275. return argv;
  276. }
  277. static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
  278. android::base::unique_fd ufd) {
  279. std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
  280. if (!fp) {
  281. PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
  282. return -errno;
  283. }
  284. if (output) output->clear();
  285. char line[1024];
  286. while (fgets(line, sizeof(line), fp.get()) != nullptr) {
  287. LOG(DEBUG) << line;
  288. if (output) output->emplace_back(line);
  289. }
  290. return OK;
  291. }
  292. status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
  293. security_context_t context) {
  294. auto argv = ConvertToArgv(args);
  295. android::base::unique_fd pipe_read, pipe_write;
  296. if (!android::base::Pipe(&pipe_read, &pipe_write)) {
  297. PLOG(ERROR) << "Pipe in ForkExecvp";
  298. return -errno;
  299. }
  300. pid_t pid = fork();
  301. if (pid == 0) {
  302. if (context) {
  303. if (setexeccon(context)) {
  304. LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
  305. abort();
  306. }
  307. }
  308. pipe_read.reset();
  309. if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
  310. PLOG(ERROR) << "dup2 in ForkExecvp";
  311. _exit(EXIT_FAILURE);
  312. }
  313. pipe_write.reset();
  314. execvp(argv[0], const_cast<char**>(argv.data()));
  315. PLOG(ERROR) << "exec in ForkExecvp";
  316. _exit(EXIT_FAILURE);
  317. }
  318. if (pid == -1) {
  319. PLOG(ERROR) << "fork in ForkExecvp";
  320. return -errno;
  321. }
  322. pipe_write.reset();
  323. auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
  324. if (st != 0) return st;
  325. int status;
  326. if (waitpid(pid, &status, 0) == -1) {
  327. PLOG(ERROR) << "waitpid in ForkExecvp";
  328. return -errno;
  329. }
  330. if (!WIFEXITED(status)) {
  331. LOG(ERROR) << "Process did not exit normally, status: " << status;
  332. return -ECHILD;
  333. }
  334. if (WEXITSTATUS(status)) {
  335. LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
  336. return WEXITSTATUS(status);
  337. }
  338. return OK;
  339. }
  340. pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
  341. auto argv = ConvertToArgv(args);
  342. pid_t pid = fork();
  343. if (pid == 0) {
  344. close(STDIN_FILENO);
  345. close(STDOUT_FILENO);
  346. close(STDERR_FILENO);
  347. execvp(argv[0], const_cast<char**>(argv.data()));
  348. PLOG(ERROR) << "exec in ForkExecvpAsync";
  349. _exit(EXIT_FAILURE);
  350. }
  351. if (pid == -1) {
  352. PLOG(ERROR) << "fork in ForkExecvpAsync";
  353. return -1;
  354. }
  355. return pid;
  356. }
  357. status_t ReadRandomBytes(size_t bytes, std::string& out) {
  358. out.resize(bytes);
  359. return ReadRandomBytes(bytes, &out[0]);
  360. }
  361. status_t ReadRandomBytes(size_t bytes, char* buf) {
  362. int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
  363. if (fd == -1) {
  364. return -errno;
  365. }
  366. ssize_t n;
  367. while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
  368. bytes -= n;
  369. buf += n;
  370. }
  371. close(fd);
  372. if (bytes == 0) {
  373. return OK;
  374. } else {
  375. return -EIO;
  376. }
  377. }
  378. status_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. status_t HexToStr(const std::string& hex, std::string& str) {
  389. str.clear();
  390. bool even = true;
  391. char cur = 0;
  392. for (size_t i = 0; i < hex.size(); i++) {
  393. int val = 0;
  394. switch (hex[i]) {
  395. // clang-format off
  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. // clang-format on
  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. static const char* kLookup = "0123456789abcdef";
  428. status_t StrToHex(const std::string& str, std::string& hex) {
  429. hex.clear();
  430. for (size_t i = 0; i < str.size(); i++) {
  431. hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
  432. hex.push_back(kLookup[str[i] & 0x0F]);
  433. }
  434. return OK;
  435. }
  436. status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
  437. hex.clear();
  438. for (size_t i = 0; i < str.size(); i++) {
  439. hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
  440. hex.push_back(kLookup[str.data()[i] & 0x0F]);
  441. }
  442. return OK;
  443. }
  444. status_t NormalizeHex(const std::string& in, std::string& out) {
  445. std::string tmp;
  446. if (HexToStr(in, tmp)) {
  447. return -EINVAL;
  448. }
  449. return StrToHex(tmp, out);
  450. }
  451. status_t GetBlockDevSize(int fd, uint64_t* size) {
  452. if (ioctl(fd, BLKGETSIZE64, size)) {
  453. return -errno;
  454. }
  455. return OK;
  456. }
  457. status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
  458. int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
  459. status_t res = OK;
  460. if (fd < 0) {
  461. return -errno;
  462. }
  463. res = GetBlockDevSize(fd, size);
  464. close(fd);
  465. return res;
  466. }
  467. status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
  468. uint64_t size;
  469. status_t res = GetBlockDevSize(path, &size);
  470. if (res != OK) {
  471. return res;
  472. }
  473. *nr_sec = size / 512;
  474. return OK;
  475. }
  476. uint64_t GetFreeBytes(const std::string& path) {
  477. struct statvfs sb;
  478. if (statvfs(path.c_str(), &sb) == 0) {
  479. return (uint64_t)sb.f_bavail * sb.f_frsize;
  480. } else {
  481. return -1;
  482. }
  483. }
  484. // TODO: borrowed from frameworks/native/libs/diskusage/ which should
  485. // eventually be migrated into system/
  486. static int64_t stat_size(struct stat* s) {
  487. int64_t blksize = s->st_blksize;
  488. // count actual blocks used instead of nominal file size
  489. int64_t size = s->st_blocks * 512;
  490. if (blksize) {
  491. /* round up to filesystem block size */
  492. size = (size + blksize - 1) & (~(blksize - 1));
  493. }
  494. return size;
  495. }
  496. // TODO: borrowed from frameworks/native/libs/diskusage/ which should
  497. // eventually be migrated into system/
  498. int64_t calculate_dir_size(int dfd) {
  499. int64_t size = 0;
  500. struct stat s;
  501. DIR* d;
  502. struct dirent* de;
  503. d = fdopendir(dfd);
  504. if (d == NULL) {
  505. close(dfd);
  506. return 0;
  507. }
  508. while ((de = readdir(d))) {
  509. const char* name = de->d_name;
  510. if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
  511. size += stat_size(&s);
  512. }
  513. if (de->d_type == DT_DIR) {
  514. int subfd;
  515. /* always skip "." and ".." */
  516. if (name[0] == '.') {
  517. if (name[1] == 0) continue;
  518. if ((name[1] == '.') && (name[2] == 0)) continue;
  519. }
  520. subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
  521. if (subfd >= 0) {
  522. size += calculate_dir_size(subfd);
  523. }
  524. }
  525. }
  526. closedir(d);
  527. return size;
  528. }
  529. uint64_t GetTreeBytes(const std::string& path) {
  530. int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
  531. if (dirfd < 0) {
  532. PLOG(WARNING) << "Failed to open " << path;
  533. return -1;
  534. } else {
  535. return calculate_dir_size(dirfd);
  536. }
  537. }
  538. bool IsFilesystemSupported(const std::string& fsType) {
  539. std::string supported;
  540. if (!ReadFileToString(kProcFilesystems, &supported)) {
  541. PLOG(ERROR) << "Failed to read supported filesystems";
  542. return false;
  543. }
  544. return supported.find(fsType + "\n") != std::string::npos;
  545. }
  546. status_t WipeBlockDevice(const std::string& path) {
  547. status_t res = -1;
  548. const char* c_path = path.c_str();
  549. uint64_t range[2] = {0, 0};
  550. int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
  551. if (fd == -1) {
  552. PLOG(ERROR) << "Failed to open " << path;
  553. goto done;
  554. }
  555. if (GetBlockDevSize(fd, &range[1]) != OK) {
  556. PLOG(ERROR) << "Failed to determine size of " << path;
  557. goto done;
  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. done:
  567. close(fd);
  568. return res;
  569. }
  570. static bool isValidFilename(const std::string& name) {
  571. if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
  572. return false;
  573. } else {
  574. return true;
  575. }
  576. }
  577. std::string BuildKeyPath(const std::string& partGuid) {
  578. return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
  579. }
  580. std::string BuildDataSystemLegacyPath(userid_t userId) {
  581. return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
  582. }
  583. std::string BuildDataSystemCePath(userid_t userId) {
  584. return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
  585. }
  586. std::string BuildDataSystemDePath(userid_t userId) {
  587. return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
  588. }
  589. std::string BuildDataMiscLegacyPath(userid_t userId) {
  590. return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
  591. }
  592. std::string BuildDataMiscCePath(userid_t userId) {
  593. return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
  594. }
  595. std::string BuildDataMiscDePath(userid_t userId) {
  596. return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
  597. }
  598. // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
  599. std::string BuildDataProfilesDePath(userid_t userId) {
  600. return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
  601. }
  602. std::string BuildDataVendorCePath(userid_t userId) {
  603. return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
  604. }
  605. std::string BuildDataVendorDePath(userid_t userId) {
  606. return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
  607. }
  608. std::string BuildDataPath(const std::string& volumeUuid) {
  609. // TODO: unify with installd path generation logic
  610. if (volumeUuid.empty()) {
  611. return "/data";
  612. } else {
  613. CHECK(isValidFilename(volumeUuid));
  614. return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
  615. }
  616. }
  617. std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
  618. // TODO: unify with installd path generation logic
  619. std::string data(BuildDataPath(volumeUuid));
  620. return StringPrintf("%s/media/%u", data.c_str(), userId);
  621. }
  622. std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
  623. // TODO: unify with installd path generation logic
  624. std::string data(BuildDataPath(volumeUuid));
  625. if (volumeUuid.empty() && userId == 0) {
  626. std::string legacy = StringPrintf("%s/data", data.c_str());
  627. struct stat sb;
  628. if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
  629. /* /data/data is dir, return /data/data for legacy system */
  630. return legacy;
  631. }
  632. }
  633. return StringPrintf("%s/user/%u", data.c_str(), userId);
  634. }
  635. std::string BuildDataUserDePath(const std::string& 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. dev_t GetDevice(const std::string& path) {
  641. struct stat sb;
  642. if (stat(path.c_str(), &sb)) {
  643. PLOG(WARNING) << "Failed to stat " << path;
  644. return 0;
  645. } else {
  646. return sb.st_dev;
  647. }
  648. }
  649. status_t RestoreconRecursive(const std::string& path) {
  650. LOG(DEBUG) << "Starting restorecon of " << path;
  651. static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
  652. android::base::SetProperty(kRestoreconString, "");
  653. android::base::SetProperty(kRestoreconString, path);
  654. android::base::WaitForProperty(kRestoreconString, path);
  655. LOG(DEBUG) << "Finished restorecon of " << path;
  656. return OK;
  657. }
  658. bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
  659. // Shamelessly borrowed from android::base::Readlink()
  660. result->clear();
  661. // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
  662. // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
  663. // waste memory to just start there. We add 1 so that we can recognize
  664. // whether it actually fit (rather than being truncated to 4095).
  665. std::vector<char> buf(4095 + 1);
  666. while (true) {
  667. ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
  668. // Unrecoverable error?
  669. if (size == -1) return false;
  670. // It fit! (If size == buf.size(), it may have been truncated.)
  671. if (static_cast<size_t>(size) < buf.size()) {
  672. result->assign(&buf[0], size);
  673. return true;
  674. }
  675. // Double our buffer and try again.
  676. buf.resize(buf.size() * 2);
  677. }
  678. }
  679. bool IsRunningInEmulator() {
  680. return android::base::GetBoolProperty("ro.kernel.qemu", false);
  681. }
  682. static status_t findMountPointsWithPrefix(const std::string& prefix,
  683. std::list<std::string>& mountPoints) {
  684. // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
  685. // when the prefix is /foo/bar
  686. std::string prefixWithSlash(prefix);
  687. if (prefix.back() != '/') {
  688. android::base::StringAppendF(&prefixWithSlash, "/");
  689. }
  690. std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
  691. if (!mnts) {
  692. PLOG(ERROR) << "Unable to open /proc/mounts";
  693. return -errno;
  694. }
  695. // Some volumes can be stacked on each other, so force unmount in
  696. // reverse order to give us the best chance of success.
  697. struct mntent* mnt; // getmntent returns a thread local, so it's safe.
  698. while ((mnt = getmntent(mnts.get())) != nullptr) {
  699. auto mountPoint = std::string(mnt->mnt_dir) + "/";
  700. if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
  701. mountPoints.push_front(mountPoint);
  702. }
  703. }
  704. return OK;
  705. }
  706. // Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
  707. status_t UnmountTreeWithPrefix(const std::string& prefix) {
  708. std::list<std::string> toUnmount;
  709. status_t result = findMountPointsWithPrefix(prefix, toUnmount);
  710. if (result < 0) {
  711. return result;
  712. }
  713. for (const auto& path : toUnmount) {
  714. if (umount2(path.c_str(), MNT_DETACH)) {
  715. PLOG(ERROR) << "Failed to unmount " << path;
  716. result = -errno;
  717. }
  718. }
  719. return result;
  720. }
  721. status_t UnmountTree(const std::string& mountPoint) {
  722. if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
  723. errno != ENOENT) {
  724. PLOG(ERROR) << "Failed to unmount " << mountPoint;
  725. return -errno;
  726. }
  727. return OK;
  728. }
  729. static status_t delete_dir_contents(DIR* dir) {
  730. // Shamelessly borrowed from android::installd
  731. int dfd = dirfd(dir);
  732. if (dfd < 0) {
  733. return -errno;
  734. }
  735. status_t result = OK;
  736. struct dirent* de;
  737. while ((de = readdir(dir))) {
  738. const char* name = de->d_name;
  739. if (de->d_type == DT_DIR) {
  740. /* always skip "." and ".." */
  741. if (name[0] == '.') {
  742. if (name[1] == 0) continue;
  743. if ((name[1] == '.') && (name[2] == 0)) continue;
  744. }
  745. android::base::unique_fd subfd(
  746. openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
  747. if (subfd.get() == -1) {
  748. PLOG(ERROR) << "Couldn't openat " << name;
  749. result = -errno;
  750. continue;
  751. }
  752. std::unique_ptr<DIR, decltype(&closedir)> subdirp(
  753. android::base::Fdopendir(std::move(subfd)), closedir);
  754. if (!subdirp) {
  755. PLOG(ERROR) << "Couldn't fdopendir " << name;
  756. result = -errno;
  757. continue;
  758. }
  759. result = delete_dir_contents(subdirp.get());
  760. if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
  761. PLOG(ERROR) << "Couldn't unlinkat " << name;
  762. result = -errno;
  763. }
  764. } else {
  765. if (unlinkat(dfd, name, 0) < 0) {
  766. PLOG(ERROR) << "Couldn't unlinkat " << name;
  767. result = -errno;
  768. }
  769. }
  770. }
  771. return result;
  772. }
  773. status_t DeleteDirContentsAndDir(const std::string& pathname) {
  774. status_t res = DeleteDirContents(pathname);
  775. if (res < 0) {
  776. return res;
  777. }
  778. if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
  779. PLOG(ERROR) << "rmdir failed on " << pathname;
  780. return -errno;
  781. }
  782. LOG(VERBOSE) << "Success: rmdir on " << pathname;
  783. return OK;
  784. }
  785. status_t DeleteDirContents(const std::string& pathname) {
  786. // Shamelessly borrowed from android::installd
  787. std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
  788. if (!dirp) {
  789. if (errno == ENOENT) {
  790. return OK;
  791. }
  792. PLOG(ERROR) << "Failed to opendir " << pathname;
  793. return -errno;
  794. }
  795. return delete_dir_contents(dirp.get());
  796. }
  797. // TODO(118708649): fix duplication with init/util.h
  798. status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
  799. android::base::Timer t;
  800. while (t.duration() < timeout) {
  801. struct stat sb;
  802. if (stat(filename, &sb) != -1) {
  803. LOG(INFO) << "wait for '" << filename << "' took " << t;
  804. return 0;
  805. }
  806. std::this_thread::sleep_for(10ms);
  807. }
  808. LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
  809. return -1;
  810. }
  811. bool FsyncDirectory(const std::string& dirname) {
  812. android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
  813. if (fd == -1) {
  814. PLOG(ERROR) << "Failed to open " << dirname;
  815. return false;
  816. }
  817. if (fsync(fd) == -1) {
  818. if (errno == EROFS || errno == EINVAL) {
  819. PLOG(WARNING) << "Skip fsync " << dirname
  820. << " on a file system does not support synchronization";
  821. } else {
  822. PLOG(ERROR) << "Failed to fsync " << dirname;
  823. return false;
  824. }
  825. }
  826. return true;
  827. }
  828. bool writeStringToFile(const std::string& payload, const std::string& filename) {
  829. android::base::unique_fd fd(TEMP_FAILURE_RETRY(
  830. open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
  831. if (fd == -1) {
  832. PLOG(ERROR) << "Failed to open " << filename;
  833. return false;
  834. }
  835. if (!android::base::WriteStringToFd(payload, fd)) {
  836. PLOG(ERROR) << "Failed to write to " << filename;
  837. unlink(filename.c_str());
  838. return false;
  839. }
  840. // fsync as close won't guarantee flush data
  841. // see close(2), fsync(2) and b/68901441
  842. if (fsync(fd) == -1) {
  843. if (errno == EROFS || errno == EINVAL) {
  844. PLOG(WARNING) << "Skip fsync " << filename
  845. << " on a file system does not support synchronization";
  846. } else {
  847. PLOG(ERROR) << "Failed to fsync " << filename;
  848. unlink(filename.c_str());
  849. return false;
  850. }
  851. }
  852. return true;
  853. }
  854. } // namespace vold
  855. } // namespace android