blob: e06111a24cde0bfd00d139d946e50b971c244846 [file] [log] [blame]
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001/*
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
Jeff Sharkeydeb24052015-03-02 21:01:40 -080017#include "sehandle.h"
18#include "Utils.h"
19#include "Process.h"
20
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070021#include <base/file.h>
Jeff Sharkey36801cc2015-03-13 16:09:20 -070022#include <base/logging.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070023#include <base/stringprintf.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080024#include <cutils/fs.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080025#include <private/android_filesystem_config.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070026#include <logwrap/logwrap.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080027
Jeff Sharkeyce6a9132015-04-08 21:07:21 -070028#include <mutex>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070029#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080030#include <fcntl.h>
31#include <linux/fs.h>
32#include <stdlib.h>
33#include <sys/mount.h>
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/wait.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070037#include <sys/statvfs.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080038
39#ifndef UMOUNT_NOFOLLOW
40#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
41#endif
42
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070043using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070044using android::base::StringPrintf;
45
Jeff Sharkeydeb24052015-03-02 21:01:40 -080046namespace android {
47namespace vold {
48
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070049security_context_t sBlkidContext = nullptr;
50security_context_t sBlkidUntrustedContext = nullptr;
51security_context_t sFsckContext = nullptr;
52security_context_t sFsckUntrustedContext = nullptr;
53
Jeff Sharkey9c484982015-03-31 10:35:33 -070054static const char* kBlkidPath = "/system/bin/blkid";
55
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070056static const char* kProcFilesystems = "/proc/filesystems";
57
Jeff Sharkeydeb24052015-03-02 21:01:40 -080058status_t CreateDeviceNode(const std::string& path, dev_t dev) {
59 const char* cpath = path.c_str();
60 status_t res = 0;
61
62 char* secontext = nullptr;
63 if (sehandle) {
64 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
65 setfscreatecon(secontext);
66 }
67 }
68
69 mode_t mode = 0660 | S_IFBLK;
70 if (mknod(cpath, mode, dev) < 0) {
71 if (errno != EEXIST) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070072 PLOG(ERROR) << "Failed to create device node for " << major(dev)
73 << ":" << minor(dev) << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080074 res = -errno;
75 }
76 }
77
78 if (secontext) {
79 setfscreatecon(nullptr);
80 freecon(secontext);
81 }
82
83 return res;
84}
85
86status_t DestroyDeviceNode(const std::string& path) {
87 const char* cpath = path.c_str();
88 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
89 return -errno;
90 } else {
91 return OK;
92 }
93}
94
Jeff Sharkeyf0121c52015-04-06 14:08:45 -070095status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
96 const char* cpath = path.c_str();
97
98 char* secontext = nullptr;
99 if (sehandle) {
100 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
101 setfscreatecon(secontext);
102 }
103 }
104
105 int res = fs_prepare_dir(cpath, mode, uid, gid);
106
107 if (secontext) {
108 setfscreatecon(nullptr);
109 freecon(secontext);
110 }
111
112 if (res == 0) {
113 return OK;
114 } else {
115 return -errno;
116 }
117}
118
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800119status_t ForceUnmount(const std::string& path) {
120 const char* cpath = path.c_str();
121 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
122 return OK;
123 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700124 PLOG(WARNING) << "Failed to unmount " << path;
125
126 sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700127 Process::killProcessesWithOpenFiles(cpath, SIGINT);
128
129 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
130 return OK;
131 }
132 PLOG(WARNING) << "Failed to unmount " << path;
133
134 sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800135 Process::killProcessesWithOpenFiles(cpath, SIGTERM);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800136
137 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
138 return OK;
139 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700140 PLOG(WARNING) << "Failed to unmount " << path;
141
142 sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800143 Process::killProcessesWithOpenFiles(cpath, SIGKILL);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800144
145 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
146 return OK;
147 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700148 PLOG(ERROR) << "Failed to unmount " << path;
149
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800150 return -errno;
151}
152
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700153status_t BindMount(const std::string& source, const std::string& target) {
154 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
155 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
156 return -errno;
157 }
158 return OK;
159}
160
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700161static status_t readMetadata(const std::string& path, std::string& fsType,
162 std::string& fsUuid, std::string& fsLabel, bool untrusted) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700163 fsType.clear();
164 fsUuid.clear();
165 fsLabel.clear();
166
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700167 std::vector<std::string> cmd;
168 cmd.push_back(kBlkidPath);
169 cmd.push_back("-c");
170 cmd.push_back("/dev/null");
171 cmd.push_back(path);
172
173 std::vector<std::string> output;
174 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
175 if (res != OK) {
176 LOG(WARNING) << "blkid failed to identify " << path;
177 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700178 }
179
Jeff Sharkey9c484982015-03-31 10:35:33 -0700180 char value[128];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700181 for (auto line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700182 // Extract values from blkid output, if defined
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700183 const char* cline = line.c_str();
184 char* start = strstr(cline, "TYPE=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700185 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
186 fsType = value;
187 }
188
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700189 start = strstr(cline, "UUID=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700190 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
191 fsUuid = value;
192 }
193
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700194 start = strstr(cline, "LABEL=");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700195 if (start != nullptr && sscanf(start + 6, "\"%127[^\"]\"", value) == 1) {
196 fsLabel = value;
197 }
Jeff Sharkey9c484982015-03-31 10:35:33 -0700198 }
199
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700200 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700201}
202
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700203status_t ReadMetadata(const std::string& path, std::string& fsType,
204 std::string& fsUuid, std::string& fsLabel) {
205 return readMetadata(path, fsType, fsUuid, fsLabel, false);
206}
207
208status_t ReadMetadataUntrusted(const std::string& path, std::string& fsType,
209 std::string& fsUuid, std::string& fsLabel) {
210 return readMetadata(path, fsType, fsUuid, fsLabel, true);
211}
212
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700213status_t ForkExecvp(const std::vector<std::string>& args) {
214 return ForkExecvp(args, nullptr);
215}
216
217status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
218 size_t argc = args.size();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700219 char** argv = (char**) calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700220 for (size_t i = 0; i < argc; i++) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700221 argv[i] = (char*) args[i].c_str();
222 if (i == 0) {
223 LOG(VERBOSE) << args[i];
224 } else {
225 LOG(VERBOSE) << " " << args[i];
226 }
227 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700228
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700229 if (setexeccon(context)) {
230 LOG(ERROR) << "Failed to setexeccon";
231 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700232 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700233 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
234 if (setexeccon(nullptr)) {
235 LOG(ERROR) << "Failed to setexeccon";
236 abort();
237 }
238
Jeff Sharkey9c484982015-03-31 10:35:33 -0700239 free(argv);
240 return res;
241}
242
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700243status_t ForkExecvp(const std::vector<std::string>& args,
244 std::vector<std::string>& output) {
245 return ForkExecvp(args, output, nullptr);
246}
247
248status_t ForkExecvp(const std::vector<std::string>& args,
249 std::vector<std::string>& output, security_context_t context) {
250 std::string cmd;
251 for (size_t i = 0; i < args.size(); i++) {
252 cmd += args[i] + " ";
253 if (i == 0) {
254 LOG(VERBOSE) << args[i];
255 } else {
256 LOG(VERBOSE) << " " << args[i];
257 }
258 }
259 output.clear();
260
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700261 if (setexeccon(context)) {
262 LOG(ERROR) << "Failed to setexeccon";
263 abort();
264 }
265 FILE* fp = popen(cmd.c_str(), "r");
266 if (setexeccon(nullptr)) {
267 LOG(ERROR) << "Failed to setexeccon";
268 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700269 }
270
271 if (!fp) {
272 PLOG(ERROR) << "Failed to popen " << cmd;
273 return -errno;
274 }
275 char line[1024];
276 while (fgets(line, sizeof(line), fp) != nullptr) {
277 LOG(VERBOSE) << line;
278 output.push_back(std::string(line));
279 }
280 if (pclose(fp) != 0) {
281 PLOG(ERROR) << "Failed to pclose " << cmd;
282 return -errno;
283 }
284
285 return OK;
286}
287
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700288pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
289 size_t argc = args.size();
290 char** argv = (char**) calloc(argc + 1, sizeof(char*));
291 for (size_t i = 0; i < argc; i++) {
292 argv[i] = (char*) args[i].c_str();
293 if (i == 0) {
294 LOG(VERBOSE) << args[i];
295 } else {
296 LOG(VERBOSE) << " " << args[i];
297 }
298 }
299
300 pid_t pid = fork();
301 if (pid == 0) {
302 close(STDIN_FILENO);
303 close(STDOUT_FILENO);
304 close(STDERR_FILENO);
305
306 if (execvp(argv[0], argv)) {
307 PLOG(ERROR) << "Failed to exec";
308 }
309
310 _exit(1);
311 }
312
313 if (pid == -1) {
314 PLOG(ERROR) << "Failed to exec";
315 }
316
317 free(argv);
318 return pid;
319}
320
Jeff Sharkey9c484982015-03-31 10:35:33 -0700321status_t ReadRandomBytes(size_t bytes, std::string& out) {
322 out.clear();
323
324 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
325 if (fd == -1) {
326 return -errno;
327 }
328
329 char buf[BUFSIZ];
330 size_t n;
331 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], std::min(sizeof(buf), bytes)))) > 0) {
332 out.append(buf, n);
333 bytes -= n;
334 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700335 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700336
337 if (bytes == 0) {
338 return OK;
339 } else {
340 return -EIO;
341 }
342}
343
344status_t HexToStr(const std::string& hex, std::string& str) {
345 str.clear();
346 bool even = true;
347 char cur = 0;
348 for (size_t i = 0; i < hex.size(); i++) {
349 int val = 0;
350 switch (hex[i]) {
351 case ' ': case '-': case ':': continue;
352 case 'f': case 'F': val = 15; break;
353 case 'e': case 'E': val = 14; break;
354 case 'd': case 'D': val = 13; break;
355 case 'c': case 'C': val = 12; break;
356 case 'b': case 'B': val = 11; break;
357 case 'a': case 'A': val = 10; break;
358 case '9': val = 9; break;
359 case '8': val = 8; break;
360 case '7': val = 7; break;
361 case '6': val = 6; break;
362 case '5': val = 5; break;
363 case '4': val = 4; break;
364 case '3': val = 3; break;
365 case '2': val = 2; break;
366 case '1': val = 1; break;
367 case '0': val = 0; break;
368 default: return -EINVAL;
369 }
370
371 if (even) {
372 cur = val << 4;
373 } else {
374 cur += val;
375 str.push_back(cur);
376 cur = 0;
377 }
378 even = !even;
379 }
380 return even ? OK : -EINVAL;
381}
382
383static const char* kLookup = "0123456789abcdef";
384
385status_t StrToHex(const std::string& str, std::string& hex) {
386 hex.clear();
387 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700388 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700389 hex.push_back(kLookup[str[i] & 0x0F]);
390 }
391 return OK;
392}
393
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700394uint64_t GetFreeBytes(const std::string& path) {
395 struct statvfs sb;
396 if (statvfs(path.c_str(), &sb) == 0) {
397 return sb.f_bfree * sb.f_bsize;
398 } else {
399 return -1;
400 }
401}
402
403// TODO: borrowed from frameworks/native/libs/diskusage/ which should
404// eventually be migrated into system/
405static int64_t stat_size(struct stat *s) {
406 int64_t blksize = s->st_blksize;
407 // count actual blocks used instead of nominal file size
408 int64_t size = s->st_blocks * 512;
409
410 if (blksize) {
411 /* round up to filesystem block size */
412 size = (size + blksize - 1) & (~(blksize - 1));
413 }
414
415 return size;
416}
417
418// TODO: borrowed from frameworks/native/libs/diskusage/ which should
419// eventually be migrated into system/
420int64_t calculate_dir_size(int dfd) {
421 int64_t size = 0;
422 struct stat s;
423 DIR *d;
424 struct dirent *de;
425
426 d = fdopendir(dfd);
427 if (d == NULL) {
428 close(dfd);
429 return 0;
430 }
431
432 while ((de = readdir(d))) {
433 const char *name = de->d_name;
434 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
435 size += stat_size(&s);
436 }
437 if (de->d_type == DT_DIR) {
438 int subfd;
439
440 /* always skip "." and ".." */
441 if (name[0] == '.') {
442 if (name[1] == 0)
443 continue;
444 if ((name[1] == '.') && (name[2] == 0))
445 continue;
446 }
447
448 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
449 if (subfd >= 0) {
450 size += calculate_dir_size(subfd);
451 }
452 }
453 }
454 closedir(d);
455 return size;
456}
457
458uint64_t GetTreeBytes(const std::string& path) {
459 int dirfd = open(path.c_str(), O_DIRECTORY, O_RDONLY);
460 if (dirfd < 0) {
461 PLOG(WARNING) << "Failed to open " << path;
462 return -1;
463 } else {
464 uint64_t res = calculate_dir_size(dirfd);
465 close(dirfd);
466 return res;
467 }
468}
469
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700470bool IsFilesystemSupported(const std::string& fsType) {
471 std::string supported;
472 if (!ReadFileToString(kProcFilesystems, &supported)) {
473 PLOG(ERROR) << "Failed to read supported filesystems";
474 return false;
475 }
476 return supported.find(fsType + "\n") != std::string::npos;
477}
478
479status_t WipeBlockDevice(const std::string& path) {
480 status_t res = -1;
481 const char* c_path = path.c_str();
482 unsigned long nr_sec = 0;
483 unsigned long long range[2];
484
485 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
486 if (fd == -1) {
487 PLOG(ERROR) << "Failed to open " << path;
488 goto done;
489 }
490
491 if ((ioctl(fd, BLKGETSIZE, nr_sec)) == -1) {
492 PLOG(ERROR) << "Failed to determine size of " << path;
493 goto done;
494 }
495
496 range[0] = 0;
497 range[1] = (unsigned long long) nr_sec * 512;
498
499 LOG(INFO) << "About to discard " << range[1] << " on " << path;
500 if (ioctl(fd, BLKDISCARD, &range) == 0) {
501 LOG(INFO) << "Discard success on " << path;
502 res = 0;
503 } else {
504 PLOG(ERROR) << "Discard failure on " << path;
505 }
506
507done:
508 close(fd);
509 return res;
510}
511
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800512} // namespace vold
513} // namespace android