blob: cdca85e7ef5be85738e0363462e0508b84e47ec9 [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 "Utils.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070018
Jeff Sharkeydeb24052015-03-02 21:01:40 -080019#include "Process.h"
Paul Crowley56292ef2017-10-20 08:07:53 -070020#include "sehandle.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>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080025#include <android-base/stringprintf.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070026#include <android-base/strings.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 Sharkey1d6fbcc2015-04-24 16:00:03 -070031#include <dirent.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080032#include <fcntl.h>
33#include <linux/fs.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070034#include <mntent.h>
35#include <stdio.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080036#include <stdlib.h>
37#include <sys/mount.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080038#include <sys/stat.h>
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -070039#include <sys/statvfs.h>
Paul Crowley14c8c072018-09-18 13:30:21 -070040#include <sys/sysmacros.h>
41#include <sys/types.h>
42#include <sys/wait.h>
Sudheer Shanka89ddf992018-09-25 14:22:07 -070043#include <list>
Paul Crowley14c8c072018-09-18 13:30:21 -070044#include <mutex>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080045
46#ifndef UMOUNT_NOFOLLOW
Paul Crowley14c8c072018-09-18 13:30:21 -070047#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
Jeff Sharkeydeb24052015-03-02 21:01:40 -080048#endif
49
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070050using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070051using android::base::StringPrintf;
52
Jeff Sharkeydeb24052015-03-02 21:01:40 -080053namespace android {
54namespace vold {
55
Jeff Sharkey95c87cc2015-04-01 11:54:32 -070056security_context_t sBlkidContext = nullptr;
57security_context_t sBlkidUntrustedContext = nullptr;
58security_context_t sFsckContext = nullptr;
59security_context_t sFsckUntrustedContext = nullptr;
60
Paul Crowley56292ef2017-10-20 08:07:53 -070061bool sSleepOnUnmount = true;
62
Jeff Sharkey9c484982015-03-31 10:35:33 -070063static const char* kBlkidPath = "/system/bin/blkid";
Jeff Sharkeybc40cc82015-06-18 14:25:08 -070064static const char* kKeyPath = "/data/misc/vold";
Jeff Sharkey9c484982015-03-31 10:35:33 -070065
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070066static const char* kProcFilesystems = "/proc/filesystems";
67
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060068// Lock used to protect process-level SELinux changes from racing with each
69// other between multiple threads.
70static std::mutex kSecurityLock;
71
Jeff Sharkeydeb24052015-03-02 21:01:40 -080072status_t CreateDeviceNode(const std::string& path, dev_t dev) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -060073 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080074 const char* cpath = path.c_str();
75 status_t res = 0;
76
77 char* secontext = nullptr;
78 if (sehandle) {
79 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
80 setfscreatecon(secontext);
81 }
82 }
83
84 mode_t mode = 0660 | S_IFBLK;
85 if (mknod(cpath, mode, dev) < 0) {
86 if (errno != EEXIST) {
Paul Crowley14c8c072018-09-18 13:30:21 -070087 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
88 << " at " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080089 res = -errno;
90 }
91 }
92
93 if (secontext) {
94 setfscreatecon(nullptr);
95 freecon(secontext);
96 }
97
98 return res;
99}
100
101status_t DestroyDeviceNode(const std::string& path) {
102 const char* cpath = path.c_str();
103 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
104 return -errno;
105 } else {
106 return OK;
107 }
108}
109
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700110status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600111 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700112 const char* cpath = path.c_str();
113
114 char* secontext = nullptr;
115 if (sehandle) {
116 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
117 setfscreatecon(secontext);
118 }
119 }
120
121 int res = fs_prepare_dir(cpath, mode, uid, gid);
122
123 if (secontext) {
124 setfscreatecon(nullptr);
125 freecon(secontext);
126 }
127
128 if (res == 0) {
129 return OK;
130 } else {
131 return -errno;
132 }
133}
134
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800135status_t ForceUnmount(const std::string& path) {
136 const char* cpath = path.c_str();
137 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
138 return OK;
139 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700140 // Apps might still be handling eject request, so wait before
141 // we start sending signals
Paul Crowley56292ef2017-10-20 08:07:53 -0700142 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700143
Jeff Sharkey3472e522017-10-06 18:02:53 -0600144 KillProcessesWithOpenFiles(path, SIGINT);
Paul Crowley56292ef2017-10-20 08:07:53 -0700145 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700146 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
147 return OK;
148 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700149
Jeff Sharkey3472e522017-10-06 18:02:53 -0600150 KillProcessesWithOpenFiles(path, SIGTERM);
Paul Crowley56292ef2017-10-20 08:07:53 -0700151 if (sSleepOnUnmount) sleep(5);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800152 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
153 return OK;
154 }
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700155
Jeff Sharkey3472e522017-10-06 18:02:53 -0600156 KillProcessesWithOpenFiles(path, SIGKILL);
Paul Crowley56292ef2017-10-20 08:07:53 -0700157 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700158 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
159 return OK;
160 }
Jeff Sharkeyf0121c52015-04-06 14:08:45 -0700161
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800162 return -errno;
163}
164
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700165status_t KillProcessesUsingPath(const std::string& path) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600166 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700167 return OK;
168 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700169 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700170
Jeff Sharkey3472e522017-10-06 18:02:53 -0600171 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700172 return OK;
173 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700174 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700175
Jeff Sharkey3472e522017-10-06 18:02:53 -0600176 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700177 return OK;
178 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700179 if (sSleepOnUnmount) sleep(5);
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700180
181 // Send SIGKILL a second time to determine if we've
182 // actually killed everyone with open files
Jeff Sharkey3472e522017-10-06 18:02:53 -0600183 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
Jeff Sharkey89f74fb2015-10-21 12:16:12 -0700184 return OK;
185 }
186 PLOG(ERROR) << "Failed to kill processes using " << path;
187 return -EBUSY;
188}
189
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700190status_t BindMount(const std::string& source, const std::string& target) {
191 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
192 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
193 return -errno;
194 }
195 return OK;
196}
197
Jeff Sharkey3472e522017-10-06 18:02:53 -0600198bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
199 auto qual = key + "=\"";
200 auto start = raw.find(qual);
201 if (start > 0 && raw[start - 1] != ' ') {
202 start = raw.find(qual, start + 1);
203 }
204
205 if (start == std::string::npos) return false;
206 start += qual.length();
207
208 auto end = raw.find("\"", start);
209 if (end == std::string::npos) return false;
210
211 *value = raw.substr(start, end - start);
212 return true;
213}
214
Paul Crowley14c8c072018-09-18 13:30:21 -0700215static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
216 std::string* fsLabel, bool untrusted) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600217 fsType->clear();
218 fsUuid->clear();
219 fsLabel->clear();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700220
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700221 std::vector<std::string> cmd;
222 cmd.push_back(kBlkidPath);
223 cmd.push_back("-c");
224 cmd.push_back("/dev/null");
Jeff Sharkeyeddf9bd2015-08-12 16:04:35 -0700225 cmd.push_back("-s");
226 cmd.push_back("TYPE");
227 cmd.push_back("-s");
228 cmd.push_back("UUID");
229 cmd.push_back("-s");
230 cmd.push_back("LABEL");
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700231 cmd.push_back(path);
232
233 std::vector<std::string> output;
234 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
235 if (res != OK) {
236 LOG(WARNING) << "blkid failed to identify " << path;
237 return res;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700238 }
239
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700240 for (const auto& line : output) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700241 // Extract values from blkid output, if defined
Jeff Sharkey3472e522017-10-06 18:02:53 -0600242 FindValue(line, "TYPE", fsType);
243 FindValue(line, "UUID", fsUuid);
244 FindValue(line, "LABEL", fsLabel);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700245 }
246
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700247 return OK;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700248}
249
Paul Crowley14c8c072018-09-18 13:30:21 -0700250status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
251 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700252 return readMetadata(path, fsType, fsUuid, fsLabel, false);
253}
254
Paul Crowley14c8c072018-09-18 13:30:21 -0700255status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
256 std::string* fsLabel) {
Jeff Sharkey95c87cc2015-04-01 11:54:32 -0700257 return readMetadata(path, fsType, fsUuid, fsLabel, true);
258}
259
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700260status_t ForkExecvp(const std::vector<std::string>& args) {
261 return ForkExecvp(args, nullptr);
262}
263
264status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600265 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700266 size_t argc = args.size();
Paul Crowley14c8c072018-09-18 13:30:21 -0700267 char** argv = (char**)calloc(argc, sizeof(char*));
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700268 for (size_t i = 0; i < argc; i++) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700269 argv[i] = (char*)args[i].c_str();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700270 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700271 LOG(DEBUG) << args[i];
Jeff Sharkey9c484982015-03-31 10:35:33 -0700272 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700273 LOG(DEBUG) << " " << args[i];
Jeff Sharkey9c484982015-03-31 10:35:33 -0700274 }
275 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700276
Paul Crowley82b41ff2017-10-20 08:17:54 -0700277 if (context) {
278 if (setexeccon(context)) {
279 LOG(ERROR) << "Failed to setexeccon";
280 abort();
281 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700282 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700283 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
Paul Crowley82b41ff2017-10-20 08:17:54 -0700284 if (context) {
285 if (setexeccon(nullptr)) {
286 LOG(ERROR) << "Failed to setexeccon";
287 abort();
288 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700289 }
290
Jeff Sharkey9c484982015-03-31 10:35:33 -0700291 free(argv);
292 return res;
293}
294
Paul Crowley14c8c072018-09-18 13:30:21 -0700295status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700296 return ForkExecvp(args, output, nullptr);
297}
298
Paul Crowley14c8c072018-09-18 13:30:21 -0700299status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output,
300 security_context_t context) {
Jeff Sharkeyae4f85d2017-10-18 17:02:21 -0600301 std::lock_guard<std::mutex> lock(kSecurityLock);
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700302 std::string cmd;
303 for (size_t i = 0; i < args.size(); i++) {
304 cmd += args[i] + " ";
305 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700306 LOG(DEBUG) << args[i];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700307 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700308 LOG(DEBUG) << " " << args[i];
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700309 }
310 }
311 output.clear();
312
Paul Crowley82b41ff2017-10-20 08:17:54 -0700313 if (context) {
314 if (setexeccon(context)) {
315 LOG(ERROR) << "Failed to setexeccon";
316 abort();
317 }
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700318 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700319 FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
Paul Crowley82b41ff2017-10-20 08:17:54 -0700320 if (context) {
321 if (setexeccon(nullptr)) {
322 LOG(ERROR) << "Failed to setexeccon";
323 abort();
324 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700325 }
326
327 if (!fp) {
328 PLOG(ERROR) << "Failed to popen " << cmd;
329 return -errno;
330 }
331 char line[1024];
332 while (fgets(line, sizeof(line), fp) != nullptr) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700333 LOG(DEBUG) << line;
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700334 output.push_back(std::string(line));
335 }
336 if (pclose(fp) != 0) {
337 PLOG(ERROR) << "Failed to pclose " << cmd;
338 return -errno;
339 }
340
341 return OK;
342}
343
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700344pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
345 size_t argc = args.size();
Paul Crowley14c8c072018-09-18 13:30:21 -0700346 char** argv = (char**)calloc(argc + 1, sizeof(char*));
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700347 for (size_t i = 0; i < argc; i++) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700348 argv[i] = (char*)args[i].c_str();
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700349 if (i == 0) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700350 LOG(DEBUG) << args[i];
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700351 } else {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700352 LOG(DEBUG) << " " << args[i];
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700353 }
354 }
355
356 pid_t pid = fork();
357 if (pid == 0) {
358 close(STDIN_FILENO);
359 close(STDOUT_FILENO);
360 close(STDERR_FILENO);
361
362 if (execvp(argv[0], argv)) {
363 PLOG(ERROR) << "Failed to exec";
364 }
365
366 _exit(1);
367 }
368
369 if (pid == -1) {
370 PLOG(ERROR) << "Failed to exec";
371 }
372
373 free(argv);
374 return pid;
375}
376
Jeff Sharkey9c484982015-03-31 10:35:33 -0700377status_t ReadRandomBytes(size_t bytes, std::string& out) {
Pavel Grafove2e2d302017-08-01 17:15:53 +0100378 out.resize(bytes);
379 return ReadRandomBytes(bytes, &out[0]);
380}
Jeff Sharkey9c484982015-03-31 10:35:33 -0700381
Pavel Grafove2e2d302017-08-01 17:15:53 +0100382status_t ReadRandomBytes(size_t bytes, char* buf) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700383 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
384 if (fd == -1) {
385 return -errno;
386 }
387
Jeff Sharkey9c484982015-03-31 10:35:33 -0700388 size_t n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100389 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700390 bytes -= n;
Pavel Grafove2e2d302017-08-01 17:15:53 +0100391 buf += n;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700392 }
Elliott Hughesa6231082015-05-15 18:34:24 -0700393 close(fd);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700394
395 if (bytes == 0) {
396 return OK;
397 } else {
398 return -EIO;
399 }
400}
401
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600402status_t GenerateRandomUuid(std::string& out) {
403 status_t res = ReadRandomBytes(16, out);
404 if (res == OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700405 out[6] &= 0x0f; /* clear version */
406 out[6] |= 0x40; /* set to version 4 */
407 out[8] &= 0x3f; /* clear variant */
408 out[8] |= 0x80; /* set to IETF variant */
Jeff Sharkey46bb69f2017-06-21 13:52:23 -0600409 }
410 return res;
411}
412
Jeff Sharkey9c484982015-03-31 10:35:33 -0700413status_t HexToStr(const std::string& hex, std::string& str) {
414 str.clear();
415 bool even = true;
416 char cur = 0;
417 for (size_t i = 0; i < hex.size(); i++) {
418 int val = 0;
419 switch (hex[i]) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700420 // clang-format off
421 case ' ': case '-': case ':': continue;
422 case 'f': case 'F': val = 15; break;
423 case 'e': case 'E': val = 14; break;
424 case 'd': case 'D': val = 13; break;
425 case 'c': case 'C': val = 12; break;
426 case 'b': case 'B': val = 11; break;
427 case 'a': case 'A': val = 10; break;
428 case '9': val = 9; break;
429 case '8': val = 8; break;
430 case '7': val = 7; break;
431 case '6': val = 6; break;
432 case '5': val = 5; break;
433 case '4': val = 4; break;
434 case '3': val = 3; break;
435 case '2': val = 2; break;
436 case '1': val = 1; break;
437 case '0': val = 0; break;
438 default: return -EINVAL;
439 // clang-format on
Jeff Sharkey9c484982015-03-31 10:35:33 -0700440 }
441
442 if (even) {
443 cur = val << 4;
444 } else {
445 cur += val;
446 str.push_back(cur);
447 cur = 0;
448 }
449 even = !even;
450 }
451 return even ? OK : -EINVAL;
452}
453
454static const char* kLookup = "0123456789abcdef";
455
456status_t StrToHex(const std::string& str, std::string& hex) {
457 hex.clear();
458 for (size_t i = 0; i < str.size(); i++) {
Jeff Sharkeyef369752015-04-29 15:57:48 -0700459 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700460 hex.push_back(kLookup[str[i] & 0x0F]);
461 }
462 return OK;
463}
464
Pavel Grafove2e2d302017-08-01 17:15:53 +0100465status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
466 hex.clear();
467 for (size_t i = 0; i < str.size(); i++) {
468 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
469 hex.push_back(kLookup[str.data()[i] & 0x0F]);
470 }
471 return OK;
472}
473
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700474status_t NormalizeHex(const std::string& in, std::string& out) {
475 std::string tmp;
476 if (HexToStr(in, tmp)) {
477 return -EINVAL;
478 }
479 return StrToHex(tmp, out);
480}
481
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200482status_t GetBlockDevSize(int fd, uint64_t* size) {
483 if (ioctl(fd, BLKGETSIZE64, size)) {
484 return -errno;
485 }
486
487 return OK;
488}
489
490status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
491 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
492 status_t res = OK;
493
494 if (fd < 0) {
495 return -errno;
496 }
497
498 res = GetBlockDevSize(fd, size);
499
500 close(fd);
501
502 return res;
503}
504
505status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
506 uint64_t size;
507 status_t res = GetBlockDevSize(path, &size);
508
509 if (res != OK) {
510 return res;
511 }
512
513 *nr_sec = size / 512;
514
515 return OK;
516}
517
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700518uint64_t GetFreeBytes(const std::string& path) {
519 struct statvfs sb;
520 if (statvfs(path.c_str(), &sb) == 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700521 return (uint64_t)sb.f_bavail * sb.f_frsize;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700522 } else {
523 return -1;
524 }
525}
526
527// TODO: borrowed from frameworks/native/libs/diskusage/ which should
528// eventually be migrated into system/
Paul Crowley14c8c072018-09-18 13:30:21 -0700529static int64_t stat_size(struct stat* s) {
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700530 int64_t blksize = s->st_blksize;
531 // count actual blocks used instead of nominal file size
532 int64_t size = s->st_blocks * 512;
533
534 if (blksize) {
535 /* round up to filesystem block size */
536 size = (size + blksize - 1) & (~(blksize - 1));
537 }
538
539 return size;
540}
541
542// TODO: borrowed from frameworks/native/libs/diskusage/ which should
543// eventually be migrated into system/
544int64_t calculate_dir_size(int dfd) {
545 int64_t size = 0;
546 struct stat s;
Paul Crowley14c8c072018-09-18 13:30:21 -0700547 DIR* d;
548 struct dirent* de;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700549
550 d = fdopendir(dfd);
551 if (d == NULL) {
552 close(dfd);
553 return 0;
554 }
555
556 while ((de = readdir(d))) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700557 const char* name = de->d_name;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700558 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
559 size += stat_size(&s);
560 }
561 if (de->d_type == DT_DIR) {
562 int subfd;
563
564 /* always skip "." and ".." */
565 if (name[0] == '.') {
Paul Crowley14c8c072018-09-18 13:30:21 -0700566 if (name[1] == 0) continue;
567 if ((name[1] == '.') && (name[2] == 0)) continue;
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700568 }
569
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600570 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700571 if (subfd >= 0) {
572 size += calculate_dir_size(subfd);
573 }
574 }
575 }
576 closedir(d);
577 return size;
578}
579
580uint64_t GetTreeBytes(const std::string& path) {
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600581 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700582 if (dirfd < 0) {
583 PLOG(WARNING) << "Failed to open " << path;
584 return -1;
585 } else {
Josh Gao72fb1a62018-05-29 19:05:16 -0700586 return calculate_dir_size(dirfd);
Jeff Sharkey1d6fbcc2015-04-24 16:00:03 -0700587 }
588}
589
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700590bool IsFilesystemSupported(const std::string& fsType) {
591 std::string supported;
592 if (!ReadFileToString(kProcFilesystems, &supported)) {
593 PLOG(ERROR) << "Failed to read supported filesystems";
594 return false;
595 }
596 return supported.find(fsType + "\n") != std::string::npos;
597}
598
599status_t WipeBlockDevice(const std::string& path) {
600 status_t res = -1;
601 const char* c_path = path.c_str();
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200602 uint64_t range[2] = {0, 0};
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700603
604 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
605 if (fd == -1) {
606 PLOG(ERROR) << "Failed to open " << path;
607 goto done;
608 }
609
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200610 if (GetBlockDevSize(fd, &range[1]) != OK) {
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700611 PLOG(ERROR) << "Failed to determine size of " << path;
612 goto done;
613 }
614
Jeff Sharkeyd0640f62015-05-21 22:35:42 -0700615 LOG(INFO) << "About to discard " << range[1] << " on " << path;
616 if (ioctl(fd, BLKDISCARD, &range) == 0) {
617 LOG(INFO) << "Discard success on " << path;
618 res = 0;
619 } else {
620 PLOG(ERROR) << "Discard failure on " << path;
621 }
622
623done:
624 close(fd);
625 return res;
626}
627
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800628static bool isValidFilename(const std::string& name) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700629 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800630 return false;
631 } else {
632 return true;
633 }
634}
635
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700636std::string BuildKeyPath(const std::string& partGuid) {
637 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
638}
639
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600640std::string BuildDataSystemLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700641 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600642}
643
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800644std::string BuildDataSystemCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700645 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700646}
647
648std::string BuildDataSystemDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700649 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700650}
651
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600652std::string BuildDataMiscLegacyPath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700653 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeybe70c9a2016-04-14 20:45:16 -0600654}
655
Jeff Sharkey47695b22016-02-01 17:02:29 -0700656std::string BuildDataMiscCePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700657 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkey47695b22016-02-01 17:02:29 -0700658}
659
660std::string BuildDataMiscDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700661 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800662}
663
Calin Juravle79f55a42016-02-17 20:14:46 +0000664// Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
665std::string BuildDataProfilesDePath(userid_t userId) {
Paul Crowley3b71fc52017-10-09 10:55:21 -0700666 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
Calin Juravle79f55a42016-02-17 20:14:46 +0000667}
668
Andreas Huber71cd43f2018-01-22 11:25:29 -0800669std::string BuildDataVendorCePath(userid_t userId) {
670 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
671}
672
673std::string BuildDataVendorDePath(userid_t userId) {
674 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
675}
676
Paul Crowley3b71fc52017-10-09 10:55:21 -0700677std::string BuildDataPath(const std::string& volumeUuid) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800678 // TODO: unify with installd path generation logic
Paul Crowley3b71fc52017-10-09 10:55:21 -0700679 if (volumeUuid.empty()) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800680 return "/data";
681 } else {
682 CHECK(isValidFilename(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700683 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800684 }
685}
686
Paul Crowley3b71fc52017-10-09 10:55:21 -0700687std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyfc505c32015-12-07 17:27:01 -0700688 // TODO: unify with installd path generation logic
689 std::string data(BuildDataPath(volumeUuid));
690 return StringPrintf("%s/media/%u", data.c_str(), userId);
691}
692
Paul Crowley3b71fc52017-10-09 10:55:21 -0700693std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800694 // TODO: unify with installd path generation logic
695 std::string data(BuildDataPath(volumeUuid));
Paul Crowley3b71fc52017-10-09 10:55:21 -0700696 if (volumeUuid.empty() && userId == 0) {
cjbaoeb501142017-04-12 00:09:00 +0800697 std::string legacy = StringPrintf("%s/data", data.c_str());
698 struct stat sb;
699 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
700 /* /data/data is dir, return /data/data for legacy system */
701 return legacy;
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800702 }
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800703 }
cjbaoeb501142017-04-12 00:09:00 +0800704 return StringPrintf("%s/user/%u", data.c_str(), userId);
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800705}
706
Paul Crowley3b71fc52017-10-09 10:55:21 -0700707std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
Jeff Sharkeyd2c96e72015-11-08 17:56:23 -0800708 // TODO: unify with installd path generation logic
709 std::string data(BuildDataPath(volumeUuid));
710 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
711}
712
Jeff Sharkey66270a22015-06-24 11:49:24 -0700713dev_t GetDevice(const std::string& path) {
714 struct stat sb;
715 if (stat(path.c_str(), &sb)) {
716 PLOG(WARNING) << "Failed to stat " << path;
717 return 0;
718 } else {
719 return sb.st_dev;
720 }
721}
722
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600723status_t RestoreconRecursive(const std::string& path) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700724 LOG(DEBUG) << "Starting restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600725
Tom Cherryd6127ef2017-06-15 17:13:56 -0700726 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600727
Tom Cherryd6127ef2017-06-15 17:13:56 -0700728 android::base::SetProperty(kRestoreconString, "");
729 android::base::SetProperty(kRestoreconString, path);
730
731 android::base::WaitForProperty(kRestoreconString, path);
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600732
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700733 LOG(DEBUG) << "Finished restorecon of " << path;
Jeff Sharkeyd24aeda2016-07-15 16:20:22 -0600734 return OK;
735}
736
Jeff Sharkey3472e522017-10-06 18:02:53 -0600737bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
738 // Shamelessly borrowed from android::base::Readlink()
739 result->clear();
740
741 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
742 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
743 // waste memory to just start there. We add 1 so that we can recognize
744 // whether it actually fit (rather than being truncated to 4095).
745 std::vector<char> buf(4095 + 1);
746 while (true) {
747 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
748 // Unrecoverable error?
Paul Crowley14c8c072018-09-18 13:30:21 -0700749 if (size == -1) return false;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600750 // It fit! (If size == buf.size(), it may have been truncated.)
751 if (static_cast<size_t>(size) < buf.size()) {
752 result->assign(&buf[0], size);
753 return true;
754 }
755 // Double our buffer and try again.
756 buf.resize(buf.size() * 2);
Daichi Hirono10d34882016-01-29 14:33:51 +0900757 }
758}
759
Yu Ning942d4e82016-01-08 17:36:47 +0800760bool IsRunningInEmulator() {
Tom Cherryd6127ef2017-06-15 17:13:56 -0700761 return android::base::GetBoolProperty("ro.kernel.qemu", false);
Yu Ning942d4e82016-01-08 17:36:47 +0800762}
763
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700764status_t UnmountTree(const std::string& prefix) {
765 FILE* fp = setmntent("/proc/mounts", "r");
766 if (fp == NULL) {
767 PLOG(ERROR) << "Failed to open /proc/mounts";
768 return -errno;
769 }
770
771 // Some volumes can be stacked on each other, so force unmount in
772 // reverse order to give us the best chance of success.
773 std::list<std::string> toUnmount;
774 mntent* mentry;
775 while ((mentry = getmntent(fp)) != NULL) {
776 auto test = std::string(mentry->mnt_dir) + "/";
777 if (android::base::StartsWith(test, prefix)) {
778 toUnmount.push_front(test);
779 }
780 }
781 endmntent(fp);
782
783 for (const auto& path : toUnmount) {
784 if (umount2(path.c_str(), MNT_DETACH)) {
785 PLOG(ERROR) << "Failed to unmount " << path;
786 }
787 }
788 return OK;
789}
790
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800791} // namespace vold
792} // namespace android