blob: 980ae083ad4012d4ed83a27a9caa9a3f05c00348 [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() {
158 incrementalService.mIncrementalManager->destroyDataLoader(mountId);
159 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()),
232 mIncrementalManager(sm.getIncrementalManager()),
233 mIncFs(sm.getIncFs()),
234 mIncrementalDir(rootDir) {
235 if (!mVold) {
236 LOG(FATAL) << "Vold service is unavailable";
237 }
238 if (!mIncrementalManager) {
239 LOG(FATAL) << "IncrementalManager service is unavailable";
240 }
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());
288 dprintf(fd, "\t\t\tdynamicArgs: %d\n", int(params.dynamicArgs.size()));
289 }
290 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
291 for (auto&& [storageId, storage] : mnt.storages) {
292 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
293 }
294
295 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
296 for (auto&& [target, bind] : mnt.bindPoints) {
297 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
298 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
299 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
300 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
301 }
302 }
303
304 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
305 for (auto&& [target, mountPairIt] : mBindsByPath) {
306 const auto& bind = mountPairIt->second;
307 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
308 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
309 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
310 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
311 }
312}
313
Songchun Fan3c82a302019-11-29 14:23:45 -0800314std::optional<std::future<void>> IncrementalService::onSystemReady() {
315 std::promise<void> threadFinished;
316 if (mSystemReady.exchange(true)) {
317 return {};
318 }
319
320 std::vector<IfsMountPtr> mounts;
321 {
322 std::lock_guard l(mLock);
323 mounts.reserve(mMounts.size());
324 for (auto&& [id, ifs] : mMounts) {
325 if (ifs->mountId == id) {
326 mounts.push_back(ifs);
327 }
328 }
329 }
330
331 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800332 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800333 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800334 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
335 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800336 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800337 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800338 }
339 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800340 mPrepareDataLoaders.set_value_at_thread_exit();
341 }).detach();
342 return mPrepareDataLoaders.get_future();
343}
344
345auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
346 for (;;) {
347 if (mNextId == kMaxStorageId) {
348 mNextId = 0;
349 }
350 auto id = ++mNextId;
351 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
352 if (inserted) {
353 return it;
354 }
355 }
356}
357
Songchun Fan1124fd32020-02-10 12:49:41 -0800358StorageId IncrementalService::createStorage(
359 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
360 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800361 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
362 if (!path::isAbsolute(mountPoint)) {
363 LOG(ERROR) << "path is not absolute: " << mountPoint;
364 return kInvalidStorageId;
365 }
366
367 auto mountNorm = path::normalize(mountPoint);
368 {
369 const auto id = findStorageId(mountNorm);
370 if (id != kInvalidStorageId) {
371 if (options & CreateOptions::OpenExisting) {
372 LOG(INFO) << "Opened existing storage " << id;
373 return id;
374 }
375 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
376 return kInvalidStorageId;
377 }
378 }
379
380 if (!(options & CreateOptions::CreateNew)) {
381 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
382 return kInvalidStorageId;
383 }
384
385 if (!path::isEmptyDir(mountNorm)) {
386 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
387 return kInvalidStorageId;
388 }
389 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
390 if (mountRoot.empty()) {
391 LOG(ERROR) << "Bad mount point";
392 return kInvalidStorageId;
393 }
394 // Make sure the code removes all crap it may create while still failing.
395 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
396 auto firstCleanupOnFailure =
397 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
398
399 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800400 const auto backing = path::join(mountRoot, constants().backing);
401 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800402 return kInvalidStorageId;
403 }
404
Songchun Fan3c82a302019-11-29 14:23:45 -0800405 IncFsMount::Control control;
406 {
407 std::lock_guard l(mMountOperationLock);
408 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800409
410 if (auto err = rmDirContent(backing.c_str())) {
411 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
412 return kInvalidStorageId;
413 }
414 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
415 return kInvalidStorageId;
416 }
417 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800418 if (!status.isOk()) {
419 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
420 return kInvalidStorageId;
421 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800422 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
423 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800424 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
425 return kInvalidStorageId;
426 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800427 control.cmd = controlParcel.cmd.release().release();
428 control.pendingReads = controlParcel.pendingReads.release().release();
429 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800430 }
431
432 std::unique_lock l(mLock);
433 const auto mountIt = getStorageSlotLocked();
434 const auto mountId = mountIt->first;
435 l.unlock();
436
437 auto ifs =
438 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
439 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
440 // is the removal of the |ifs|.
441 firstCleanupOnFailure.release();
442
443 auto secondCleanup = [this, &l](auto itPtr) {
444 if (!l.owns_lock()) {
445 l.lock();
446 }
447 mMounts.erase(*itPtr);
448 };
449 auto secondCleanupOnFailure =
450 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
451
452 const auto storageIt = ifs->makeStorage(ifs->mountId);
453 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800454 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800455 return kInvalidStorageId;
456 }
457
458 {
459 metadata::Mount m;
460 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800461 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Songchun Fan3c82a302019-11-29 14:23:45 -0800462 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800463 m.mutable_loader()->set_class_name(dataLoaderParams.className);
464 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800465 const auto metadata = m.SerializeAsString();
466 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800467 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800468 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800469 if (auto err =
470 mIncFs->makeFile(ifs->control,
471 path::join(ifs->root, constants().mount,
472 constants().infoMdName),
473 0777, idFromMetadata(metadata),
474 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800475 LOG(ERROR) << "Saving mount metadata failed: " << -err;
476 return kInvalidStorageId;
477 }
478 }
479
480 const auto bk =
481 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800482 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
483 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800484 err < 0) {
485 LOG(ERROR) << "adding bind mount failed: " << -err;
486 return kInvalidStorageId;
487 }
488
489 // Done here as well, all data structures are in good state.
490 secondCleanupOnFailure.release();
491
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800492 if (!prepareDataLoader(*ifs, &dataLoaderParams, &dataLoaderStatusListener)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800493 LOG(ERROR) << "prepareDataLoader() failed";
494 deleteStorageLocked(*ifs, std::move(l));
495 return kInvalidStorageId;
496 }
497
498 mountIt->second = std::move(ifs);
499 l.unlock();
500 LOG(INFO) << "created storage " << mountId;
501 return mountId;
502}
503
504StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
505 StorageId linkedStorage,
506 IncrementalService::CreateOptions options) {
507 if (!isValidMountTarget(mountPoint)) {
508 LOG(ERROR) << "Mount point is invalid or missing";
509 return kInvalidStorageId;
510 }
511
512 std::unique_lock l(mLock);
513 const auto& ifs = getIfsLocked(linkedStorage);
514 if (!ifs) {
515 LOG(ERROR) << "Ifs unavailable";
516 return kInvalidStorageId;
517 }
518
519 const auto mountIt = getStorageSlotLocked();
520 const auto storageId = mountIt->first;
521 const auto storageIt = ifs->makeStorage(storageId);
522 if (storageIt == ifs->storages.end()) {
523 LOG(ERROR) << "Can't create a new storage";
524 mMounts.erase(mountIt);
525 return kInvalidStorageId;
526 }
527
528 l.unlock();
529
530 const auto bk =
531 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800532 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
533 std::string(storageIt->second.name), path::normalize(mountPoint),
534 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800535 err < 0) {
536 LOG(ERROR) << "bindMount failed with error: " << err;
537 return kInvalidStorageId;
538 }
539
540 mountIt->second = ifs;
541 return storageId;
542}
543
544IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
545 std::string_view path) const {
546 auto bindPointIt = mBindsByPath.upper_bound(path);
547 if (bindPointIt == mBindsByPath.begin()) {
548 return mBindsByPath.end();
549 }
550 --bindPointIt;
551 if (!path::startsWith(path, bindPointIt->first)) {
552 return mBindsByPath.end();
553 }
554 return bindPointIt;
555}
556
557StorageId IncrementalService::findStorageId(std::string_view path) const {
558 std::lock_guard l(mLock);
559 auto it = findStorageLocked(path);
560 if (it == mBindsByPath.end()) {
561 return kInvalidStorageId;
562 }
563 return it->second->second.storage;
564}
565
566void IncrementalService::deleteStorage(StorageId storageId) {
567 const auto ifs = getIfs(storageId);
568 if (!ifs) {
569 return;
570 }
571 deleteStorage(*ifs);
572}
573
574void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
575 std::unique_lock l(ifs.lock);
576 deleteStorageLocked(ifs, std::move(l));
577}
578
579void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
580 std::unique_lock<std::mutex>&& ifsLock) {
581 const auto storages = std::move(ifs.storages);
582 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
583 const auto bindPoints = ifs.bindPoints;
584 ifsLock.unlock();
585
586 std::lock_guard l(mLock);
587 for (auto&& [id, _] : storages) {
588 if (id != ifs.mountId) {
589 mMounts.erase(id);
590 }
591 }
592 for (auto&& [path, _] : bindPoints) {
593 mBindsByPath.erase(path);
594 }
595 mMounts.erase(ifs.mountId);
596}
597
598StorageId IncrementalService::openStorage(std::string_view pathInMount) {
599 if (!path::isAbsolute(pathInMount)) {
600 return kInvalidStorageId;
601 }
602
603 return findStorageId(path::normalize(pathInMount));
604}
605
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800606FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800607 const auto ifs = getIfs(storage);
608 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800609 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800610 }
611 std::unique_lock l(ifs->lock);
612 auto storageIt = ifs->storages.find(storage);
613 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800614 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800615 }
616 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800617 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800618 }
619 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
620 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800621 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800622}
623
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800624std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800625 StorageId storage, std::string_view subpath) const {
626 auto name = path::basename(subpath);
627 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800628 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800629 }
630 auto dir = path::dirname(subpath);
631 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800632 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800633 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800634 auto id = nodeFor(storage, dir);
635 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800636}
637
638IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
639 std::lock_guard l(mLock);
640 return getIfsLocked(storage);
641}
642
643const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
644 auto it = mMounts.find(storage);
645 if (it == mMounts.end()) {
646 static const IfsMountPtr kEmpty = {};
647 return kEmpty;
648 }
649 return it->second;
650}
651
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800652int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
653 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800654 if (!isValidMountTarget(target)) {
655 return -EINVAL;
656 }
657
658 const auto ifs = getIfs(storage);
659 if (!ifs) {
660 return -EINVAL;
661 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800662
Songchun Fan3c82a302019-11-29 14:23:45 -0800663 std::unique_lock l(ifs->lock);
664 const auto storageInfo = ifs->storages.find(storage);
665 if (storageInfo == ifs->storages.end()) {
666 return -EINVAL;
667 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800668 std::string normSource = normalizePathToStorage(ifs, storage, source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800669 l.unlock();
670 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800671 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
672 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800673}
674
675int IncrementalService::unbind(StorageId storage, std::string_view target) {
676 if (!path::isAbsolute(target)) {
677 return -EINVAL;
678 }
679
680 LOG(INFO) << "Removing bind point " << target;
681
682 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
683 // otherwise there's a chance to unmount something completely unrelated
684 const auto norm = path::normalize(target);
685 std::unique_lock l(mLock);
686 const auto storageIt = mBindsByPath.find(norm);
687 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
688 return -EINVAL;
689 }
690 const auto bindIt = storageIt->second;
691 const auto storageId = bindIt->second.storage;
692 const auto ifs = getIfsLocked(storageId);
693 if (!ifs) {
694 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
695 << " is missing";
696 return -EFAULT;
697 }
698 mBindsByPath.erase(storageIt);
699 l.unlock();
700
701 mVold->unmountIncFs(bindIt->first);
702 std::unique_lock l2(ifs->lock);
703 if (ifs->bindPoints.size() <= 1) {
704 ifs->bindPoints.clear();
705 deleteStorageLocked(*ifs, std::move(l2));
706 } else {
707 const std::string savedFile = std::move(bindIt->second.savedFilename);
708 ifs->bindPoints.erase(bindIt);
709 l2.unlock();
710 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800711 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800712 }
713 }
714 return 0;
715}
716
Songchun Fan103ba1d2020-02-03 17:32:32 -0800717std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr ifs,
718 StorageId storage, std::string_view path) {
719 const auto storageInfo = ifs->storages.find(storage);
720 if (storageInfo == ifs->storages.end()) {
721 return {};
722 }
723 std::string normPath;
724 if (path::isAbsolute(path)) {
725 normPath = path::normalize(path);
726 } else {
727 normPath = path::normalize(path::join(storageInfo->second.name, path));
728 }
729 if (!path::startsWith(normPath, storageInfo->second.name)) {
730 return {};
731 }
732 return normPath;
733}
734
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800735int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
736 incfs::NewFileParams params) {
737 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800738 std::string normPath = normalizePathToStorage(ifs, storage, path);
739 if (normPath.empty()) {
Songchun Fan54c6aed2020-01-31 16:52:41 -0800740 return -EINVAL;
741 }
742 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800743 if (err) {
744 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800745 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800746 std::vector<uint8_t> metadataBytes;
747 if (params.metadata.data && params.metadata.size > 0) {
748 metadataBytes.assign(params.metadata.data, params.metadata.data + params.metadata.size);
Songchun Fan3c82a302019-11-29 14:23:45 -0800749 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800750 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800751 }
752 return -EINVAL;
753}
754
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800755int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800756 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800757 std::string normPath = normalizePathToStorage(ifs, storageId, path);
758 if (normPath.empty()) {
759 return -EINVAL;
760 }
761 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800762 }
763 return -EINVAL;
764}
765
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800766int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800767 const auto ifs = getIfs(storageId);
768 if (!ifs) {
769 return -EINVAL;
770 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800771 std::string normPath = normalizePathToStorage(ifs, storageId, path);
772 if (normPath.empty()) {
773 return -EINVAL;
774 }
775 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800776 if (err == -EEXIST) {
777 return 0;
778 } else if (err != -ENOENT) {
779 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800780 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800781 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800782 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800783 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800784 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800785}
786
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800787int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
788 StorageId destStorageId, std::string_view newPath) {
789 if (auto ifsSrc = getIfs(sourceStorageId), ifsDest = getIfs(destStorageId);
790 ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800791 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
792 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
793 if (normOldPath.empty() || normNewPath.empty()) {
794 return -EINVAL;
795 }
796 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800797 }
798 return -EINVAL;
799}
800
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800801int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800802 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800803 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
804 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800805 }
806 return -EINVAL;
807}
808
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800809int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
810 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800811 std::string&& target, BindKind kind,
812 std::unique_lock<std::mutex>& mainLock) {
813 if (!isValidMountTarget(target)) {
814 return -EINVAL;
815 }
816
817 std::string mdFileName;
818 if (kind != BindKind::Temporary) {
819 metadata::BindPoint bp;
820 bp.set_storage_id(storage);
821 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800822 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800823 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800824 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800825 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800826 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800827 auto node =
828 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
829 0444, idFromMetadata(metadata),
830 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
831 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800832 return int(node);
833 }
834 }
835
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800836 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800837 std::move(target), kind, mainLock);
838}
839
840int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800841 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800842 std::string&& target, BindKind kind,
843 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800844 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800845 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800846 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800847 if (!status.isOk()) {
848 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
849 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
850 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
851 : status.serviceSpecificErrorCode() == 0
852 ? -EFAULT
853 : status.serviceSpecificErrorCode()
854 : -EIO;
855 }
856 }
857
858 if (!mainLock.owns_lock()) {
859 mainLock.lock();
860 }
861 std::lock_guard l(ifs.lock);
862 const auto [it, _] =
863 ifs.bindPoints.insert_or_assign(target,
864 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800865 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800866 mBindsByPath[std::move(target)] = it;
867 return 0;
868}
869
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800870RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800871 const auto ifs = getIfs(storage);
872 if (!ifs) {
873 return {};
874 }
875 return mIncFs->getMetadata(ifs->control, node);
876}
877
878std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
879 const auto ifs = getIfs(storage);
880 if (!ifs) {
881 return {};
882 }
883
884 std::unique_lock l(ifs->lock);
885 auto subdirIt = ifs->storages.find(storage);
886 if (subdirIt == ifs->storages.end()) {
887 return {};
888 }
889 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
890 l.unlock();
891
892 const auto prefixSize = dir.size() + 1;
893 std::vector<std::string> todoDirs{std::move(dir)};
894 std::vector<std::string> result;
895 do {
896 auto currDir = std::move(todoDirs.back());
897 todoDirs.pop_back();
898
899 auto d =
900 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
901 while (auto e = ::readdir(d.get())) {
902 if (e->d_type == DT_REG) {
903 result.emplace_back(
904 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
905 continue;
906 }
907 if (e->d_type == DT_DIR) {
908 if (e->d_name == "."sv || e->d_name == ".."sv) {
909 continue;
910 }
911 todoDirs.emplace_back(path::join(currDir, e->d_name));
912 continue;
913 }
914 }
915 } while (!todoDirs.empty());
916 return result;
917}
918
919bool IncrementalService::startLoading(StorageId storage) const {
920 const auto ifs = getIfs(storage);
921 if (!ifs) {
922 return false;
923 }
924 bool started = false;
925 std::unique_lock l(ifs->lock);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800926 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800927 if (ifs->dataLoaderReady.wait_for(l, Seconds(5)) == std::cv_status::timeout) {
928 LOG(ERROR) << "Timeout waiting for data loader to be ready";
929 return false;
930 }
931 }
932 auto status = mIncrementalManager->startDataLoader(ifs->mountId, &started);
933 if (!status.isOk()) {
934 return false;
935 }
936 return started;
937}
938
939void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -0800940 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
941 const auto path = entry.path().u8string();
942 const auto name = entry.path().filename().u8string();
943 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800944 continue;
945 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800946 const auto root = path::join(mIncrementalDir, name);
947 if (!mountExistingImage(root, name)) {
948 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800949 }
950 }
951}
952
953bool IncrementalService::mountExistingImage(std::string_view root, std::string_view key) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800954 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800955 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -0800956
957 IncFsMount::Control control;
958 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800959 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800960 if (!status.isOk()) {
961 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
962 return false;
963 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800964 control.cmd = controlParcel.cmd.release().release();
965 control.pendingReads = controlParcel.pendingReads.release().release();
966 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800967
968 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
969
970 auto m = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
971 path::join(mountTarget, constants().infoMdName));
972 if (!m.has_loader() || !m.has_storage()) {
973 LOG(ERROR) << "Bad mount metadata in mount at " << root;
974 return false;
975 }
976
977 ifs->mountId = m.storage().id();
978 mNextId = std::max(mNextId, ifs->mountId + 1);
979
980 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800981 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -0800982 while (auto e = ::readdir(d.get())) {
983 if (e->d_type == DT_REG) {
984 auto name = std::string_view(e->d_name);
985 if (name.starts_with(constants().mountpointMdPrefix)) {
986 bindPoints.emplace_back(name,
987 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
988 ifs->control,
989 path::join(mountTarget,
990 name)));
991 if (bindPoints.back().second.dest_path().empty() ||
992 bindPoints.back().second.source_subdir().empty()) {
993 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800994 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -0800995 }
996 }
997 } else if (e->d_type == DT_DIR) {
998 if (e->d_name == "."sv || e->d_name == ".."sv) {
999 continue;
1000 }
1001 auto name = std::string_view(e->d_name);
1002 if (name.starts_with(constants().storagePrefix)) {
1003 auto md = parseFromIncfs<metadata::Storage>(mIncFs.get(), ifs->control,
1004 path::join(mountTarget, name));
1005 auto [_, inserted] = mMounts.try_emplace(md.id(), ifs);
1006 if (!inserted) {
1007 LOG(WARNING) << "Ignoring storage with duplicate id " << md.id()
1008 << " for mount " << root;
1009 continue;
1010 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001011 ifs->storages.insert_or_assign(md.id(), IncFsMount::Storage{std::string(name)});
Songchun Fan3c82a302019-11-29 14:23:45 -08001012 mNextId = std::max(mNextId, md.id() + 1);
1013 }
1014 }
1015 }
1016
1017 if (ifs->storages.empty()) {
1018 LOG(WARNING) << "No valid storages in mount " << root;
1019 return false;
1020 }
1021
1022 int bindCount = 0;
1023 for (auto&& bp : bindPoints) {
1024 std::unique_lock l(mLock, std::defer_lock);
1025 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1026 std::move(*bp.second.mutable_source_subdir()),
1027 std::move(*bp.second.mutable_dest_path()),
1028 BindKind::Permanent, l);
1029 }
1030
1031 if (bindCount == 0) {
1032 LOG(WARNING) << "No valid bind points for mount " << root;
1033 deleteStorage(*ifs);
1034 return false;
1035 }
1036
Songchun Fan3c82a302019-11-29 14:23:45 -08001037 mMounts[ifs->mountId] = std::move(ifs);
1038 return true;
1039}
1040
1041bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001042 DataLoaderParamsParcel* params,
1043 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001044 if (!mSystemReady.load(std::memory_order_relaxed)) {
1045 std::unique_lock l(ifs.lock);
1046 if (params) {
1047 if (ifs.savedDataLoaderParams) {
1048 LOG(WARNING) << "Trying to pass second set of data loader parameters, ignored it";
1049 } else {
1050 ifs.savedDataLoaderParams = std::move(*params);
1051 }
1052 } else {
1053 if (!ifs.savedDataLoaderParams) {
1054 LOG(ERROR) << "Mount " << ifs.mountId
1055 << " is broken: no data loader params (system is not ready yet)";
1056 return false;
1057 }
1058 }
1059 return true; // eventually...
1060 }
1061 if (base::GetBoolProperty("incremental.skip_loader", false)) {
1062 LOG(INFO) << "Skipped data loader because of incremental.skip_loader property";
1063 std::unique_lock l(ifs.lock);
1064 ifs.savedDataLoaderParams.reset();
1065 return true;
1066 }
1067
1068 std::unique_lock l(ifs.lock);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001069 if (ifs.dataLoaderStatus == IDataLoaderStatusListener::DATA_LOADER_CREATED) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001070 LOG(INFO) << "Skipped data loader preparation because it already exists";
1071 return true;
1072 }
1073
1074 auto* dlp = params ? params
1075 : ifs.savedDataLoaderParams ? &ifs.savedDataLoaderParams.value() : nullptr;
1076 if (!dlp) {
1077 LOG(ERROR) << "Mount " << ifs.mountId << " is broken: no data loader params";
1078 return false;
1079 }
1080 FileSystemControlParcel fsControlParcel;
1081 fsControlParcel.incremental = std::make_unique<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001082 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd)));
1083 fsControlParcel.incremental->pendingReads.reset(
1084 base::unique_fd(::dup(ifs.control.pendingReads)));
1085 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs)));
Songchun Fan1124fd32020-02-10 12:49:41 -08001086 sp<IncrementalDataLoaderListener> listener =
1087 new IncrementalDataLoaderListener(*this, *externalListener);
Songchun Fan3c82a302019-11-29 14:23:45 -08001088 bool created = false;
1089 auto status = mIncrementalManager->prepareDataLoader(ifs.mountId, fsControlParcel, *dlp,
1090 listener, &created);
1091 if (!status.isOk() || !created) {
1092 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
1093 return false;
1094 }
1095 ifs.savedDataLoaderParams.reset();
1096 return true;
1097}
1098
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001099// Extract lib filse from zip, create new files in incfs and write data to them
1100bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1101 std::string_view libDirRelativePath,
1102 std::string_view abi) {
1103 const auto ifs = getIfs(storage);
1104 // First prepare target directories if they don't exist yet
1105 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1106 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1107 << " errno: " << res;
1108 return false;
1109 }
1110
1111 std::unique_ptr<ZipFileRO> zipFile(ZipFileRO::open(apkFullPath.data()));
1112 if (!zipFile) {
1113 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1114 return false;
1115 }
1116 void* cookie = nullptr;
1117 const auto libFilePrefix = path::join(constants().libDir, abi);
1118 if (!zipFile.get()->startIteration(&cookie, libFilePrefix.c_str() /* prefix */,
1119 constants().libSuffix.data() /* suffix */)) {
1120 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1121 return false;
1122 }
1123 ZipEntryRO entry = nullptr;
1124 bool success = true;
1125 while ((entry = zipFile.get()->nextEntry(cookie)) != nullptr) {
1126 char fileName[PATH_MAX];
1127 if (zipFile.get()->getEntryFileName(entry, fileName, sizeof(fileName))) {
1128 continue;
1129 }
1130 const auto libName = path::basename(fileName);
1131 const auto targetLibPath = path::join(libDirRelativePath, libName);
1132 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1133 // If the extract file already exists, skip
1134 struct stat st;
1135 if (stat(targetLibPathAbsolute.c_str(), &st) == 0) {
1136 LOG(INFO) << "Native lib file already exists: " << targetLibPath
1137 << "; skipping extraction";
1138 continue;
1139 }
1140
1141 uint32_t uncompressedLen;
1142 if (!zipFile.get()->getEntryInfo(entry, nullptr, &uncompressedLen, nullptr, nullptr,
1143 nullptr, nullptr)) {
1144 LOG(ERROR) << "Failed to read native lib entry: " << fileName;
1145 success = false;
1146 break;
1147 }
1148
1149 // Create new lib file without signature info
George Burgess IVdd5275d2020-02-10 11:18:07 -08001150 incfs::NewFileParams libFileParams{};
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001151 libFileParams.size = uncompressedLen;
1152 libFileParams.verification.hashAlgorithm = INCFS_HASH_NONE;
1153 // Metadata of the new lib file is its relative path
1154 IncFsSpan libFileMetadata;
1155 libFileMetadata.data = targetLibPath.c_str();
1156 libFileMetadata.size = targetLibPath.size();
1157 libFileParams.metadata = libFileMetadata;
1158 incfs::FileId libFileId = idFromMetadata(targetLibPath);
1159 if (auto res = makeFile(storage, targetLibPath, 0777, libFileId, libFileParams)) {
1160 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
1161 success = false;
1162 // If one lib file fails to be created, abort others as well
1163 break;
1164 }
1165
1166 // Write extracted data to new file
1167 std::vector<uint8_t> libData(uncompressedLen);
1168 if (!zipFile.get()->uncompressEntry(entry, &libData[0], uncompressedLen)) {
1169 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
1170 success = false;
1171 break;
1172 }
1173 android::base::unique_fd writeFd(mIncFs->openWrite(ifs->control, libFileId));
1174 if (writeFd < 0) {
1175 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1176 success = false;
1177 break;
1178 }
1179 const int numBlocks = uncompressedLen / constants().blockSize + 1;
1180 std::vector<IncFsDataBlock> instructions;
1181 auto remainingData = std::span(libData);
1182 for (int i = 0; i < numBlocks - 1; i++) {
1183 auto inst = IncFsDataBlock{
1184 .fileFd = writeFd,
1185 .pageIndex = static_cast<IncFsBlockIndex>(i),
1186 .compression = INCFS_COMPRESSION_KIND_NONE,
1187 .kind = INCFS_BLOCK_KIND_DATA,
1188 .dataSize = static_cast<uint16_t>(constants().blockSize),
1189 .data = reinterpret_cast<const char*>(remainingData.data()),
1190 };
1191 instructions.push_back(inst);
1192 remainingData = remainingData.subspan(constants().blockSize);
1193 }
1194 // Last block
1195 auto inst = IncFsDataBlock{
1196 .fileFd = writeFd,
1197 .pageIndex = static_cast<IncFsBlockIndex>(numBlocks - 1),
1198 .compression = INCFS_COMPRESSION_KIND_NONE,
1199 .kind = INCFS_BLOCK_KIND_DATA,
1200 .dataSize = static_cast<uint16_t>(remainingData.size()),
1201 .data = reinterpret_cast<const char*>(remainingData.data()),
1202 };
1203 instructions.push_back(inst);
1204 size_t res = mIncFs->writeBlocks(instructions);
1205 if (res != instructions.size()) {
1206 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1207 success = false;
1208 }
1209 instructions.clear();
1210 }
1211 zipFile.get()->endIteration(cookie);
1212 return success;
1213}
1214
Songchun Fan3c82a302019-11-29 14:23:45 -08001215binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1216 int newStatus) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001217 if (externalListener) {
1218 // Give an external listener a chance to act before we destroy something.
1219 externalListener->onStatusChanged(mountId, newStatus);
1220 }
1221
Songchun Fan3c82a302019-11-29 14:23:45 -08001222 std::unique_lock l(incrementalService.mLock);
1223 const auto& ifs = incrementalService.getIfsLocked(mountId);
1224 if (!ifs) {
1225 LOG(WARNING) << "Received data loader status " << int(newStatus) << " for unknown mount "
1226 << mountId;
1227 return binder::Status::ok();
1228 }
1229 ifs->dataLoaderStatus = newStatus;
1230 switch (newStatus) {
1231 case IDataLoaderStatusListener::DATA_LOADER_NO_CONNECTION: {
1232 auto now = Clock::now();
1233 if (ifs->connectionLostTime.time_since_epoch().count() == 0) {
1234 ifs->connectionLostTime = now;
1235 break;
1236 }
1237 auto duration =
1238 std::chrono::duration_cast<Seconds>(now - ifs->connectionLostTime).count();
1239 if (duration >= 10) {
1240 incrementalService.mIncrementalManager->showHealthBlockedUI(mountId);
1241 }
1242 break;
1243 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001244 case IDataLoaderStatusListener::DATA_LOADER_CONNECTION_OK: {
1245 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STARTED;
1246 break;
1247 }
1248 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001249 ifs->dataLoaderReady.notify_one();
1250 break;
1251 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001252 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001253 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1254 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1255 break;
1256 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001257 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001258 break;
1259 }
1260 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1261 break;
1262 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001263 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1264 break;
1265 }
1266 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1267 break;
1268 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001269 default: {
1270 LOG(WARNING) << "Unknown data loader status: " << newStatus
1271 << " for mount: " << mountId;
1272 break;
1273 }
1274 }
1275
1276 return binder::Status::ok();
1277}
1278
1279} // namespace android::incremental