OSDN Git Service

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