blob: cccd0133917724c6657fd2b42f8884fd9dab4162 [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>
Jooyung Han66c567a2020-03-07 21:47:09 +090031#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080032#include <binder/ParcelFileDescriptor.h>
33#include <binder/Status.h>
34#include <sys/stat.h>
35#include <uuid/uuid.h>
36#include <zlib.h>
37
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080038#include <ctime>
Songchun Fan1124fd32020-02-10 12:49:41 -080039#include <filesystem>
Songchun Fan3c82a302019-11-29 14:23:45 -080040#include <iterator>
41#include <span>
42#include <stack>
43#include <thread>
44#include <type_traits>
45
46#include "Metadata.pb.h"
47
48using namespace std::literals;
49using namespace android::content::pm;
Songchun Fan1124fd32020-02-10 12:49:41 -080050namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080051
52namespace android::incremental {
53
54namespace {
55
56using IncrementalFileSystemControlParcel =
57 ::android::os::incremental::IncrementalFileSystemControlParcel;
58
59struct Constants {
60 static constexpr auto backing = "backing_store"sv;
61 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080062 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080063 static constexpr auto storagePrefix = "st"sv;
64 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
65 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080066 static constexpr auto libDir = "lib"sv;
67 static constexpr auto libSuffix = ".so"sv;
68 static constexpr auto blockSize = 4096;
Songchun Fan3c82a302019-11-29 14:23:45 -080069};
70
71static const Constants& constants() {
72 static Constants c;
73 return c;
74}
75
76template <base::LogSeverity level = base::ERROR>
77bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
78 auto cstr = path::c_str(name);
79 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080080 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080081 PLOG(level) << "Can't create directory '" << name << '\'';
82 return false;
83 }
84 struct stat st;
85 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
86 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
87 return false;
88 }
89 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080090 if (::chmod(cstr, mode)) {
91 PLOG(level) << "Changing permission failed for '" << name << '\'';
92 return false;
93 }
94
Songchun Fan3c82a302019-11-29 14:23:45 -080095 return true;
96}
97
98static std::string toMountKey(std::string_view path) {
99 if (path.empty()) {
100 return "@none";
101 }
102 if (path == "/"sv) {
103 return "@root";
104 }
105 if (path::isAbsolute(path)) {
106 path.remove_prefix(1);
107 }
108 std::string res(path);
109 std::replace(res.begin(), res.end(), '/', '_');
110 std::replace(res.begin(), res.end(), '@', '_');
Songchun Fan1124fd32020-02-10 12:49:41 -0800111 return std::string(constants().mountKeyPrefix) + res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800112}
113
114static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
115 std::string_view path) {
116 auto mountKey = toMountKey(path);
117 const auto prefixSize = mountKey.size();
118 for (int counter = 0; counter < 1000;
119 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
120 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800121 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800122 return {mountKey, mountRoot};
123 }
124 }
125 return {};
126}
127
128template <class ProtoMessage, class Control>
129static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
130 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800131 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800132 ProtoMessage message;
133 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
134}
135
136static bool isValidMountTarget(std::string_view path) {
137 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
138}
139
140std::string makeBindMdName() {
141 static constexpr auto uuidStringSize = 36;
142
143 uuid_t guid;
144 uuid_generate(guid);
145
146 std::string name;
147 const auto prefixSize = constants().mountpointMdPrefix.size();
148 name.reserve(prefixSize + uuidStringSize);
149
150 name = constants().mountpointMdPrefix;
151 name.resize(prefixSize + uuidStringSize);
152 uuid_unparse(guid, name.data() + prefixSize);
153
154 return name;
155}
156} // namespace
157
158IncrementalService::IncFsMount::~IncFsMount() {
Songchun Fan68645c42020-02-27 15:57:35 -0800159 incrementalService.mDataLoaderManager->destroyDataLoader(mountId);
Songchun Fan3c82a302019-11-29 14:23:45 -0800160 control.reset();
161 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
162 for (auto&& [target, _] : bindPoints) {
163 LOG(INFO) << "\tbind: " << target;
164 incrementalService.mVold->unmountIncFs(target);
165 }
166 LOG(INFO) << "\troot: " << root;
167 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
168 cleanupFilesystem(root);
169}
170
171auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800172 std::string name;
173 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
174 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
175 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800176 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
177 constants().storagePrefix.data(), id, no);
178 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800179 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800180 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800181 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
182 } else if (err != EEXIST) {
183 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
184 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800185 }
186 }
187 nextStorageDirNo = 0;
188 return storages.end();
189}
190
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800191static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
192 return {::opendir(path), ::closedir};
193}
194
195static int rmDirContent(const char* path) {
196 auto dir = openDir(path);
197 if (!dir) {
198 return -EINVAL;
199 }
200 while (auto entry = ::readdir(dir.get())) {
201 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
202 continue;
203 }
204 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
205 if (entry->d_type == DT_DIR) {
206 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
207 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
208 return err;
209 }
210 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
211 PLOG(WARNING) << "Failed to rmdir " << fullPath;
212 return err;
213 }
214 } else {
215 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
216 PLOG(WARNING) << "Failed to delete " << fullPath;
217 return err;
218 }
219 }
220 }
221 return 0;
222}
223
Songchun Fan3c82a302019-11-29 14:23:45 -0800224void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800225 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800226 ::rmdir(path::join(root, constants().backing).c_str());
227 ::rmdir(path::join(root, constants().mount).c_str());
228 ::rmdir(path::c_str(root));
229}
230
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800231IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800232 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800233 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800234 mIncFs(sm.getIncFs()),
235 mIncrementalDir(rootDir) {
236 if (!mVold) {
237 LOG(FATAL) << "Vold service is unavailable";
238 }
Songchun Fan68645c42020-02-27 15:57:35 -0800239 if (!mDataLoaderManager) {
240 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800241 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800242 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800243}
244
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800245FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800246 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800247}
248
Songchun Fan3c82a302019-11-29 14:23:45 -0800249IncrementalService::~IncrementalService() = default;
250
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800251inline const char* toString(TimePoint t) {
252 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800253 time_t time = SystemClock::to_time_t(
254 SystemClock::now() +
255 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800256 return std::ctime(&time);
257}
258
259inline const char* toString(IncrementalService::BindKind kind) {
260 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800261 case IncrementalService::BindKind::Temporary:
262 return "Temporary";
263 case IncrementalService::BindKind::Permanent:
264 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800265 }
266}
267
268void IncrementalService::onDump(int fd) {
269 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
270 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
271
272 std::unique_lock l(mLock);
273
274 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
275 for (auto&& [id, ifs] : mMounts) {
276 const IncFsMount& mnt = *ifs.get();
277 dprintf(fd, "\t[%d]:\n", id);
278 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
279 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
280 dprintf(fd, "\t\tdataLoaderStatus: %d\n", mnt.dataLoaderStatus.load());
281 dprintf(fd, "\t\tconnectionLostTime: %s\n", toString(mnt.connectionLostTime));
282 if (mnt.savedDataLoaderParams) {
283 const auto& params = mnt.savedDataLoaderParams.value();
284 dprintf(fd, "\t\tsavedDataLoaderParams:\n");
285 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
286 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
287 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
288 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
289 dprintf(fd, "\t\t\tdynamicArgs: %d\n", int(params.dynamicArgs.size()));
290 }
291 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
292 for (auto&& [storageId, storage] : mnt.storages) {
293 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
294 }
295
296 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
297 for (auto&& [target, bind] : mnt.bindPoints) {
298 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
299 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
300 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
301 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
302 }
303 }
304
305 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
306 for (auto&& [target, mountPairIt] : mBindsByPath) {
307 const auto& bind = mountPairIt->second;
308 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
309 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
310 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
311 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
312 }
313}
314
Songchun Fan3c82a302019-11-29 14:23:45 -0800315std::optional<std::future<void>> IncrementalService::onSystemReady() {
316 std::promise<void> threadFinished;
317 if (mSystemReady.exchange(true)) {
318 return {};
319 }
320
321 std::vector<IfsMountPtr> mounts;
322 {
323 std::lock_guard l(mLock);
324 mounts.reserve(mMounts.size());
325 for (auto&& [id, ifs] : mMounts) {
326 if (ifs->mountId == id) {
327 mounts.push_back(ifs);
328 }
329 }
330 }
331
332 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800333 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800334 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800335 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
336 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800337 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800338 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800339 }
340 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800341 mPrepareDataLoaders.set_value_at_thread_exit();
342 }).detach();
343 return mPrepareDataLoaders.get_future();
344}
345
346auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
347 for (;;) {
348 if (mNextId == kMaxStorageId) {
349 mNextId = 0;
350 }
351 auto id = ++mNextId;
352 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
353 if (inserted) {
354 return it;
355 }
356 }
357}
358
Songchun Fan1124fd32020-02-10 12:49:41 -0800359StorageId IncrementalService::createStorage(
360 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
361 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800362 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
363 if (!path::isAbsolute(mountPoint)) {
364 LOG(ERROR) << "path is not absolute: " << mountPoint;
365 return kInvalidStorageId;
366 }
367
368 auto mountNorm = path::normalize(mountPoint);
369 {
370 const auto id = findStorageId(mountNorm);
371 if (id != kInvalidStorageId) {
372 if (options & CreateOptions::OpenExisting) {
373 LOG(INFO) << "Opened existing storage " << id;
374 return id;
375 }
376 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
377 return kInvalidStorageId;
378 }
379 }
380
381 if (!(options & CreateOptions::CreateNew)) {
382 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
383 return kInvalidStorageId;
384 }
385
386 if (!path::isEmptyDir(mountNorm)) {
387 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
388 return kInvalidStorageId;
389 }
390 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
391 if (mountRoot.empty()) {
392 LOG(ERROR) << "Bad mount point";
393 return kInvalidStorageId;
394 }
395 // Make sure the code removes all crap it may create while still failing.
396 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
397 auto firstCleanupOnFailure =
398 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
399
400 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800401 const auto backing = path::join(mountRoot, constants().backing);
402 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800403 return kInvalidStorageId;
404 }
405
Songchun Fan3c82a302019-11-29 14:23:45 -0800406 IncFsMount::Control control;
407 {
408 std::lock_guard l(mMountOperationLock);
409 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800410
411 if (auto err = rmDirContent(backing.c_str())) {
412 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
413 return kInvalidStorageId;
414 }
415 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
416 return kInvalidStorageId;
417 }
418 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800419 if (!status.isOk()) {
420 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
421 return kInvalidStorageId;
422 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800423 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
424 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800425 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
426 return kInvalidStorageId;
427 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800428 control.cmd = controlParcel.cmd.release().release();
429 control.pendingReads = controlParcel.pendingReads.release().release();
430 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800431 }
432
433 std::unique_lock l(mLock);
434 const auto mountIt = getStorageSlotLocked();
435 const auto mountId = mountIt->first;
436 l.unlock();
437
438 auto ifs =
439 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
440 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
441 // is the removal of the |ifs|.
442 firstCleanupOnFailure.release();
443
444 auto secondCleanup = [this, &l](auto itPtr) {
445 if (!l.owns_lock()) {
446 l.lock();
447 }
448 mMounts.erase(*itPtr);
449 };
450 auto secondCleanupOnFailure =
451 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
452
453 const auto storageIt = ifs->makeStorage(ifs->mountId);
454 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800455 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800456 return kInvalidStorageId;
457 }
458
459 {
460 metadata::Mount m;
461 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800462 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Songchun Fan3c82a302019-11-29 14:23:45 -0800463 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800464 m.mutable_loader()->set_class_name(dataLoaderParams.className);
465 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800466 const auto metadata = m.SerializeAsString();
467 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800468 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800469 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800470 if (auto err =
471 mIncFs->makeFile(ifs->control,
472 path::join(ifs->root, constants().mount,
473 constants().infoMdName),
474 0777, idFromMetadata(metadata),
475 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800476 LOG(ERROR) << "Saving mount metadata failed: " << -err;
477 return kInvalidStorageId;
478 }
479 }
480
481 const auto bk =
482 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800483 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
484 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800485 err < 0) {
486 LOG(ERROR) << "adding bind mount failed: " << -err;
487 return kInvalidStorageId;
488 }
489
490 // Done here as well, all data structures are in good state.
491 secondCleanupOnFailure.release();
492
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800493 if (!prepareDataLoader(*ifs, &dataLoaderParams, &dataLoaderStatusListener)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800494 LOG(ERROR) << "prepareDataLoader() failed";
495 deleteStorageLocked(*ifs, std::move(l));
496 return kInvalidStorageId;
497 }
498
499 mountIt->second = std::move(ifs);
500 l.unlock();
501 LOG(INFO) << "created storage " << mountId;
502 return mountId;
503}
504
505StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
506 StorageId linkedStorage,
507 IncrementalService::CreateOptions options) {
508 if (!isValidMountTarget(mountPoint)) {
509 LOG(ERROR) << "Mount point is invalid or missing";
510 return kInvalidStorageId;
511 }
512
513 std::unique_lock l(mLock);
514 const auto& ifs = getIfsLocked(linkedStorage);
515 if (!ifs) {
516 LOG(ERROR) << "Ifs unavailable";
517 return kInvalidStorageId;
518 }
519
520 const auto mountIt = getStorageSlotLocked();
521 const auto storageId = mountIt->first;
522 const auto storageIt = ifs->makeStorage(storageId);
523 if (storageIt == ifs->storages.end()) {
524 LOG(ERROR) << "Can't create a new storage";
525 mMounts.erase(mountIt);
526 return kInvalidStorageId;
527 }
528
529 l.unlock();
530
531 const auto bk =
532 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800533 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
534 std::string(storageIt->second.name), path::normalize(mountPoint),
535 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800536 err < 0) {
537 LOG(ERROR) << "bindMount failed with error: " << err;
538 return kInvalidStorageId;
539 }
540
541 mountIt->second = ifs;
542 return storageId;
543}
544
545IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
546 std::string_view path) const {
547 auto bindPointIt = mBindsByPath.upper_bound(path);
548 if (bindPointIt == mBindsByPath.begin()) {
549 return mBindsByPath.end();
550 }
551 --bindPointIt;
552 if (!path::startsWith(path, bindPointIt->first)) {
553 return mBindsByPath.end();
554 }
555 return bindPointIt;
556}
557
558StorageId IncrementalService::findStorageId(std::string_view path) const {
559 std::lock_guard l(mLock);
560 auto it = findStorageLocked(path);
561 if (it == mBindsByPath.end()) {
562 return kInvalidStorageId;
563 }
564 return it->second->second.storage;
565}
566
567void IncrementalService::deleteStorage(StorageId storageId) {
568 const auto ifs = getIfs(storageId);
569 if (!ifs) {
570 return;
571 }
572 deleteStorage(*ifs);
573}
574
575void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
576 std::unique_lock l(ifs.lock);
577 deleteStorageLocked(ifs, std::move(l));
578}
579
580void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
581 std::unique_lock<std::mutex>&& ifsLock) {
582 const auto storages = std::move(ifs.storages);
583 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
584 const auto bindPoints = ifs.bindPoints;
585 ifsLock.unlock();
586
587 std::lock_guard l(mLock);
588 for (auto&& [id, _] : storages) {
589 if (id != ifs.mountId) {
590 mMounts.erase(id);
591 }
592 }
593 for (auto&& [path, _] : bindPoints) {
594 mBindsByPath.erase(path);
595 }
596 mMounts.erase(ifs.mountId);
597}
598
599StorageId IncrementalService::openStorage(std::string_view pathInMount) {
600 if (!path::isAbsolute(pathInMount)) {
601 return kInvalidStorageId;
602 }
603
604 return findStorageId(path::normalize(pathInMount));
605}
606
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800607FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800608 const auto ifs = getIfs(storage);
609 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800610 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800611 }
612 std::unique_lock l(ifs->lock);
613 auto storageIt = ifs->storages.find(storage);
614 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800615 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800616 }
617 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800618 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800619 }
620 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
621 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800622 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800623}
624
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800625std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800626 StorageId storage, std::string_view subpath) const {
627 auto name = path::basename(subpath);
628 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800629 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800630 }
631 auto dir = path::dirname(subpath);
632 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800633 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800634 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800635 auto id = nodeFor(storage, dir);
636 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800637}
638
639IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
640 std::lock_guard l(mLock);
641 return getIfsLocked(storage);
642}
643
644const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
645 auto it = mMounts.find(storage);
646 if (it == mMounts.end()) {
647 static const IfsMountPtr kEmpty = {};
648 return kEmpty;
649 }
650 return it->second;
651}
652
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800653int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
654 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800655 if (!isValidMountTarget(target)) {
656 return -EINVAL;
657 }
658
659 const auto ifs = getIfs(storage);
660 if (!ifs) {
661 return -EINVAL;
662 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800663
Songchun Fan3c82a302019-11-29 14:23:45 -0800664 std::unique_lock l(ifs->lock);
665 const auto storageInfo = ifs->storages.find(storage);
666 if (storageInfo == ifs->storages.end()) {
667 return -EINVAL;
668 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800669 std::string normSource = normalizePathToStorage(ifs, storage, source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800670 l.unlock();
671 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800672 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
673 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800674}
675
676int IncrementalService::unbind(StorageId storage, std::string_view target) {
677 if (!path::isAbsolute(target)) {
678 return -EINVAL;
679 }
680
681 LOG(INFO) << "Removing bind point " << target;
682
683 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
684 // otherwise there's a chance to unmount something completely unrelated
685 const auto norm = path::normalize(target);
686 std::unique_lock l(mLock);
687 const auto storageIt = mBindsByPath.find(norm);
688 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
689 return -EINVAL;
690 }
691 const auto bindIt = storageIt->second;
692 const auto storageId = bindIt->second.storage;
693 const auto ifs = getIfsLocked(storageId);
694 if (!ifs) {
695 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
696 << " is missing";
697 return -EFAULT;
698 }
699 mBindsByPath.erase(storageIt);
700 l.unlock();
701
702 mVold->unmountIncFs(bindIt->first);
703 std::unique_lock l2(ifs->lock);
704 if (ifs->bindPoints.size() <= 1) {
705 ifs->bindPoints.clear();
706 deleteStorageLocked(*ifs, std::move(l2));
707 } else {
708 const std::string savedFile = std::move(bindIt->second.savedFilename);
709 ifs->bindPoints.erase(bindIt);
710 l2.unlock();
711 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800712 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800713 }
714 }
715 return 0;
716}
717
Songchun Fan103ba1d2020-02-03 17:32:32 -0800718std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr ifs,
719 StorageId storage, std::string_view path) {
720 const auto storageInfo = ifs->storages.find(storage);
721 if (storageInfo == ifs->storages.end()) {
722 return {};
723 }
724 std::string normPath;
725 if (path::isAbsolute(path)) {
726 normPath = path::normalize(path);
727 } else {
728 normPath = path::normalize(path::join(storageInfo->second.name, path));
729 }
730 if (!path::startsWith(normPath, storageInfo->second.name)) {
731 return {};
732 }
733 return normPath;
734}
735
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800736int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
737 incfs::NewFileParams params) {
738 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800739 std::string normPath = normalizePathToStorage(ifs, storage, path);
740 if (normPath.empty()) {
Songchun Fan54c6aed2020-01-31 16:52:41 -0800741 return -EINVAL;
742 }
743 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800744 if (err) {
745 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800746 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800747 std::vector<uint8_t> metadataBytes;
748 if (params.metadata.data && params.metadata.size > 0) {
749 metadataBytes.assign(params.metadata.data, params.metadata.data + params.metadata.size);
Songchun Fan3c82a302019-11-29 14:23:45 -0800750 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800751 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800752 }
753 return -EINVAL;
754}
755
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800756int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800757 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800758 std::string normPath = normalizePathToStorage(ifs, storageId, path);
759 if (normPath.empty()) {
760 return -EINVAL;
761 }
762 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800763 }
764 return -EINVAL;
765}
766
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800767int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800768 const auto ifs = getIfs(storageId);
769 if (!ifs) {
770 return -EINVAL;
771 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800772 std::string normPath = normalizePathToStorage(ifs, storageId, path);
773 if (normPath.empty()) {
774 return -EINVAL;
775 }
776 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800777 if (err == -EEXIST) {
778 return 0;
779 } else if (err != -ENOENT) {
780 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800781 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800782 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800783 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800784 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800785 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800786}
787
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800788int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
789 StorageId destStorageId, std::string_view newPath) {
790 if (auto ifsSrc = getIfs(sourceStorageId), ifsDest = getIfs(destStorageId);
791 ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800792 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
793 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
794 if (normOldPath.empty() || normNewPath.empty()) {
795 return -EINVAL;
796 }
797 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800798 }
799 return -EINVAL;
800}
801
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800802int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800803 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800804 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
805 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800806 }
807 return -EINVAL;
808}
809
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800810int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
811 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800812 std::string&& target, BindKind kind,
813 std::unique_lock<std::mutex>& mainLock) {
814 if (!isValidMountTarget(target)) {
815 return -EINVAL;
816 }
817
818 std::string mdFileName;
819 if (kind != BindKind::Temporary) {
820 metadata::BindPoint bp;
821 bp.set_storage_id(storage);
822 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800823 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800824 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800825 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800826 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800827 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800828 auto node =
829 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
830 0444, idFromMetadata(metadata),
831 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
832 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800833 return int(node);
834 }
835 }
836
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800837 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800838 std::move(target), kind, mainLock);
839}
840
841int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800842 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800843 std::string&& target, BindKind kind,
844 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800845 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800846 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800847 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800848 if (!status.isOk()) {
849 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
850 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
851 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
852 : status.serviceSpecificErrorCode() == 0
853 ? -EFAULT
854 : status.serviceSpecificErrorCode()
855 : -EIO;
856 }
857 }
858
859 if (!mainLock.owns_lock()) {
860 mainLock.lock();
861 }
862 std::lock_guard l(ifs.lock);
863 const auto [it, _] =
864 ifs.bindPoints.insert_or_assign(target,
865 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800866 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800867 mBindsByPath[std::move(target)] = it;
868 return 0;
869}
870
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800871RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800872 const auto ifs = getIfs(storage);
873 if (!ifs) {
874 return {};
875 }
876 return mIncFs->getMetadata(ifs->control, node);
877}
878
879std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
880 const auto ifs = getIfs(storage);
881 if (!ifs) {
882 return {};
883 }
884
885 std::unique_lock l(ifs->lock);
886 auto subdirIt = ifs->storages.find(storage);
887 if (subdirIt == ifs->storages.end()) {
888 return {};
889 }
890 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
891 l.unlock();
892
893 const auto prefixSize = dir.size() + 1;
894 std::vector<std::string> todoDirs{std::move(dir)};
895 std::vector<std::string> result;
896 do {
897 auto currDir = std::move(todoDirs.back());
898 todoDirs.pop_back();
899
900 auto d =
901 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
902 while (auto e = ::readdir(d.get())) {
903 if (e->d_type == DT_REG) {
904 result.emplace_back(
905 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
906 continue;
907 }
908 if (e->d_type == DT_DIR) {
909 if (e->d_name == "."sv || e->d_name == ".."sv) {
910 continue;
911 }
912 todoDirs.emplace_back(path::join(currDir, e->d_name));
913 continue;
914 }
915 }
916 } while (!todoDirs.empty());
917 return result;
918}
919
920bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700921 {
922 std::unique_lock l(mLock);
923 const auto& ifs = getIfsLocked(storage);
924 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 return false;
926 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700927 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
928 ifs->dataLoaderStartRequested = true;
929 return true;
930 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800931 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700932 return startDataLoader(storage);
933}
934
935bool IncrementalService::startDataLoader(MountId mountId) const {
Songchun Fan68645c42020-02-27 15:57:35 -0800936 sp<IDataLoader> dataloader;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700937 auto status = mDataLoaderManager->getDataLoader(mountId, &dataloader);
Songchun Fan3c82a302019-11-29 14:23:45 -0800938 if (!status.isOk()) {
939 return false;
940 }
Songchun Fan68645c42020-02-27 15:57:35 -0800941 if (!dataloader) {
942 return false;
943 }
944 status = dataloader->start();
945 if (!status.isOk()) {
946 return false;
947 }
948 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -0800949}
950
951void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -0800952 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
953 const auto path = entry.path().u8string();
954 const auto name = entry.path().filename().u8string();
955 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800956 continue;
957 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800958 const auto root = path::join(mIncrementalDir, name);
959 if (!mountExistingImage(root, name)) {
960 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800961 }
962 }
963}
964
965bool IncrementalService::mountExistingImage(std::string_view root, std::string_view key) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800966 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800967 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -0800968
969 IncFsMount::Control control;
970 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800971 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800972 if (!status.isOk()) {
973 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
974 return false;
975 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800976 control.cmd = controlParcel.cmd.release().release();
977 control.pendingReads = controlParcel.pendingReads.release().release();
978 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800979
980 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
981
982 auto m = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
983 path::join(mountTarget, constants().infoMdName));
984 if (!m.has_loader() || !m.has_storage()) {
985 LOG(ERROR) << "Bad mount metadata in mount at " << root;
986 return false;
987 }
988
989 ifs->mountId = m.storage().id();
990 mNextId = std::max(mNextId, ifs->mountId + 1);
991
992 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800993 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -0800994 while (auto e = ::readdir(d.get())) {
995 if (e->d_type == DT_REG) {
996 auto name = std::string_view(e->d_name);
997 if (name.starts_with(constants().mountpointMdPrefix)) {
998 bindPoints.emplace_back(name,
999 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1000 ifs->control,
1001 path::join(mountTarget,
1002 name)));
1003 if (bindPoints.back().second.dest_path().empty() ||
1004 bindPoints.back().second.source_subdir().empty()) {
1005 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001006 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001007 }
1008 }
1009 } else if (e->d_type == DT_DIR) {
1010 if (e->d_name == "."sv || e->d_name == ".."sv) {
1011 continue;
1012 }
1013 auto name = std::string_view(e->d_name);
1014 if (name.starts_with(constants().storagePrefix)) {
1015 auto md = parseFromIncfs<metadata::Storage>(mIncFs.get(), ifs->control,
1016 path::join(mountTarget, name));
1017 auto [_, inserted] = mMounts.try_emplace(md.id(), ifs);
1018 if (!inserted) {
1019 LOG(WARNING) << "Ignoring storage with duplicate id " << md.id()
1020 << " for mount " << root;
1021 continue;
1022 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001023 ifs->storages.insert_or_assign(md.id(), IncFsMount::Storage{std::string(name)});
Songchun Fan3c82a302019-11-29 14:23:45 -08001024 mNextId = std::max(mNextId, md.id() + 1);
1025 }
1026 }
1027 }
1028
1029 if (ifs->storages.empty()) {
1030 LOG(WARNING) << "No valid storages in mount " << root;
1031 return false;
1032 }
1033
1034 int bindCount = 0;
1035 for (auto&& bp : bindPoints) {
1036 std::unique_lock l(mLock, std::defer_lock);
1037 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1038 std::move(*bp.second.mutable_source_subdir()),
1039 std::move(*bp.second.mutable_dest_path()),
1040 BindKind::Permanent, l);
1041 }
1042
1043 if (bindCount == 0) {
1044 LOG(WARNING) << "No valid bind points for mount " << root;
1045 deleteStorage(*ifs);
1046 return false;
1047 }
1048
Songchun Fan3c82a302019-11-29 14:23:45 -08001049 mMounts[ifs->mountId] = std::move(ifs);
1050 return true;
1051}
1052
1053bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001054 DataLoaderParamsParcel* params,
1055 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001056 if (!mSystemReady.load(std::memory_order_relaxed)) {
1057 std::unique_lock l(ifs.lock);
1058 if (params) {
1059 if (ifs.savedDataLoaderParams) {
1060 LOG(WARNING) << "Trying to pass second set of data loader parameters, ignored it";
1061 } else {
1062 ifs.savedDataLoaderParams = std::move(*params);
1063 }
1064 } else {
1065 if (!ifs.savedDataLoaderParams) {
1066 LOG(ERROR) << "Mount " << ifs.mountId
1067 << " is broken: no data loader params (system is not ready yet)";
1068 return false;
1069 }
1070 }
1071 return true; // eventually...
1072 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001073
1074 std::unique_lock l(ifs.lock);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001075 if (ifs.dataLoaderStatus != -1) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001076 LOG(INFO) << "Skipped data loader preparation because it already exists";
1077 return true;
1078 }
1079
1080 auto* dlp = params ? params
1081 : ifs.savedDataLoaderParams ? &ifs.savedDataLoaderParams.value() : nullptr;
1082 if (!dlp) {
1083 LOG(ERROR) << "Mount " << ifs.mountId << " is broken: no data loader params";
1084 return false;
1085 }
1086 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001087 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001088 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd)));
1089 fsControlParcel.incremental->pendingReads.reset(
1090 base::unique_fd(::dup(ifs.control.pendingReads)));
1091 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs)));
Songchun Fan1124fd32020-02-10 12:49:41 -08001092 sp<IncrementalDataLoaderListener> listener =
1093 new IncrementalDataLoaderListener(*this, *externalListener);
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;
1158 libFileParams.verification.hashAlgorithm = INCFS_HASH_NONE;
1159 // 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 }
1171
1172 // Write extracted data to new file
1173 std::vector<uint8_t> libData(uncompressedLen);
1174 if (!zipFile.get()->uncompressEntry(entry, &libData[0], uncompressedLen)) {
1175 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
1176 success = false;
1177 break;
1178 }
1179 android::base::unique_fd writeFd(mIncFs->openWrite(ifs->control, libFileId));
1180 if (writeFd < 0) {
1181 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1182 success = false;
1183 break;
1184 }
1185 const int numBlocks = uncompressedLen / constants().blockSize + 1;
1186 std::vector<IncFsDataBlock> instructions;
1187 auto remainingData = std::span(libData);
1188 for (int i = 0; i < numBlocks - 1; i++) {
1189 auto inst = IncFsDataBlock{
1190 .fileFd = writeFd,
1191 .pageIndex = static_cast<IncFsBlockIndex>(i),
1192 .compression = INCFS_COMPRESSION_KIND_NONE,
1193 .kind = INCFS_BLOCK_KIND_DATA,
1194 .dataSize = static_cast<uint16_t>(constants().blockSize),
1195 .data = reinterpret_cast<const char*>(remainingData.data()),
1196 };
1197 instructions.push_back(inst);
1198 remainingData = remainingData.subspan(constants().blockSize);
1199 }
1200 // Last block
1201 auto inst = IncFsDataBlock{
1202 .fileFd = writeFd,
1203 .pageIndex = static_cast<IncFsBlockIndex>(numBlocks - 1),
1204 .compression = INCFS_COMPRESSION_KIND_NONE,
1205 .kind = INCFS_BLOCK_KIND_DATA,
1206 .dataSize = static_cast<uint16_t>(remainingData.size()),
1207 .data = reinterpret_cast<const char*>(remainingData.data()),
1208 };
1209 instructions.push_back(inst);
1210 size_t res = mIncFs->writeBlocks(instructions);
1211 if (res != instructions.size()) {
1212 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1213 success = false;
1214 }
1215 instructions.clear();
1216 }
1217 zipFile.get()->endIteration(cookie);
1218 return success;
1219}
1220
Songchun Fan3c82a302019-11-29 14:23:45 -08001221binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1222 int newStatus) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001223 if (externalListener) {
1224 // Give an external listener a chance to act before we destroy something.
1225 externalListener->onStatusChanged(mountId, newStatus);
1226 }
1227
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001228 bool startRequested = false;
1229 {
1230 std::unique_lock l(incrementalService.mLock);
1231 const auto& ifs = incrementalService.getIfsLocked(mountId);
1232 if (!ifs) {
1233 LOG(WARNING) << "Received data loader status " << int(newStatus) << " for unknown mount "
1234 << mountId;
1235 return binder::Status::ok();
1236 }
1237 ifs->dataLoaderStatus = newStatus;
1238
1239 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1240 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1241 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1242 return binder::Status::ok();
1243 }
1244
1245 startRequested = ifs->dataLoaderStartRequested;
Songchun Fan3c82a302019-11-29 14:23:45 -08001246 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001247
Songchun Fan3c82a302019-11-29 14:23:45 -08001248 switch (newStatus) {
1249 case IDataLoaderStatusListener::DATA_LOADER_NO_CONNECTION: {
Songchun Fan68645c42020-02-27 15:57:35 -08001250 // TODO(b/150411019): handle data loader connection loss
Songchun Fan3c82a302019-11-29 14:23:45 -08001251 break;
1252 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001253 case IDataLoaderStatusListener::DATA_LOADER_CONNECTION_OK: {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001254 // TODO(b/150411019): handle data loader connection loss
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001255 break;
1256 }
1257 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001258 if (startRequested) {
1259 incrementalService.startDataLoader(mountId);
1260 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001261 break;
1262 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001263 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001264 break;
1265 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001266 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001267 break;
1268 }
1269 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1270 break;
1271 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001272 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1273 break;
1274 }
1275 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
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