blob: 9c1919075b55390db9036aca85cac667b0da33f7 [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"
Keun-young Park375ac252017-08-02 17:45:48 -070020#include "VolumeManager.h"
Jeff Sharkeydeb24052015-03-02 21:01:40 -080021
Elliott Hughes7e128fb2015-12-04 15:50:53 -080022#include <android-base/file.h>
23#include <android-base/logging.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070024#include <android-base/properties.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060025#include <android-base/strings.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080026#include <android-base/stringprintf.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080027#include <cutils/fs.h>
Jeff Sharkey9c484982015-03-31 10:35:33 -070028#include <logwrap/logwrap.h>
Tom Cherryd6127ef2017-06-15 17:13:56 -070029#include <private/android_filesystem_config.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080030
Jeff Sharkeyce6a9132015-04-08 21:07:21 -070031#include <mutex>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070032#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080033#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>
Elliott Hughes0e08e842017-05-18 09:08:24 -070039#include <sys/sysmacros.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080040#include <sys/wait.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070041#include <sys/statvfs.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080042
43#ifndef UMOUNT_NOFOLLOW
44#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
45#endif
46
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070047using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070048using android::base::StringPrintf;
49
Jeff Sharkeydeb24052015-03-02 21:01:40 -080050namespace android {
51namespace vold {
52
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070053security_context_t sBlkidContext = nullptr;
54security_context_t sBlkidUntrustedContext = nullptr;
55security_context_t sFsckContext = nullptr;
56security_context_t sFsckUntrustedContext = nullptr;
57
Jeff Sharkey9c484982015-03-31 10:35:33 -070058static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070059static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070060
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070061static const char* kProcFilesystems = "/proc/filesystems";
62
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060063// Lock used to protect process-level SELinux changes from racing with each
64// other between multiple threads.
65static std::mutex kSecurityLock;
66
Jeff Sharkeydeb24052015-03-02 21:01:40 -080067status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060068 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080069 const char* cpath = path.c_str();
70 status_t res = 0;
71
72 char* secontext = nullptr;
73 if (sehandle) {
74 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
75 setfscreatecon(secontext);
76 }
77 }
78
79 mode_t mode = 0660 | S_IFBLK;
80 if (mknod(cpath, mode, dev) < 0) {
81 if (errno != EEXIST) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070082 PLOG(ERROR) << "Failed to create device node for " << major(dev)
83 << ":" << minor(dev) << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080084 res = -errno;
85 }
86 }
87
88 if (secontext) {
89 setfscreatecon(nullptr);
90 freecon(secontext);
91 }
92
93 return res;
94}
95
96status_t DestroyDeviceNode(const std::string& path) {
97 const char* cpath = path.c_str();
98 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
99 return -errno;
100 } else {
101 return OK;
102 }
103}
104
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700105status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600106 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700107 const char* cpath = path.c_str();
108
109 char* secontext = nullptr;
110 if (sehandle) {
111 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
112 setfscreatecon(secontext);
113 }
114 }
115
116 int res = fs_prepare_dir(cpath, mode, uid, gid);
117
118 if (secontext) {
119 setfscreatecon(nullptr);
120 freecon(secontext);
121 }
122
123 if (res == 0) {
124 return OK;
125 } else {
126 return -errno;
127 }
128}
129
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800130status_t ForceUnmount(const std::string& path) {
131 const char* cpath = path.c_str();
132 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
133 return OK;
134 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700135 // Apps might still be handling eject request, so wait before
136 // we start sending signals
Keun-young Park375ac252017-08-02 17:45:48 -0700137 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700138
Jeff Sharkey3472e522017-10-06 18:02:53 -0600139 KillProcessesWithOpenFiles(path, SIGINT);
Keun-young Park375ac252017-08-02 17:45:48 -0700140 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700141 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
142 return OK;
143 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700144
Jeff Sharkey3472e522017-10-06 18:02:53 -0600145 KillProcessesWithOpenFiles(path, SIGTERM);
Keun-young Park375ac252017-08-02 17:45:48 -0700146 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800147 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
148 return OK;
149 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700150
Jeff Sharkey3472e522017-10-06 18:02:53 -0600151 KillProcessesWithOpenFiles(path, SIGKILL);
Keun-young Park375ac252017-08-02 17:45:48 -0700152 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700153 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
154 return OK;
155 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700156
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800157 return -errno;
158}
159
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700160status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600161 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700162 return OK;
163 }
Keun-young Park375ac252017-08-02 17:45:48 -0700164 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700165
Jeff Sharkey3472e522017-10-06 18:02:53 -0600166 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700167 return OK;
168 }
Keun-young Park375ac252017-08-02 17:45:48 -0700169 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700170
Jeff Sharkey3472e522017-10-06 18:02:53 -0600171 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700172 return OK;
173 }
Keun-young Park375ac252017-08-02 17:45:48 -0700174 if (!VolumeManager::shutting_down) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700175
176 // Send SIGKILL a second time to determine if we've
177 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600178 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700179 return OK;
180 }
181 PLOG(ERROR) << "Failed to kill processes using " << path;
182 return -EBUSY;
183}
184
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700185status_t BindMount(const std::string& source, const std::string& target) {
186 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
187 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
188 return -errno;
189 }
190 return OK;
191}
192
Jeff Sharkey3472e522017-10-06 18:02:53 -0600193bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
194 auto qual = key + "=\"";
195 auto start = raw.find(qual);
196 if (start > 0 && raw[start - 1] != ' ') {
197 start = raw.find(qual, start + 1);
198 }
199
200 if (start == std::string::npos) return false;
201 start += qual.length();
202
203 auto end = raw.find("\"", start);
204 if (end == std::string::npos) return false;
205
206 *value = raw.substr(start, end - start);
207 return true;
208}
209
210static status_t readMetadata(const std::string& path, std::string* fsType,
211 std::string* fsUuid, std::string* fsLabel, bool untrusted) {
212 fsType->clear();
213 fsUuid->clear();
214 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700215
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700216 std::vector<std::string> cmd;
217 cmd.push_back(kBlkidPath);
218 cmd.push_back("-c");
219 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700220 cmd.push_back("-s");
221 cmd.push_back("TYPE");
222 cmd.push_back("-s");
223 cmd.push_back("UUID");
224 cmd.push_back("-s");
225 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700226 cmd.push_back(path);
227
228 std::vector<std::string> output;
229 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
230 if (res != OK) {
231 LOG(WARNING) << "blkid failed to identify " << path;
232 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700233 }
234
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700235 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700236 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600237 FindValue(line, "TYPE", fsType);
238 FindValue(line, "UUID", fsUuid);
239 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700240 }
241
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700242 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700243}
244
Jeff Sharkey3472e522017-10-06 18:02:53 -0600245status_t ReadMetadata(const std::string& path, std::string* fsType,
246 std::string* fsUuid, std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700247 return readMetadata(path, fsType, fsUuid, fsLabel, false);
248}
249
Jeff Sharkey3472e522017-10-06 18:02:53 -0600250status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType,
251 std::string* fsUuid, std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700252 return readMetadata(path, fsType, fsUuid, fsLabel, true);
253}
254
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700255status_t ForkExecvp(const std::vector<std::string>& args) {
256 return ForkExecvp(args, nullptr);
257}
258
259status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600260 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700261 size_t argc = args.size();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700262 char** argv = (char**) calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700263 for (size_t i = 0; i < argc; i++) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700264 argv[i] = (char*) args[i].c_str();
265 if (i == 0) {
266 LOG(VERBOSE) << args[i];
267 } else {
268 LOG(VERBOSE) << " " << args[i];
269 }
270 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700271
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700272 if (setexeccon(context)) {
273 LOG(ERROR) << "Failed to setexeccon";
274 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700275 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700276 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
277 if (setexeccon(nullptr)) {
278 LOG(ERROR) << "Failed to setexeccon";
279 abort();
280 }
281
Jeff Sharkey9c484982015-03-31 10:35:33 -0700282 free(argv);
283 return res;
284}
285
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700286status_t ForkExecvp(const std::vector<std::string>& args,
287 std::vector<std::string>& output) {
288 return ForkExecvp(args, output, nullptr);
289}
290
291status_t ForkExecvp(const std::vector<std::string>& args,
292 std::vector<std::string>& output, security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600293 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700294 std::string cmd;
295 for (size_t i = 0; i < args.size(); i++) {
296 cmd += args[i] + " ";
297 if (i == 0) {
298 LOG(VERBOSE) << args[i];
299 } else {
300 LOG(VERBOSE) << " " << args[i];
301 }
302 }
303 output.clear();
304
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700305 if (setexeccon(context)) {
306 LOG(ERROR) << "Failed to setexeccon";
307 abort();
308 }
Jeff Sharkey32ebb732017-03-27 16:18:50 -0600309 FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700310 if (setexeccon(nullptr)) {
311 LOG(ERROR) << "Failed to setexeccon";
312 abort();
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700313 }
314
315 if (!fp) {
316 PLOG(ERROR) << "Failed to popen " << cmd;
317 return -errno;
318 }
319 char line[1024];
320 while (fgets(line, sizeof(line), fp) != nullptr) {
321 LOG(VERBOSE) << line;
322 output.push_back(std::string(line));
323 }
324 if (pclose(fp) != 0) {
325 PLOG(ERROR) << "Failed to pclose " << cmd;
326 return -errno;
327 }
328
329 return OK;
330}
331
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700332pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
333 size_t argc = args.size();
334 char** argv = (char**) calloc(argc + 1, sizeof(char*));
335 for (size_t i = 0; i < argc; i++) {
336 argv[i] = (char*) args[i].c_str();
337 if (i == 0) {
338 LOG(VERBOSE) << args[i];
339 } else {
340 LOG(VERBOSE) << " " << args[i];
341 }
342 }
343
344 pid_t pid = fork();
345 if (pid == 0) {
346 close(STDIN_FILENO);
347 close(STDOUT_FILENO);
348 close(STDERR_FILENO);
349
350 if (execvp(argv[0], argv)) {
351 PLOG(ERROR) << "Failed to exec";
352 }
353
354 _exit(1);
355 }
356
357 if (pid == -1) {
358 PLOG(ERROR) << "Failed to exec";
359 }
360
361 free(argv);
362 return pid;
363}
364
Jeff Sharkey9c484982015-03-31 10:35:33 -0700365status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100366 out.resize(bytes);
367 return ReadRandomBytes(bytes, &out[0]);
368}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700369
Pavel Grafove2e2d302017-08-01 17:15:53 +0100370status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700371 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
372 if (fd == -1) {
373 return -errno;
374 }
375
Jeff Sharkey9c484982015-03-31 10:35:33 -0700376 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100377 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700378 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100379 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700380 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700381 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700382
383 if (bytes == 0) {
384 return OK;
385 } else {
386 return -EIO;
387 }
388}
389
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600390status_t GenerateRandomUuid(std::string& out) {
391 status_t res = ReadRandomBytes(16, out);
392 if (res == OK) {
393 out[6] &= 0x0f; /* clear version */
394 out[6] |= 0x40; /* set to version 4 */
395 out[8] &= 0x3f; /* clear variant */
396 out[8] |= 0x80; /* set to IETF variant */
397 }
398 return res;
399}
400
Jeff Sharkey9c484982015-03-31 10:35:33 -0700401status_t HexToStr(const std::string& hex, std::string& str) {
402 str.clear();
403 bool even = true;
404 char cur = 0;
405 for (size_t i = 0; i < hex.size(); i++) {
406 int val = 0;
407 switch (hex[i]) {
408 case ' ': case '-': case ':': continue;
409 case 'f': case 'F': val = 15; break;
410 case 'e': case 'E': val = 14; break;
411 case 'd': case 'D': val = 13; break;
412 case 'c': case 'C': val = 12; break;
413 case 'b': case 'B': val = 11; break;
414 case 'a': case 'A': val = 10; break;
415 case '9': val = 9; break;
416 case '8': val = 8; break;
417 case '7': val = 7; break;
418 case '6': val = 6; break;
419 case '5': val = 5; break;
420 case '4': val = 4; break;
421 case '3': val = 3; break;
422 case '2': val = 2; break;
423 case '1': val = 1; break;
424 case '0': val = 0; break;
425 default: return -EINVAL;
426 }
427
428 if (even) {
429 cur = val << 4;
430 } else {
431 cur += val;
432 str.push_back(cur);
433 cur = 0;
434 }
435 even = !even;
436 }
437 return even ? OK : -EINVAL;
438}
439
440static const char* kLookup = "0123456789abcdef";
441
442status_t StrToHex(const std::string& str, std::string& hex) {
443 hex.clear();
444 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700445 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700446 hex.push_back(kLookup[str[i] & 0x0F]);
447 }
448 return OK;
449}
450
Pavel Grafove2e2d302017-08-01 17:15:53 +0100451status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
452 hex.clear();
453 for (size_t i = 0; i < str.size(); i++) {
454 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
455 hex.push_back(kLookup[str.data()[i] & 0x0F]);
456 }
457 return OK;
458}
459
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700460status_t NormalizeHex(const std::string& in, std::string& out) {
461 std::string tmp;
462 if (HexToStr(in, tmp)) {
463 return -EINVAL;
464 }
465 return StrToHex(tmp, out);
466}
467
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700468uint64_t GetFreeBytes(const std::string& path) {
469 struct statvfs sb;
470 if (statvfs(path.c_str(), &sb) == 0) {
Jeff Sharkeya0220a52017-04-03 17:11:45 -0600471 return (uint64_t) sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700472 } else {
473 return -1;
474 }
475}
476
477// TODO: borrowed from frameworks/native/libs/diskusage/ which should
478// eventually be migrated into system/
479static int64_t stat_size(struct stat *s) {
480 int64_t blksize = s->st_blksize;
481 // count actual blocks used instead of nominal file size
482 int64_t size = s->st_blocks * 512;
483
484 if (blksize) {
485 /* round up to filesystem block size */
486 size = (size + blksize - 1) & (~(blksize - 1));
487 }
488
489 return size;
490}
491
492// TODO: borrowed from frameworks/native/libs/diskusage/ which should
493// eventually be migrated into system/
494int64_t calculate_dir_size(int dfd) {
495 int64_t size = 0;
496 struct stat s;
497 DIR *d;
498 struct dirent *de;
499
500 d = fdopendir(dfd);
501 if (d == NULL) {
502 close(dfd);
503 return 0;
504 }
505
506 while ((de = readdir(d))) {
507 const char *name = de->d_name;
508 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
509 size += stat_size(&s);
510 }
511 if (de->d_type == DT_DIR) {
512 int subfd;
513
514 /* always skip "." and ".." */
515 if (name[0] == '.') {
516 if (name[1] == 0)
517 continue;
518 if ((name[1] == '.') && (name[2] == 0))
519 continue;
520 }
521
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600522 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700523 if (subfd >= 0) {
524 size += calculate_dir_size(subfd);
525 }
526 }
527 }
528 closedir(d);
529 return size;
530}
531
532uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600533 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700534 if (dirfd < 0) {
535 PLOG(WARNING) << "Failed to open " << path;
536 return -1;
537 } else {
538 uint64_t res = calculate_dir_size(dirfd);
539 close(dirfd);
540 return res;
541 }
542}
543
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700544bool IsFilesystemSupported(const std::string& fsType) {
545 std::string supported;
546 if (!ReadFileToString(kProcFilesystems, &supported)) {
547 PLOG(ERROR) << "Failed to read supported filesystems";
548 return false;
549 }
550 return supported.find(fsType + "\n") != std::string::npos;
551}
552
553status_t WipeBlockDevice(const std::string& path) {
554 status_t res = -1;
555 const char* c_path = path.c_str();
556 unsigned long nr_sec = 0;
557 unsigned long long range[2];
558
559 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
560 if (fd == -1) {
561 PLOG(ERROR) << "Failed to open " << path;
562 goto done;
563 }
564
caozhiyuan9102b0b2015-10-29 16:39:00 +0800565 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700566 PLOG(ERROR) << "Failed to determine size of " << path;
567 goto done;
568 }
569
570 range[0] = 0;
571 range[1] = (unsigned long long) nr_sec * 512;
572
573 LOG(INFO) << "About to discard " << range[1] << " on " << path;
574 if (ioctl(fd, BLKDISCARD, &range) == 0) {
575 LOG(INFO) << "Discard success on " << path;
576 res = 0;
577 } else {
578 PLOG(ERROR) << "Discard failure on " << path;
579 }
580
581done:
582 close(fd);
583 return res;
584}
585
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800586static bool isValidFilename(const std::string& name) {
587 if (name.empty() || (name == ".") || (name == "..")
588 || (name.find('/') != std::string::npos)) {
589 return false;
590 } else {
591 return true;
592 }
593}
594
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700595std::string BuildKeyPath(const std::string& partGuid) {
596 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
597}
598
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600599std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700600 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600601}
602
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800603std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700604 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700605}
606
607std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700608 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700609}
610
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600611std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700612 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600613}
614
Jeff Sharkey47695b22016-02-01 17:02:29 -0700615std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700616 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700617}
618
619std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700620 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800621}
622
Calin Juravle79f55a42016-02-17 20:14:46 +0000623// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
624std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700625 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000626}
627
Paul Crowley3b71fc52017-10-09 10:55:21 -0700628std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800629 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700630 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800631 return "/data";
632 } else {
633 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700634 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800635 }
636}
637
Paul Crowley3b71fc52017-10-09 10:55:21 -0700638std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700639 // TODO: unify with installd path generation logic
640 std::string data(BuildDataPath(volumeUuid));
641 return StringPrintf("%s/media/%u", data.c_str(), userId);
642}
643
Paul Crowley3b71fc52017-10-09 10:55:21 -0700644std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800645 // TODO: unify with installd path generation logic
646 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700647 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800648 std::string legacy = StringPrintf("%s/data", data.c_str());
649 struct stat sb;
650 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
651 /* /data/data is dir, return /data/data for legacy system */
652 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800653 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800654 }
cjbaoeb501142017-04-12 00:09:00 +0800655 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800656}
657
Paul Crowley3b71fc52017-10-09 10:55:21 -0700658std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800659 // TODO: unify with installd path generation logic
660 std::string data(BuildDataPath(volumeUuid));
661 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
662}
663
Jeff Sharkey66270a22015-06-24 11:49:24 -0700664dev_t GetDevice(const std::string& path) {
665 struct stat sb;
666 if (stat(path.c_str(), &sb)) {
667 PLOG(WARNING) << "Failed to stat " << path;
668 return 0;
669 } else {
670 return sb.st_dev;
671 }
672}
673
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600674status_t RestoreconRecursive(const std::string& path) {
675 LOG(VERBOSE) << "Starting restorecon of " << path;
676
Tom Cherryd6127ef2017-06-15 17:13:56 -0700677 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600678
Tom Cherryd6127ef2017-06-15 17:13:56 -0700679 android::base::SetProperty(kRestoreconString, "");
680 android::base::SetProperty(kRestoreconString, path);
681
682 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600683
684 LOG(VERBOSE) << "Finished restorecon of " << path;
685 return OK;
686}
687
Jeff Sharkey3472e522017-10-06 18:02:53 -0600688bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
689 // Shamelessly borrowed from android::base::Readlink()
690 result->clear();
691
692 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
693 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
694 // waste memory to just start there. We add 1 so that we can recognize
695 // whether it actually fit (rather than being truncated to 4095).
696 std::vector<char> buf(4095 + 1);
697 while (true) {
698 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
699 // Unrecoverable error?
700 if (size == -1)
701 return false;
702 // It fit! (If size == buf.size(), it may have been truncated.)
703 if (static_cast<size_t>(size) < buf.size()) {
704 result->assign(&buf[0], size);
705 return true;
706 }
707 // Double our buffer and try again.
708 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900709 }
710}
711
Yu Ning942d4e82016-01-08 17:36:47 +0800712bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700713 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800714}
715
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800716} // namespace vold
717} // namespace android