• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
19 #include "Process.h"
20 #include "sehandle.h"
21 
22 #include <android-base/file.h>
23 #include <android-base/logging.h>
24 #include <android-base/properties.h>
25 #include <android-base/strings.h>
26 #include <android-base/stringprintf.h>
27 #include <cutils/fs.h>
28 #include <logwrap/logwrap.h>
29 #include <private/android_filesystem_config.h>
30 
31 #include <mutex>
32 #include <dirent.h>
33 #include <fcntl.h>
34 #include <linux/fs.h>
35 #include <stdlib.h>
36 #include <sys/mount.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <sys/sysmacros.h>
40 #include <sys/wait.h>
41 #include <sys/statvfs.h>
42 
43 #ifndef UMOUNT_NOFOLLOW
44 #define UMOUNT_NOFOLLOW    0x00000008  /* Don't follow symlink on umount */
45 #endif
46 
47 using android::base::ReadFileToString;
48 using android::base::StringPrintf;
49 
50 namespace android {
51 namespace vold {
52 
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 
58 bool sSleepOnUnmount = true;
59 
60 static const char* kBlkidPath = "/system/bin/blkid";
61 static const char* kKeyPath = "/data/misc/vold";
62 
63 static const char* kProcFilesystems = "/proc/filesystems";
64 
65 // Lock used to protect process-level SELinux changes from racing with each
66 // other between multiple threads.
67 static std::mutex kSecurityLock;
68 
CreateDeviceNode(const std::string & path,dev_t dev)69 status_t CreateDeviceNode(const std::string& path, dev_t dev) {
70     std::lock_guard<std::mutex> lock(kSecurityLock);
71     const char* cpath = path.c_str();
72     status_t res = 0;
73 
74     char* secontext = nullptr;
75     if (sehandle) {
76         if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
77             setfscreatecon(secontext);
78         }
79     }
80 
81     mode_t mode = 0660 | S_IFBLK;
82     if (mknod(cpath, mode, dev) < 0) {
83         if (errno != EEXIST) {
84             PLOG(ERROR) << "Failed to create device node for " << major(dev)
85                     << ":" << minor(dev) << " at " << path;
86             res = -errno;
87         }
88     }
89 
90     if (secontext) {
91         setfscreatecon(nullptr);
92         freecon(secontext);
93     }
94 
95     return res;
96 }
97 
DestroyDeviceNode(const std::string & path)98 status_t DestroyDeviceNode(const std::string& path) {
99     const char* cpath = path.c_str();
100     if (TEMP_FAILURE_RETRY(unlink(cpath))) {
101         return -errno;
102     } else {
103         return OK;
104     }
105 }
106 
PrepareDir(const std::string & path,mode_t mode,uid_t uid,gid_t gid)107 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
108     std::lock_guard<std::mutex> lock(kSecurityLock);
109     const char* cpath = path.c_str();
110 
111     char* secontext = nullptr;
112     if (sehandle) {
113         if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
114             setfscreatecon(secontext);
115         }
116     }
117 
118     int res = fs_prepare_dir(cpath, mode, uid, gid);
119 
120     if (secontext) {
121         setfscreatecon(nullptr);
122         freecon(secontext);
123     }
124 
125     if (res == 0) {
126         return OK;
127     } else {
128         return -errno;
129     }
130 }
131 
ForceUnmount(const std::string & path)132 status_t ForceUnmount(const std::string& path) {
133     const char* cpath = path.c_str();
134     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
135         return OK;
136     }
137     // Apps might still be handling eject request, so wait before
138     // we start sending signals
139     if (sSleepOnUnmount) sleep(5);
140 
141     KillProcessesWithOpenFiles(path, SIGINT);
142     if (sSleepOnUnmount) sleep(5);
143     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
144         return OK;
145     }
146 
147     KillProcessesWithOpenFiles(path, SIGTERM);
148     if (sSleepOnUnmount) sleep(5);
149     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
150         return OK;
151     }
152 
153     KillProcessesWithOpenFiles(path, SIGKILL);
154     if (sSleepOnUnmount) sleep(5);
155     if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
156         return OK;
157     }
158 
159     return -errno;
160 }
161 
KillProcessesUsingPath(const std::string & path)162 status_t KillProcessesUsingPath(const std::string& path) {
163     if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
164         return OK;
165     }
166     if (sSleepOnUnmount) sleep(5);
167 
168     if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
169         return OK;
170     }
171     if (sSleepOnUnmount) sleep(5);
172 
173     if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
174         return OK;
175     }
176     if (sSleepOnUnmount) sleep(5);
177 
178     // Send SIGKILL a second time to determine if we've
179     // actually killed everyone with open files
180     if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
181         return OK;
182     }
183     PLOG(ERROR) << "Failed to kill processes using " << path;
184     return -EBUSY;
185 }
186 
BindMount(const std::string & source,const std::string & target)187 status_t BindMount(const std::string& source, const std::string& target) {
188     if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
189         PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
190         return -errno;
191     }
192     return OK;
193 }
194 
FindValue(const std::string & raw,const std::string & key,std::string * value)195 bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
196     auto qual = key + "=\"";
197     auto start = raw.find(qual);
198     if (start > 0 && raw[start - 1] != ' ') {
199         start = raw.find(qual, start + 1);
200     }
201 
202     if (start == std::string::npos) return false;
203     start += qual.length();
204 
205     auto end = raw.find("\"", start);
206     if (end == std::string::npos) return false;
207 
208     *value = raw.substr(start, end - start);
209     return true;
210 }
211 
readMetadata(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel,bool untrusted)212 static status_t readMetadata(const std::string& path, std::string* fsType,
213         std::string* fsUuid, std::string* fsLabel, bool untrusted) {
214     fsType->clear();
215     fsUuid->clear();
216     fsLabel->clear();
217 
218     std::vector<std::string> cmd;
219     cmd.push_back(kBlkidPath);
220     cmd.push_back("-c");
221     cmd.push_back("/dev/null");
222     cmd.push_back("-s");
223     cmd.push_back("TYPE");
224     cmd.push_back("-s");
225     cmd.push_back("UUID");
226     cmd.push_back("-s");
227     cmd.push_back("LABEL");
228     cmd.push_back(path);
229 
230     std::vector<std::string> output;
231     status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
232     if (res != OK) {
233         LOG(WARNING) << "blkid failed to identify " << path;
234         return res;
235     }
236 
237     for (const auto& line : output) {
238         // Extract values from blkid output, if defined
239         FindValue(line, "TYPE", fsType);
240         FindValue(line, "UUID", fsUuid);
241         FindValue(line, "LABEL", fsLabel);
242     }
243 
244     return OK;
245 }
246 
ReadMetadata(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel)247 status_t ReadMetadata(const std::string& path, std::string* fsType,
248         std::string* fsUuid, std::string* fsLabel) {
249     return readMetadata(path, fsType, fsUuid, fsLabel, false);
250 }
251 
ReadMetadataUntrusted(const std::string & path,std::string * fsType,std::string * fsUuid,std::string * fsLabel)252 status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType,
253         std::string* fsUuid, std::string* fsLabel) {
254     return readMetadata(path, fsType, fsUuid, fsLabel, true);
255 }
256 
ForkExecvp(const std::vector<std::string> & args)257 status_t ForkExecvp(const std::vector<std::string>& args) {
258     return ForkExecvp(args, nullptr);
259 }
260 
ForkExecvp(const std::vector<std::string> & args,security_context_t context)261 status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
262     std::lock_guard<std::mutex> lock(kSecurityLock);
263     size_t argc = args.size();
264     char** argv = (char**) calloc(argc, sizeof(char*));
265     for (size_t i = 0; i < argc; i++) {
266         argv[i] = (char*) args[i].c_str();
267         if (i == 0) {
268             LOG(VERBOSE) << args[i];
269         } else {
270             LOG(VERBOSE) << "    " << args[i];
271         }
272     }
273 
274     if (context) {
275         if (setexeccon(context)) {
276             LOG(ERROR) << "Failed to setexeccon";
277             abort();
278         }
279     }
280     status_t res = android_fork_execvp(argc, argv, NULL, false, true);
281     if (context) {
282         if (setexeccon(nullptr)) {
283             LOG(ERROR) << "Failed to setexeccon";
284             abort();
285         }
286     }
287 
288     free(argv);
289     return res;
290 }
291 
ForkExecvp(const std::vector<std::string> & args,std::vector<std::string> & output)292 status_t ForkExecvp(const std::vector<std::string>& args,
293         std::vector<std::string>& output) {
294     return ForkExecvp(args, output, nullptr);
295 }
296 
ForkExecvp(const std::vector<std::string> & args,std::vector<std::string> & output,security_context_t context)297 status_t ForkExecvp(const std::vector<std::string>& args,
298         std::vector<std::string>& output, security_context_t context) {
299     std::lock_guard<std::mutex> lock(kSecurityLock);
300     std::string cmd;
301     for (size_t i = 0; i < args.size(); i++) {
302         cmd += args[i] + " ";
303         if (i == 0) {
304             LOG(VERBOSE) << args[i];
305         } else {
306             LOG(VERBOSE) << "    " << args[i];
307         }
308     }
309     output.clear();
310 
311     if (context) {
312         if (setexeccon(context)) {
313             LOG(ERROR) << "Failed to setexeccon";
314             abort();
315         }
316     }
317     FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
318     if (context) {
319         if (setexeccon(nullptr)) {
320             LOG(ERROR) << "Failed to setexeccon";
321             abort();
322         }
323     }
324 
325     if (!fp) {
326         PLOG(ERROR) << "Failed to popen " << cmd;
327         return -errno;
328     }
329     char line[1024];
330     while (fgets(line, sizeof(line), fp) != nullptr) {
331         LOG(VERBOSE) << line;
332         output.push_back(std::string(line));
333     }
334     if (pclose(fp) != 0) {
335         PLOG(ERROR) << "Failed to pclose " << cmd;
336         return -errno;
337     }
338 
339     return OK;
340 }
341 
ForkExecvpAsync(const std::vector<std::string> & args)342 pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
343     size_t argc = args.size();
344     char** argv = (char**) calloc(argc + 1, sizeof(char*));
345     for (size_t i = 0; i < argc; i++) {
346         argv[i] = (char*) args[i].c_str();
347         if (i == 0) {
348             LOG(VERBOSE) << args[i];
349         } else {
350             LOG(VERBOSE) << "    " << args[i];
351         }
352     }
353 
354     pid_t pid = fork();
355     if (pid == 0) {
356         close(STDIN_FILENO);
357         close(STDOUT_FILENO);
358         close(STDERR_FILENO);
359 
360         if (execvp(argv[0], argv)) {
361             PLOG(ERROR) << "Failed to exec";
362         }
363 
364         _exit(1);
365     }
366 
367     if (pid == -1) {
368         PLOG(ERROR) << "Failed to exec";
369     }
370 
371     free(argv);
372     return pid;
373 }
374 
ReadRandomBytes(size_t bytes,std::string & out)375 status_t ReadRandomBytes(size_t bytes, std::string& out) {
376     out.resize(bytes);
377     return ReadRandomBytes(bytes, &out[0]);
378 }
379 
ReadRandomBytes(size_t bytes,char * buf)380 status_t ReadRandomBytes(size_t bytes, char* buf) {
381     int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
382     if (fd == -1) {
383         return -errno;
384     }
385 
386     size_t n;
387     while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
388         bytes -= n;
389         buf += n;
390     }
391     close(fd);
392 
393     if (bytes == 0) {
394         return OK;
395     } else {
396         return -EIO;
397     }
398 }
399 
GenerateRandomUuid(std::string & out)400 status_t GenerateRandomUuid(std::string& out) {
401     status_t res = ReadRandomBytes(16, out);
402     if (res == OK) {
403         out[6] &= 0x0f;  /* clear version        */
404         out[6] |= 0x40;  /* set to version 4     */
405         out[8] &= 0x3f;  /* clear variant        */
406         out[8] |= 0x80;  /* set to IETF variant  */
407     }
408     return res;
409 }
410 
HexToStr(const std::string & hex,std::string & str)411 status_t HexToStr(const std::string& hex, std::string& str) {
412     str.clear();
413     bool even = true;
414     char cur = 0;
415     for (size_t i = 0; i < hex.size(); i++) {
416         int val = 0;
417         switch (hex[i]) {
418         case ' ': case '-': case ':': continue;
419         case 'f': case 'F': val = 15; break;
420         case 'e': case 'E': val = 14; break;
421         case 'd': case 'D': val = 13; break;
422         case 'c': case 'C': val = 12; break;
423         case 'b': case 'B': val = 11; break;
424         case 'a': case 'A': val = 10; break;
425         case '9': val = 9; break;
426         case '8': val = 8; break;
427         case '7': val = 7; break;
428         case '6': val = 6; break;
429         case '5': val = 5; break;
430         case '4': val = 4; break;
431         case '3': val = 3; break;
432         case '2': val = 2; break;
433         case '1': val = 1; break;
434         case '0': val = 0; break;
435         default: return -EINVAL;
436         }
437 
438         if (even) {
439             cur = val << 4;
440         } else {
441             cur += val;
442             str.push_back(cur);
443             cur = 0;
444         }
445         even = !even;
446     }
447     return even ? OK : -EINVAL;
448 }
449 
450 static const char* kLookup = "0123456789abcdef";
451 
StrToHex(const std::string & str,std::string & hex)452 status_t StrToHex(const std::string& str, std::string& hex) {
453     hex.clear();
454     for (size_t i = 0; i < str.size(); i++) {
455         hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
456         hex.push_back(kLookup[str[i] & 0x0F]);
457     }
458     return OK;
459 }
460 
StrToHex(const KeyBuffer & str,KeyBuffer & hex)461 status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
462     hex.clear();
463     for (size_t i = 0; i < str.size(); i++) {
464         hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
465         hex.push_back(kLookup[str.data()[i] & 0x0F]);
466     }
467     return OK;
468 }
469 
NormalizeHex(const std::string & in,std::string & out)470 status_t NormalizeHex(const std::string& in, std::string& out) {
471     std::string tmp;
472     if (HexToStr(in, tmp)) {
473         return -EINVAL;
474     }
475     return StrToHex(tmp, out);
476 }
477 
GetFreeBytes(const std::string & path)478 uint64_t GetFreeBytes(const std::string& path) {
479     struct statvfs sb;
480     if (statvfs(path.c_str(), &sb) == 0) {
481         return (uint64_t) sb.f_bavail * sb.f_frsize;
482     } else {
483         return -1;
484     }
485 }
486 
487 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
488 // eventually be migrated into system/
stat_size(struct stat * s)489 static int64_t stat_size(struct stat *s) {
490     int64_t blksize = s->st_blksize;
491     // count actual blocks used instead of nominal file size
492     int64_t size = s->st_blocks * 512;
493 
494     if (blksize) {
495         /* round up to filesystem block size */
496         size = (size + blksize - 1) & (~(blksize - 1));
497     }
498 
499     return size;
500 }
501 
502 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
503 // eventually be migrated into system/
calculate_dir_size(int dfd)504 int64_t calculate_dir_size(int dfd) {
505     int64_t size = 0;
506     struct stat s;
507     DIR *d;
508     struct dirent *de;
509 
510     d = fdopendir(dfd);
511     if (d == NULL) {
512         close(dfd);
513         return 0;
514     }
515 
516     while ((de = readdir(d))) {
517         const char *name = de->d_name;
518         if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
519             size += stat_size(&s);
520         }
521         if (de->d_type == DT_DIR) {
522             int subfd;
523 
524             /* always skip "." and ".." */
525             if (name[0] == '.') {
526                 if (name[1] == 0)
527                     continue;
528                 if ((name[1] == '.') && (name[2] == 0))
529                     continue;
530             }
531 
532             subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
533             if (subfd >= 0) {
534                 size += calculate_dir_size(subfd);
535             }
536         }
537     }
538     closedir(d);
539     return size;
540 }
541 
GetTreeBytes(const std::string & path)542 uint64_t GetTreeBytes(const std::string& path) {
543     int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
544     if (dirfd < 0) {
545         PLOG(WARNING) << "Failed to open " << path;
546         return -1;
547     } else {
548         uint64_t res = calculate_dir_size(dirfd);
549         close(dirfd);
550         return res;
551     }
552 }
553 
IsFilesystemSupported(const std::string & fsType)554 bool IsFilesystemSupported(const std::string& fsType) {
555     std::string supported;
556     if (!ReadFileToString(kProcFilesystems, &supported)) {
557         PLOG(ERROR) << "Failed to read supported filesystems";
558         return false;
559     }
560     return supported.find(fsType + "\n") != std::string::npos;
561 }
562 
WipeBlockDevice(const std::string & path)563 status_t WipeBlockDevice(const std::string& path) {
564     status_t res = -1;
565     const char* c_path = path.c_str();
566     unsigned long nr_sec = 0;
567     unsigned long long range[2];
568 
569     int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
570     if (fd == -1) {
571         PLOG(ERROR) << "Failed to open " << path;
572         goto done;
573     }
574 
575     if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
576         PLOG(ERROR) << "Failed to determine size of " << path;
577         goto done;
578     }
579 
580     range[0] = 0;
581     range[1] = (unsigned long long) nr_sec * 512;
582 
583     LOG(INFO) << "About to discard " << range[1] << " on " << path;
584     if (ioctl(fd, BLKDISCARD, &range) == 0) {
585         LOG(INFO) << "Discard success on " << path;
586         res = 0;
587     } else {
588         PLOG(ERROR) << "Discard failure on " << path;
589     }
590 
591 done:
592     close(fd);
593     return res;
594 }
595 
isValidFilename(const std::string & name)596 static bool isValidFilename(const std::string& name) {
597     if (name.empty() || (name == ".") || (name == "..")
598             || (name.find('/') != std::string::npos)) {
599         return false;
600     } else {
601         return true;
602     }
603 }
604 
BuildKeyPath(const std::string & partGuid)605 std::string BuildKeyPath(const std::string& partGuid) {
606     return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
607 }
608 
BuildDataSystemLegacyPath(userid_t userId)609 std::string BuildDataSystemLegacyPath(userid_t userId) {
610     return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
611 }
612 
BuildDataSystemCePath(userid_t userId)613 std::string BuildDataSystemCePath(userid_t userId) {
614     return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
615 }
616 
BuildDataSystemDePath(userid_t userId)617 std::string BuildDataSystemDePath(userid_t userId) {
618     return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
619 }
620 
BuildDataMiscLegacyPath(userid_t userId)621 std::string BuildDataMiscLegacyPath(userid_t userId) {
622     return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
623 }
624 
BuildDataMiscCePath(userid_t userId)625 std::string BuildDataMiscCePath(userid_t userId) {
626     return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
627 }
628 
BuildDataMiscDePath(userid_t userId)629 std::string BuildDataMiscDePath(userid_t userId) {
630     return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
631 }
632 
633 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
BuildDataProfilesDePath(userid_t userId)634 std::string BuildDataProfilesDePath(userid_t userId) {
635     return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
636 }
637 
BuildDataVendorCePath(userid_t userId)638 std::string BuildDataVendorCePath(userid_t userId) {
639     return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
640 }
641 
BuildDataVendorDePath(userid_t userId)642 std::string BuildDataVendorDePath(userid_t userId) {
643     return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
644 }
645 
BuildDataPath(const std::string & volumeUuid)646 std::string BuildDataPath(const std::string& volumeUuid) {
647     // TODO: unify with installd path generation logic
648     if (volumeUuid.empty()) {
649         return "/data";
650     } else {
651         CHECK(isValidFilename(volumeUuid));
652         return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
653     }
654 }
655 
BuildDataMediaCePath(const std::string & volumeUuid,userid_t userId)656 std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
657     // TODO: unify with installd path generation logic
658     std::string data(BuildDataPath(volumeUuid));
659     return StringPrintf("%s/media/%u", data.c_str(), userId);
660 }
661 
BuildDataUserCePath(const std::string & volumeUuid,userid_t userId)662 std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
663     // TODO: unify with installd path generation logic
664     std::string data(BuildDataPath(volumeUuid));
665     if (volumeUuid.empty() && userId == 0) {
666         std::string legacy = StringPrintf("%s/data", data.c_str());
667         struct stat sb;
668         if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
669             /* /data/data is dir, return /data/data for legacy system */
670             return legacy;
671         }
672     }
673     return StringPrintf("%s/user/%u", data.c_str(), userId);
674 }
675 
BuildDataUserDePath(const std::string & volumeUuid,userid_t userId)676 std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
677     // TODO: unify with installd path generation logic
678     std::string data(BuildDataPath(volumeUuid));
679     return StringPrintf("%s/user_de/%u", data.c_str(), userId);
680 }
681 
GetDevice(const std::string & path)682 dev_t GetDevice(const std::string& path) {
683     struct stat sb;
684     if (stat(path.c_str(), &sb)) {
685         PLOG(WARNING) << "Failed to stat " << path;
686         return 0;
687     } else {
688         return sb.st_dev;
689     }
690 }
691 
RestoreconRecursive(const std::string & path)692 status_t RestoreconRecursive(const std::string& path) {
693     LOG(VERBOSE) << "Starting restorecon of " << path;
694 
695     static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
696 
697     android::base::SetProperty(kRestoreconString, "");
698     android::base::SetProperty(kRestoreconString, path);
699 
700     android::base::WaitForProperty(kRestoreconString, path);
701 
702     LOG(VERBOSE) << "Finished restorecon of " << path;
703     return OK;
704 }
705 
Readlinkat(int dirfd,const std::string & path,std::string * result)706 bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
707     // Shamelessly borrowed from android::base::Readlink()
708     result->clear();
709 
710     // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
711     // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
712     // waste memory to just start there. We add 1 so that we can recognize
713     // whether it actually fit (rather than being truncated to 4095).
714     std::vector<char> buf(4095 + 1);
715     while (true) {
716         ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
717         // Unrecoverable error?
718         if (size == -1)
719             return false;
720         // It fit! (If size == buf.size(), it may have been truncated.)
721         if (static_cast<size_t>(size) < buf.size()) {
722             result->assign(&buf[0], size);
723             return true;
724         }
725         // Double our buffer and try again.
726         buf.resize(buf.size() * 2);
727     }
728 }
729 
IsRunningInEmulator()730 bool IsRunningInEmulator() {
731     return android::base::GetBoolProperty("ro.kernel.qemu", false);
732 }
733 
734 }  // namespace vold
735 }  // namespace android
736