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