blob: 28dd15aaf5a9261c0890fd01bd21133bd96fb607 [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 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#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.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 <android-base/strings.h>
26#include <android/content/pm/IDataLoaderStatusListener.h>
27#include <android/os/IVold.h>
28#include <androidfw/ZipFileRO.h>
29#include <androidfw/ZipUtils.h>
30#include <binder/BinderService.h>
31#include <binder/ParcelFileDescriptor.h>
32#include <binder/Status.h>
33#include <sys/stat.h>
34#include <uuid/uuid.h>
35#include <zlib.h>
36
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080037#include <ctime>
Songchun Fan1124fd32020-02-10 12:49:41 -080038#include <filesystem>
Songchun Fan3c82a302019-11-29 14:23:45 -080039#include <iterator>
40#include <span>
41#include <stack>
42#include <thread>
43#include <type_traits>
44
45#include "Metadata.pb.h"
46
47using namespace std::literals;
48using namespace android::content::pm;
Songchun Fan1124fd32020-02-10 12:49:41 -080049namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080050
51namespace android::incremental {
52
53namespace {
54
55using IncrementalFileSystemControlParcel =
56 ::android::os::incremental::IncrementalFileSystemControlParcel;
57
58struct Constants {
59 static constexpr auto backing = "backing_store"sv;
60 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080061 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080062 static constexpr auto storagePrefix = "st"sv;
63 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
64 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080065 static constexpr auto libDir = "lib"sv;
66 static constexpr auto libSuffix = ".so"sv;
67 static constexpr auto blockSize = 4096;
Songchun Fan3c82a302019-11-29 14:23:45 -080068};
69
70static const Constants& constants() {
71 static Constants c;
72 return c;
73}
74
75template <base::LogSeverity level = base::ERROR>
76bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
77 auto cstr = path::c_str(name);
78 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080079 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080080 PLOG(level) << "Can't create directory '" << name << '\'';
81 return false;
82 }
83 struct stat st;
84 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
85 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
86 return false;
87 }
88 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080089 if (::chmod(cstr, mode)) {
90 PLOG(level) << "Changing permission failed for '" << name << '\'';
91 return false;
92 }
93
Songchun Fan3c82a302019-11-29 14:23:45 -080094 return true;
95}
96
97static std::string toMountKey(std::string_view path) {
98 if (path.empty()) {
99 return "@none";
100 }
101 if (path == "/"sv) {
102 return "@root";
103 }
104 if (path::isAbsolute(path)) {
105 path.remove_prefix(1);
106 }
107 std::string res(path);
108 std::replace(res.begin(), res.end(), '/', '_');
109 std::replace(res.begin(), res.end(), '@', '_');
Songchun Fan1124fd32020-02-10 12:49:41 -0800110 return std::string(constants().mountKeyPrefix) + res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800111}
112
113static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
114 std::string_view path) {
115 auto mountKey = toMountKey(path);
116 const auto prefixSize = mountKey.size();
117 for (int counter = 0; counter < 1000;
118 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
119 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800120 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800121 return {mountKey, mountRoot};
122 }
123 }
124 return {};
125}
126
127template <class ProtoMessage, class Control>
128static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
129 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800130 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800131 ProtoMessage message;
132 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
133}
134
135static bool isValidMountTarget(std::string_view path) {
136 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
137}
138
139std::string makeBindMdName() {
140 static constexpr auto uuidStringSize = 36;
141
142 uuid_t guid;
143 uuid_generate(guid);
144
145 std::string name;
146 const auto prefixSize = constants().mountpointMdPrefix.size();
147 name.reserve(prefixSize + uuidStringSize);
148
149 name = constants().mountpointMdPrefix;
150 name.resize(prefixSize + uuidStringSize);
151 uuid_unparse(guid, name.data() + prefixSize);
152
153 return name;
154}
155} // namespace
156
157IncrementalService::IncFsMount::~IncFsMount() {
Songchun Fan68645c42020-02-27 15:57:35 -0800158 incrementalService.mDataLoaderManager->destroyDataLoader(mountId);
Songchun Fan3c82a302019-11-29 14:23:45 -0800159 control.reset();
160 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
161 for (auto&& [target, _] : bindPoints) {
162 LOG(INFO) << "\tbind: " << target;
163 incrementalService.mVold->unmountIncFs(target);
164 }
165 LOG(INFO) << "\troot: " << root;
166 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
167 cleanupFilesystem(root);
168}
169
170auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800171 std::string name;
172 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
173 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
174 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800175 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
176 constants().storagePrefix.data(), id, no);
177 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800178 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800179 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800180 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
181 } else if (err != EEXIST) {
182 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
183 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800184 }
185 }
186 nextStorageDirNo = 0;
187 return storages.end();
188}
189
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800190static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
191 return {::opendir(path), ::closedir};
192}
193
194static int rmDirContent(const char* path) {
195 auto dir = openDir(path);
196 if (!dir) {
197 return -EINVAL;
198 }
199 while (auto entry = ::readdir(dir.get())) {
200 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
201 continue;
202 }
203 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
204 if (entry->d_type == DT_DIR) {
205 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
206 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
207 return err;
208 }
209 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
210 PLOG(WARNING) << "Failed to rmdir " << fullPath;
211 return err;
212 }
213 } else {
214 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
215 PLOG(WARNING) << "Failed to delete " << fullPath;
216 return err;
217 }
218 }
219 }
220 return 0;
221}
222
Songchun Fan3c82a302019-11-29 14:23:45 -0800223void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800224 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800225 ::rmdir(path::join(root, constants().backing).c_str());
226 ::rmdir(path::join(root, constants().mount).c_str());
227 ::rmdir(path::c_str(root));
228}
229
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800230IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800231 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800232 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800233 mIncFs(sm.getIncFs()),
234 mIncrementalDir(rootDir) {
235 if (!mVold) {
236 LOG(FATAL) << "Vold service is unavailable";
237 }
Songchun Fan68645c42020-02-27 15:57:35 -0800238 if (!mDataLoaderManager) {
239 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800240 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800241 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800242}
243
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800244FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800245 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800246}
247
Songchun Fan3c82a302019-11-29 14:23:45 -0800248IncrementalService::~IncrementalService() = default;
249
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800250inline const char* toString(TimePoint t) {
251 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800252 time_t time = SystemClock::to_time_t(
253 SystemClock::now() +
254 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800255 return std::ctime(&time);
256}
257
258inline const char* toString(IncrementalService::BindKind kind) {
259 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800260 case IncrementalService::BindKind::Temporary:
261 return "Temporary";
262 case IncrementalService::BindKind::Permanent:
263 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800264 }
265}
266
267void IncrementalService::onDump(int fd) {
268 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
269 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
270
271 std::unique_lock l(mLock);
272
273 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
274 for (auto&& [id, ifs] : mMounts) {
275 const IncFsMount& mnt = *ifs.get();
276 dprintf(fd, "\t[%d]:\n", id);
277 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
278 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
279 dprintf(fd, "\t\tdataLoaderStatus: %d\n", mnt.dataLoaderStatus.load());
280 dprintf(fd, "\t\tconnectionLostTime: %s\n", toString(mnt.connectionLostTime));
281 if (mnt.savedDataLoaderParams) {
282 const auto& params = mnt.savedDataLoaderParams.value();
283 dprintf(fd, "\t\tsavedDataLoaderParams:\n");
284 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
285 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
286 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
287 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800288 }
289 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
290 for (auto&& [storageId, storage] : mnt.storages) {
291 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
292 }
293
294 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
295 for (auto&& [target, bind] : mnt.bindPoints) {
296 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
297 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
298 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
299 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
300 }
301 }
302
303 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
304 for (auto&& [target, mountPairIt] : mBindsByPath) {
305 const auto& bind = mountPairIt->second;
306 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
307 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
308 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
309 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
310 }
311}
312
Songchun Fan3c82a302019-11-29 14:23:45 -0800313std::optional<std::future<void>> IncrementalService::onSystemReady() {
314 std::promise<void> threadFinished;
315 if (mSystemReady.exchange(true)) {
316 return {};
317 }
318
319 std::vector<IfsMountPtr> mounts;
320 {
321 std::lock_guard l(mLock);
322 mounts.reserve(mMounts.size());
323 for (auto&& [id, ifs] : mMounts) {
324 if (ifs->mountId == id) {
325 mounts.push_back(ifs);
326 }
327 }
328 }
329
330 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800331 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800332 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800333 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
334 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800335 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800336 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800337 }
338 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800339 mPrepareDataLoaders.set_value_at_thread_exit();
340 }).detach();
341 return mPrepareDataLoaders.get_future();
342}
343
344auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
345 for (;;) {
346 if (mNextId == kMaxStorageId) {
347 mNextId = 0;
348 }
349 auto id = ++mNextId;
350 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
351 if (inserted) {
352 return it;
353 }
354 }
355}
356
Songchun Fan1124fd32020-02-10 12:49:41 -0800357StorageId IncrementalService::createStorage(
358 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
359 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800360 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
361 if (!path::isAbsolute(mountPoint)) {
362 LOG(ERROR) << "path is not absolute: " << mountPoint;
363 return kInvalidStorageId;
364 }
365
366 auto mountNorm = path::normalize(mountPoint);
367 {
368 const auto id = findStorageId(mountNorm);
369 if (id != kInvalidStorageId) {
370 if (options & CreateOptions::OpenExisting) {
371 LOG(INFO) << "Opened existing storage " << id;
372 return id;
373 }
374 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
375 return kInvalidStorageId;
376 }
377 }
378
379 if (!(options & CreateOptions::CreateNew)) {
380 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
381 return kInvalidStorageId;
382 }
383
384 if (!path::isEmptyDir(mountNorm)) {
385 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
386 return kInvalidStorageId;
387 }
388 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
389 if (mountRoot.empty()) {
390 LOG(ERROR) << "Bad mount point";
391 return kInvalidStorageId;
392 }
393 // Make sure the code removes all crap it may create while still failing.
394 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
395 auto firstCleanupOnFailure =
396 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
397
398 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800399 const auto backing = path::join(mountRoot, constants().backing);
400 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800401 return kInvalidStorageId;
402 }
403
Songchun Fan3c82a302019-11-29 14:23:45 -0800404 IncFsMount::Control control;
405 {
406 std::lock_guard l(mMountOperationLock);
407 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800408
409 if (auto err = rmDirContent(backing.c_str())) {
410 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
411 return kInvalidStorageId;
412 }
413 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
414 return kInvalidStorageId;
415 }
416 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800417 if (!status.isOk()) {
418 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
419 return kInvalidStorageId;
420 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800421 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
422 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800423 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
424 return kInvalidStorageId;
425 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800426 control.cmd = controlParcel.cmd.release().release();
427 control.pendingReads = controlParcel.pendingReads.release().release();
428 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800429 }
430
431 std::unique_lock l(mLock);
432 const auto mountIt = getStorageSlotLocked();
433 const auto mountId = mountIt->first;
434 l.unlock();
435
436 auto ifs =
437 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
438 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
439 // is the removal of the |ifs|.
440 firstCleanupOnFailure.release();
441
442 auto secondCleanup = [this, &l](auto itPtr) {
443 if (!l.owns_lock()) {
444 l.lock();
445 }
446 mMounts.erase(*itPtr);
447 };
448 auto secondCleanupOnFailure =
449 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
450
451 const auto storageIt = ifs->makeStorage(ifs->mountId);
452 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800453 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800454 return kInvalidStorageId;
455 }
456
457 {
458 metadata::Mount m;
459 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800460 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Songchun Fan3c82a302019-11-29 14:23:45 -0800461 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800462 m.mutable_loader()->set_class_name(dataLoaderParams.className);
463 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800464 const auto metadata = m.SerializeAsString();
465 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800466 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800467 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800468 if (auto err =
469 mIncFs->makeFile(ifs->control,
470 path::join(ifs->root, constants().mount,
471 constants().infoMdName),
472 0777, idFromMetadata(metadata),
473 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800474 LOG(ERROR) << "Saving mount metadata failed: " << -err;
475 return kInvalidStorageId;
476 }
477 }
478
479 const auto bk =
480 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800481 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
482 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800483 err < 0) {
484 LOG(ERROR) << "adding bind mount failed: " << -err;
485 return kInvalidStorageId;
486 }
487
488 // Done here as well, all data structures are in good state.
489 secondCleanupOnFailure.release();
490
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800491 if (!prepareDataLoader(*ifs, &dataLoaderParams, &dataLoaderStatusListener)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800492 LOG(ERROR) << "prepareDataLoader() failed";
493 deleteStorageLocked(*ifs, std::move(l));
494 return kInvalidStorageId;
495 }
496
497 mountIt->second = std::move(ifs);
498 l.unlock();
499 LOG(INFO) << "created storage " << mountId;
500 return mountId;
501}
502
503StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
504 StorageId linkedStorage,
505 IncrementalService::CreateOptions options) {
506 if (!isValidMountTarget(mountPoint)) {
507 LOG(ERROR) << "Mount point is invalid or missing";
508 return kInvalidStorageId;
509 }
510
511 std::unique_lock l(mLock);
512 const auto& ifs = getIfsLocked(linkedStorage);
513 if (!ifs) {
514 LOG(ERROR) << "Ifs unavailable";
515 return kInvalidStorageId;
516 }
517
518 const auto mountIt = getStorageSlotLocked();
519 const auto storageId = mountIt->first;
520 const auto storageIt = ifs->makeStorage(storageId);
521 if (storageIt == ifs->storages.end()) {
522 LOG(ERROR) << "Can't create a new storage";
523 mMounts.erase(mountIt);
524 return kInvalidStorageId;
525 }
526
527 l.unlock();
528
529 const auto bk =
530 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800531 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
532 std::string(storageIt->second.name), path::normalize(mountPoint),
533 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800534 err < 0) {
535 LOG(ERROR) << "bindMount failed with error: " << err;
536 return kInvalidStorageId;
537 }
538
539 mountIt->second = ifs;
540 return storageId;
541}
542
543IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
544 std::string_view path) const {
545 auto bindPointIt = mBindsByPath.upper_bound(path);
546 if (bindPointIt == mBindsByPath.begin()) {
547 return mBindsByPath.end();
548 }
549 --bindPointIt;
550 if (!path::startsWith(path, bindPointIt->first)) {
551 return mBindsByPath.end();
552 }
553 return bindPointIt;
554}
555
556StorageId IncrementalService::findStorageId(std::string_view path) const {
557 std::lock_guard l(mLock);
558 auto it = findStorageLocked(path);
559 if (it == mBindsByPath.end()) {
560 return kInvalidStorageId;
561 }
562 return it->second->second.storage;
563}
564
565void IncrementalService::deleteStorage(StorageId storageId) {
566 const auto ifs = getIfs(storageId);
567 if (!ifs) {
568 return;
569 }
570 deleteStorage(*ifs);
571}
572
573void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
574 std::unique_lock l(ifs.lock);
575 deleteStorageLocked(ifs, std::move(l));
576}
577
578void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
579 std::unique_lock<std::mutex>&& ifsLock) {
580 const auto storages = std::move(ifs.storages);
581 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
582 const auto bindPoints = ifs.bindPoints;
583 ifsLock.unlock();
584
585 std::lock_guard l(mLock);
586 for (auto&& [id, _] : storages) {
587 if (id != ifs.mountId) {
588 mMounts.erase(id);
589 }
590 }
591 for (auto&& [path, _] : bindPoints) {
592 mBindsByPath.erase(path);
593 }
594 mMounts.erase(ifs.mountId);
595}
596
597StorageId IncrementalService::openStorage(std::string_view pathInMount) {
598 if (!path::isAbsolute(pathInMount)) {
599 return kInvalidStorageId;
600 }
601
602 return findStorageId(path::normalize(pathInMount));
603}
604
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800605FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800606 const auto ifs = getIfs(storage);
607 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800608 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800609 }
610 std::unique_lock l(ifs->lock);
611 auto storageIt = ifs->storages.find(storage);
612 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800613 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800614 }
615 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800616 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800617 }
618 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
619 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800620 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800621}
622
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800623std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800624 StorageId storage, std::string_view subpath) const {
625 auto name = path::basename(subpath);
626 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800627 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800628 }
629 auto dir = path::dirname(subpath);
630 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800631 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800632 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800633 auto id = nodeFor(storage, dir);
634 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800635}
636
637IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
638 std::lock_guard l(mLock);
639 return getIfsLocked(storage);
640}
641
642const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
643 auto it = mMounts.find(storage);
644 if (it == mMounts.end()) {
645 static const IfsMountPtr kEmpty = {};
646 return kEmpty;
647 }
648 return it->second;
649}
650
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800651int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
652 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800653 if (!isValidMountTarget(target)) {
654 return -EINVAL;
655 }
656
657 const auto ifs = getIfs(storage);
658 if (!ifs) {
659 return -EINVAL;
660 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800661
Songchun Fan3c82a302019-11-29 14:23:45 -0800662 std::unique_lock l(ifs->lock);
663 const auto storageInfo = ifs->storages.find(storage);
664 if (storageInfo == ifs->storages.end()) {
665 return -EINVAL;
666 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800667 std::string normSource = normalizePathToStorage(ifs, storage, source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800668 l.unlock();
669 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800670 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
671 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800672}
673
674int IncrementalService::unbind(StorageId storage, std::string_view target) {
675 if (!path::isAbsolute(target)) {
676 return -EINVAL;
677 }
678
679 LOG(INFO) << "Removing bind point " << target;
680
681 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
682 // otherwise there's a chance to unmount something completely unrelated
683 const auto norm = path::normalize(target);
684 std::unique_lock l(mLock);
685 const auto storageIt = mBindsByPath.find(norm);
686 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
687 return -EINVAL;
688 }
689 const auto bindIt = storageIt->second;
690 const auto storageId = bindIt->second.storage;
691 const auto ifs = getIfsLocked(storageId);
692 if (!ifs) {
693 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
694 << " is missing";
695 return -EFAULT;
696 }
697 mBindsByPath.erase(storageIt);
698 l.unlock();
699
700 mVold->unmountIncFs(bindIt->first);
701 std::unique_lock l2(ifs->lock);
702 if (ifs->bindPoints.size() <= 1) {
703 ifs->bindPoints.clear();
704 deleteStorageLocked(*ifs, std::move(l2));
705 } else {
706 const std::string savedFile = std::move(bindIt->second.savedFilename);
707 ifs->bindPoints.erase(bindIt);
708 l2.unlock();
709 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800710 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800711 }
712 }
713 return 0;
714}
715
Songchun Fan103ba1d2020-02-03 17:32:32 -0800716std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr ifs,
717 StorageId storage, std::string_view path) {
718 const auto storageInfo = ifs->storages.find(storage);
719 if (storageInfo == ifs->storages.end()) {
720 return {};
721 }
722 std::string normPath;
723 if (path::isAbsolute(path)) {
724 normPath = path::normalize(path);
725 } else {
726 normPath = path::normalize(path::join(storageInfo->second.name, path));
727 }
728 if (!path::startsWith(normPath, storageInfo->second.name)) {
729 return {};
730 }
731 return normPath;
732}
733
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800734int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
735 incfs::NewFileParams params) {
736 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800737 std::string normPath = normalizePathToStorage(ifs, storage, path);
738 if (normPath.empty()) {
Songchun Fan54c6aed2020-01-31 16:52:41 -0800739 return -EINVAL;
740 }
741 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800742 if (err) {
743 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800744 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800745 std::vector<uint8_t> metadataBytes;
746 if (params.metadata.data && params.metadata.size > 0) {
747 metadataBytes.assign(params.metadata.data, params.metadata.data + params.metadata.size);
Songchun Fan3c82a302019-11-29 14:23:45 -0800748 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800749 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800750 }
751 return -EINVAL;
752}
753
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800754int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800755 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800756 std::string normPath = normalizePathToStorage(ifs, storageId, path);
757 if (normPath.empty()) {
758 return -EINVAL;
759 }
760 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800761 }
762 return -EINVAL;
763}
764
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800765int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800766 const auto ifs = getIfs(storageId);
767 if (!ifs) {
768 return -EINVAL;
769 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800770 std::string normPath = normalizePathToStorage(ifs, storageId, path);
771 if (normPath.empty()) {
772 return -EINVAL;
773 }
774 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800775 if (err == -EEXIST) {
776 return 0;
777 } else if (err != -ENOENT) {
778 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800779 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800780 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800781 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800782 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800783 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800784}
785
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800786int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
787 StorageId destStorageId, std::string_view newPath) {
788 if (auto ifsSrc = getIfs(sourceStorageId), ifsDest = getIfs(destStorageId);
789 ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800790 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
791 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
792 if (normOldPath.empty() || normNewPath.empty()) {
793 return -EINVAL;
794 }
795 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800796 }
797 return -EINVAL;
798}
799
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800800int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800801 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800802 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
803 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800804 }
805 return -EINVAL;
806}
807
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800808int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
809 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800810 std::string&& target, BindKind kind,
811 std::unique_lock<std::mutex>& mainLock) {
812 if (!isValidMountTarget(target)) {
813 return -EINVAL;
814 }
815
816 std::string mdFileName;
817 if (kind != BindKind::Temporary) {
818 metadata::BindPoint bp;
819 bp.set_storage_id(storage);
820 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800821 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800822 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800823 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800824 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800825 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800826 auto node =
827 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
828 0444, idFromMetadata(metadata),
829 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
830 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800831 return int(node);
832 }
833 }
834
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800835 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800836 std::move(target), kind, mainLock);
837}
838
839int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800840 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800841 std::string&& target, BindKind kind,
842 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800843 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800844 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800845 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800846 if (!status.isOk()) {
847 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
848 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
849 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
850 : status.serviceSpecificErrorCode() == 0
851 ? -EFAULT
852 : status.serviceSpecificErrorCode()
853 : -EIO;
854 }
855 }
856
857 if (!mainLock.owns_lock()) {
858 mainLock.lock();
859 }
860 std::lock_guard l(ifs.lock);
861 const auto [it, _] =
862 ifs.bindPoints.insert_or_assign(target,
863 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800864 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800865 mBindsByPath[std::move(target)] = it;
866 return 0;
867}
868
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800869RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800870 const auto ifs = getIfs(storage);
871 if (!ifs) {
872 return {};
873 }
874 return mIncFs->getMetadata(ifs->control, node);
875}
876
877std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
878 const auto ifs = getIfs(storage);
879 if (!ifs) {
880 return {};
881 }
882
883 std::unique_lock l(ifs->lock);
884 auto subdirIt = ifs->storages.find(storage);
885 if (subdirIt == ifs->storages.end()) {
886 return {};
887 }
888 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
889 l.unlock();
890
891 const auto prefixSize = dir.size() + 1;
892 std::vector<std::string> todoDirs{std::move(dir)};
893 std::vector<std::string> result;
894 do {
895 auto currDir = std::move(todoDirs.back());
896 todoDirs.pop_back();
897
898 auto d =
899 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
900 while (auto e = ::readdir(d.get())) {
901 if (e->d_type == DT_REG) {
902 result.emplace_back(
903 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
904 continue;
905 }
906 if (e->d_type == DT_DIR) {
907 if (e->d_name == "."sv || e->d_name == ".."sv) {
908 continue;
909 }
910 todoDirs.emplace_back(path::join(currDir, e->d_name));
911 continue;
912 }
913 }
914 } while (!todoDirs.empty());
915 return result;
916}
917
918bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700919 {
920 std::unique_lock l(mLock);
921 const auto& ifs = getIfsLocked(storage);
922 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800923 return false;
924 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700925 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
926 ifs->dataLoaderStartRequested = true;
927 return true;
928 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800929 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700930 return startDataLoader(storage);
931}
932
933bool IncrementalService::startDataLoader(MountId mountId) const {
Songchun Fan68645c42020-02-27 15:57:35 -0800934 sp<IDataLoader> dataloader;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700935 auto status = mDataLoaderManager->getDataLoader(mountId, &dataloader);
Songchun Fan3c82a302019-11-29 14:23:45 -0800936 if (!status.isOk()) {
937 return false;
938 }
Songchun Fan68645c42020-02-27 15:57:35 -0800939 if (!dataloader) {
940 return false;
941 }
Alex Buynytskyyb6e02f72020-03-17 18:12:23 -0700942 status = dataloader->start(mountId);
Songchun Fan68645c42020-02-27 15:57:35 -0800943 if (!status.isOk()) {
944 return false;
945 }
946 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -0800947}
948
949void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -0800950 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
951 const auto path = entry.path().u8string();
952 const auto name = entry.path().filename().u8string();
953 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800954 continue;
955 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800956 const auto root = path::join(mIncrementalDir, name);
957 if (!mountExistingImage(root, name)) {
958 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800959 }
960 }
961}
962
963bool IncrementalService::mountExistingImage(std::string_view root, std::string_view key) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800964 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800965 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -0800966
967 IncFsMount::Control control;
968 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800969 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800970 if (!status.isOk()) {
971 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
972 return false;
973 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800974 control.cmd = controlParcel.cmd.release().release();
975 control.pendingReads = controlParcel.pendingReads.release().release();
976 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800977
978 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
979
980 auto m = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
981 path::join(mountTarget, constants().infoMdName));
982 if (!m.has_loader() || !m.has_storage()) {
983 LOG(ERROR) << "Bad mount metadata in mount at " << root;
984 return false;
985 }
986
987 ifs->mountId = m.storage().id();
988 mNextId = std::max(mNextId, ifs->mountId + 1);
989
990 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800991 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -0800992 while (auto e = ::readdir(d.get())) {
993 if (e->d_type == DT_REG) {
994 auto name = std::string_view(e->d_name);
995 if (name.starts_with(constants().mountpointMdPrefix)) {
996 bindPoints.emplace_back(name,
997 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
998 ifs->control,
999 path::join(mountTarget,
1000 name)));
1001 if (bindPoints.back().second.dest_path().empty() ||
1002 bindPoints.back().second.source_subdir().empty()) {
1003 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001004 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001005 }
1006 }
1007 } else if (e->d_type == DT_DIR) {
1008 if (e->d_name == "."sv || e->d_name == ".."sv) {
1009 continue;
1010 }
1011 auto name = std::string_view(e->d_name);
1012 if (name.starts_with(constants().storagePrefix)) {
1013 auto md = parseFromIncfs<metadata::Storage>(mIncFs.get(), ifs->control,
1014 path::join(mountTarget, name));
1015 auto [_, inserted] = mMounts.try_emplace(md.id(), ifs);
1016 if (!inserted) {
1017 LOG(WARNING) << "Ignoring storage with duplicate id " << md.id()
1018 << " for mount " << root;
1019 continue;
1020 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001021 ifs->storages.insert_or_assign(md.id(), IncFsMount::Storage{std::string(name)});
Songchun Fan3c82a302019-11-29 14:23:45 -08001022 mNextId = std::max(mNextId, md.id() + 1);
1023 }
1024 }
1025 }
1026
1027 if (ifs->storages.empty()) {
1028 LOG(WARNING) << "No valid storages in mount " << root;
1029 return false;
1030 }
1031
1032 int bindCount = 0;
1033 for (auto&& bp : bindPoints) {
1034 std::unique_lock l(mLock, std::defer_lock);
1035 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1036 std::move(*bp.second.mutable_source_subdir()),
1037 std::move(*bp.second.mutable_dest_path()),
1038 BindKind::Permanent, l);
1039 }
1040
1041 if (bindCount == 0) {
1042 LOG(WARNING) << "No valid bind points for mount " << root;
1043 deleteStorage(*ifs);
1044 return false;
1045 }
1046
Songchun Fan3c82a302019-11-29 14:23:45 -08001047 mMounts[ifs->mountId] = std::move(ifs);
1048 return true;
1049}
1050
1051bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001052 DataLoaderParamsParcel* params,
1053 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001054 if (!mSystemReady.load(std::memory_order_relaxed)) {
1055 std::unique_lock l(ifs.lock);
1056 if (params) {
1057 if (ifs.savedDataLoaderParams) {
1058 LOG(WARNING) << "Trying to pass second set of data loader parameters, ignored it";
1059 } else {
1060 ifs.savedDataLoaderParams = std::move(*params);
1061 }
1062 } else {
1063 if (!ifs.savedDataLoaderParams) {
1064 LOG(ERROR) << "Mount " << ifs.mountId
1065 << " is broken: no data loader params (system is not ready yet)";
1066 return false;
1067 }
1068 }
1069 return true; // eventually...
1070 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001071
1072 std::unique_lock l(ifs.lock);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001073 if (ifs.dataLoaderStatus != -1) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001074 LOG(INFO) << "Skipped data loader preparation because it already exists";
1075 return true;
1076 }
1077
1078 auto* dlp = params ? params
1079 : ifs.savedDataLoaderParams ? &ifs.savedDataLoaderParams.value() : nullptr;
1080 if (!dlp) {
1081 LOG(ERROR) << "Mount " << ifs.mountId << " is broken: no data loader params";
1082 return false;
1083 }
1084 FileSystemControlParcel fsControlParcel;
Jooyung Hanaa7d5dd2020-03-12 07:03:46 +00001085 fsControlParcel.incremental = IncrementalFileSystemControlParcel();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001086 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd)));
1087 fsControlParcel.incremental->pendingReads.reset(
1088 base::unique_fd(::dup(ifs.control.pendingReads)));
1089 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs)));
Songchun Fan1124fd32020-02-10 12:49:41 -08001090 sp<IncrementalDataLoaderListener> listener =
Songchun Fan306b7df2020-03-17 12:37:07 -07001091 new IncrementalDataLoaderListener(*this,
1092 externalListener ? *externalListener
1093 : DataLoaderStatusListener());
Songchun Fan3c82a302019-11-29 14:23:45 -08001094 bool created = false;
Songchun Fan68645c42020-02-27 15:57:35 -08001095 auto status = mDataLoaderManager->initializeDataLoader(ifs.mountId, *dlp, fsControlParcel,
1096 listener, &created);
Songchun Fan3c82a302019-11-29 14:23:45 -08001097 if (!status.isOk() || !created) {
1098 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
1099 return false;
1100 }
1101 ifs.savedDataLoaderParams.reset();
1102 return true;
1103}
1104
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001105// Extract lib filse from zip, create new files in incfs and write data to them
1106bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1107 std::string_view libDirRelativePath,
1108 std::string_view abi) {
1109 const auto ifs = getIfs(storage);
1110 // First prepare target directories if they don't exist yet
1111 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1112 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1113 << " errno: " << res;
1114 return false;
1115 }
1116
1117 std::unique_ptr<ZipFileRO> zipFile(ZipFileRO::open(apkFullPath.data()));
1118 if (!zipFile) {
1119 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1120 return false;
1121 }
1122 void* cookie = nullptr;
1123 const auto libFilePrefix = path::join(constants().libDir, abi);
1124 if (!zipFile.get()->startIteration(&cookie, libFilePrefix.c_str() /* prefix */,
1125 constants().libSuffix.data() /* suffix */)) {
1126 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1127 return false;
1128 }
1129 ZipEntryRO entry = nullptr;
1130 bool success = true;
1131 while ((entry = zipFile.get()->nextEntry(cookie)) != nullptr) {
1132 char fileName[PATH_MAX];
1133 if (zipFile.get()->getEntryFileName(entry, fileName, sizeof(fileName))) {
1134 continue;
1135 }
1136 const auto libName = path::basename(fileName);
1137 const auto targetLibPath = path::join(libDirRelativePath, libName);
1138 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1139 // If the extract file already exists, skip
1140 struct stat st;
1141 if (stat(targetLibPathAbsolute.c_str(), &st) == 0) {
1142 LOG(INFO) << "Native lib file already exists: " << targetLibPath
1143 << "; skipping extraction";
1144 continue;
1145 }
1146
1147 uint32_t uncompressedLen;
1148 if (!zipFile.get()->getEntryInfo(entry, nullptr, &uncompressedLen, nullptr, nullptr,
1149 nullptr, nullptr)) {
1150 LOG(ERROR) << "Failed to read native lib entry: " << fileName;
1151 success = false;
1152 break;
1153 }
1154
1155 // Create new lib file without signature info
George Burgess IVdd5275d2020-02-10 11:18:07 -08001156 incfs::NewFileParams libFileParams{};
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001157 libFileParams.size = uncompressedLen;
Alex Buynytskyyf5e605a2020-03-13 13:31:12 -07001158 libFileParams.signature = {};
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001159 // Metadata of the new lib file is its relative path
1160 IncFsSpan libFileMetadata;
1161 libFileMetadata.data = targetLibPath.c_str();
1162 libFileMetadata.size = targetLibPath.size();
1163 libFileParams.metadata = libFileMetadata;
1164 incfs::FileId libFileId = idFromMetadata(targetLibPath);
1165 if (auto res = makeFile(storage, targetLibPath, 0777, libFileId, libFileParams)) {
1166 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
1167 success = false;
1168 // If one lib file fails to be created, abort others as well
1169 break;
1170 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001171 // If it is a zero-byte file, skip data writing
1172 if (uncompressedLen == 0) {
1173 continue;
1174 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001175
1176 // Write extracted data to new file
1177 std::vector<uint8_t> libData(uncompressedLen);
1178 if (!zipFile.get()->uncompressEntry(entry, &libData[0], uncompressedLen)) {
1179 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
1180 success = false;
1181 break;
1182 }
1183 android::base::unique_fd writeFd(mIncFs->openWrite(ifs->control, libFileId));
1184 if (writeFd < 0) {
1185 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1186 success = false;
1187 break;
1188 }
1189 const int numBlocks = uncompressedLen / constants().blockSize + 1;
1190 std::vector<IncFsDataBlock> instructions;
1191 auto remainingData = std::span(libData);
1192 for (int i = 0; i < numBlocks - 1; i++) {
1193 auto inst = IncFsDataBlock{
1194 .fileFd = writeFd,
1195 .pageIndex = static_cast<IncFsBlockIndex>(i),
1196 .compression = INCFS_COMPRESSION_KIND_NONE,
1197 .kind = INCFS_BLOCK_KIND_DATA,
1198 .dataSize = static_cast<uint16_t>(constants().blockSize),
1199 .data = reinterpret_cast<const char*>(remainingData.data()),
1200 };
1201 instructions.push_back(inst);
1202 remainingData = remainingData.subspan(constants().blockSize);
1203 }
1204 // Last block
1205 auto inst = IncFsDataBlock{
1206 .fileFd = writeFd,
1207 .pageIndex = static_cast<IncFsBlockIndex>(numBlocks - 1),
1208 .compression = INCFS_COMPRESSION_KIND_NONE,
1209 .kind = INCFS_BLOCK_KIND_DATA,
1210 .dataSize = static_cast<uint16_t>(remainingData.size()),
1211 .data = reinterpret_cast<const char*>(remainingData.data()),
1212 };
1213 instructions.push_back(inst);
1214 size_t res = mIncFs->writeBlocks(instructions);
1215 if (res != instructions.size()) {
1216 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1217 success = false;
1218 }
1219 instructions.clear();
1220 }
1221 zipFile.get()->endIteration(cookie);
1222 return success;
1223}
1224
Songchun Fan3c82a302019-11-29 14:23:45 -08001225binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1226 int newStatus) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001227 if (externalListener) {
1228 // Give an external listener a chance to act before we destroy something.
1229 externalListener->onStatusChanged(mountId, newStatus);
1230 }
1231
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001232 bool startRequested = false;
1233 {
1234 std::unique_lock l(incrementalService.mLock);
1235 const auto& ifs = incrementalService.getIfsLocked(mountId);
1236 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001237 LOG(WARNING) << "Received data loader status " << int(newStatus)
1238 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001239 return binder::Status::ok();
1240 }
1241 ifs->dataLoaderStatus = newStatus;
1242
1243 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1244 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1245 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1246 return binder::Status::ok();
1247 }
1248
1249 startRequested = ifs->dataLoaderStartRequested;
Songchun Fan3c82a302019-11-29 14:23:45 -08001250 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001251
Songchun Fan3c82a302019-11-29 14:23:45 -08001252 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001253 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001254 if (startRequested) {
1255 incrementalService.startDataLoader(mountId);
1256 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001257 break;
1258 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001259 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001260 break;
1261 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001262 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001263 break;
1264 }
1265 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1266 break;
1267 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001268 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1269 break;
1270 }
1271 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1272 break;
1273 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001274 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1275 // Nothing for now. Rely on externalListener to handle this.
1276 break;
1277 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001278 default: {
1279 LOG(WARNING) << "Unknown data loader status: " << newStatus
1280 << " for mount: " << mountId;
1281 break;
1282 }
1283 }
1284
1285 return binder::Status::ok();
1286}
1287
1288} // namespace android::incremental