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