blob: 7349cf673cc4c0531ea5f479a85471ca9efee132 [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
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070038#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080039#include <ctime>
Songchun Fan1124fd32020-02-10 12:49:41 -080040#include <filesystem>
Songchun Fan3c82a302019-11-29 14:23:45 -080041#include <iterator>
42#include <span>
43#include <stack>
44#include <thread>
45#include <type_traits>
46
47#include "Metadata.pb.h"
48
49using namespace std::literals;
50using namespace android::content::pm;
Songchun Fan1124fd32020-02-10 12:49:41 -080051namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080052
53namespace android::incremental {
54
55namespace {
56
57using IncrementalFileSystemControlParcel =
58 ::android::os::incremental::IncrementalFileSystemControlParcel;
59
60struct Constants {
61 static constexpr auto backing = "backing_store"sv;
62 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080063 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080064 static constexpr auto storagePrefix = "st"sv;
65 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
66 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080067 static constexpr auto libDir = "lib"sv;
68 static constexpr auto libSuffix = ".so"sv;
69 static constexpr auto blockSize = 4096;
Songchun Fan3c82a302019-11-29 14:23:45 -080070};
71
72static const Constants& constants() {
73 static Constants c;
74 return c;
75}
76
77template <base::LogSeverity level = base::ERROR>
78bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
79 auto cstr = path::c_str(name);
80 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080081 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080082 PLOG(level) << "Can't create directory '" << name << '\'';
83 return false;
84 }
85 struct stat st;
86 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
87 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
88 return false;
89 }
90 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080091 if (::chmod(cstr, mode)) {
92 PLOG(level) << "Changing permission failed for '" << name << '\'';
93 return false;
94 }
95
Songchun Fan3c82a302019-11-29 14:23:45 -080096 return true;
97}
98
99static std::string toMountKey(std::string_view path) {
100 if (path.empty()) {
101 return "@none";
102 }
103 if (path == "/"sv) {
104 return "@root";
105 }
106 if (path::isAbsolute(path)) {
107 path.remove_prefix(1);
108 }
109 std::string res(path);
110 std::replace(res.begin(), res.end(), '/', '_');
111 std::replace(res.begin(), res.end(), '@', '_');
Songchun Fan1124fd32020-02-10 12:49:41 -0800112 return std::string(constants().mountKeyPrefix) + res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800113}
114
115static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
116 std::string_view path) {
117 auto mountKey = toMountKey(path);
118 const auto prefixSize = mountKey.size();
119 for (int counter = 0; counter < 1000;
120 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
121 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800122 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800123 return {mountKey, mountRoot};
124 }
125 }
126 return {};
127}
128
129template <class ProtoMessage, class Control>
130static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
131 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800132 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800133 ProtoMessage message;
134 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
135}
136
137static bool isValidMountTarget(std::string_view path) {
138 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
139}
140
141std::string makeBindMdName() {
142 static constexpr auto uuidStringSize = 36;
143
144 uuid_t guid;
145 uuid_generate(guid);
146
147 std::string name;
148 const auto prefixSize = constants().mountpointMdPrefix.size();
149 name.reserve(prefixSize + uuidStringSize);
150
151 name = constants().mountpointMdPrefix;
152 name.resize(prefixSize + uuidStringSize);
153 uuid_unparse(guid, name.data() + prefixSize);
154
155 return name;
156}
157} // namespace
158
159IncrementalService::IncFsMount::~IncFsMount() {
Songchun Fan68645c42020-02-27 15:57:35 -0800160 incrementalService.mDataLoaderManager->destroyDataLoader(mountId);
Songchun Fan3c82a302019-11-29 14:23:45 -0800161 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);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700279 dprintf(fd, "\t\troot: %s\n", mnt.root.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800280 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
281 dprintf(fd, "\t\tdataLoaderStatus: %d\n", mnt.dataLoaderStatus.load());
282 dprintf(fd, "\t\tconnectionLostTime: %s\n", toString(mnt.connectionLostTime));
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700283 dprintf(fd, "\t\tsavedDataLoaderParams:\n");
284 if (!mnt.savedDataLoaderParams) {
285 dprintf(fd, "\t\t\tnone\n");
286 } else {
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800287 const auto& params = mnt.savedDataLoaderParams.value();
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800288 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
289 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
290 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
291 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800292 }
293 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
294 for (auto&& [storageId, storage] : mnt.storages) {
295 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
296 }
297
298 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
299 for (auto&& [target, bind] : mnt.bindPoints) {
300 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
301 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
302 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
303 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
304 }
305 }
306
307 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
308 for (auto&& [target, mountPairIt] : mBindsByPath) {
309 const auto& bind = mountPairIt->second;
310 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
311 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
312 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
313 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
314 }
315}
316
Songchun Fan3c82a302019-11-29 14:23:45 -0800317std::optional<std::future<void>> IncrementalService::onSystemReady() {
318 std::promise<void> threadFinished;
319 if (mSystemReady.exchange(true)) {
320 return {};
321 }
322
323 std::vector<IfsMountPtr> mounts;
324 {
325 std::lock_guard l(mLock);
326 mounts.reserve(mMounts.size());
327 for (auto&& [id, ifs] : mMounts) {
328 if (ifs->mountId == id) {
329 mounts.push_back(ifs);
330 }
331 }
332 }
333
334 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800335 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800336 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800337 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
338 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800339 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800340 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800341 }
342 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800343 mPrepareDataLoaders.set_value_at_thread_exit();
344 }).detach();
345 return mPrepareDataLoaders.get_future();
346}
347
348auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
349 for (;;) {
350 if (mNextId == kMaxStorageId) {
351 mNextId = 0;
352 }
353 auto id = ++mNextId;
354 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
355 if (inserted) {
356 return it;
357 }
358 }
359}
360
Songchun Fan1124fd32020-02-10 12:49:41 -0800361StorageId IncrementalService::createStorage(
362 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
363 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800364 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
365 if (!path::isAbsolute(mountPoint)) {
366 LOG(ERROR) << "path is not absolute: " << mountPoint;
367 return kInvalidStorageId;
368 }
369
370 auto mountNorm = path::normalize(mountPoint);
371 {
372 const auto id = findStorageId(mountNorm);
373 if (id != kInvalidStorageId) {
374 if (options & CreateOptions::OpenExisting) {
375 LOG(INFO) << "Opened existing storage " << id;
376 return id;
377 }
378 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
379 return kInvalidStorageId;
380 }
381 }
382
383 if (!(options & CreateOptions::CreateNew)) {
384 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
385 return kInvalidStorageId;
386 }
387
388 if (!path::isEmptyDir(mountNorm)) {
389 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
390 return kInvalidStorageId;
391 }
392 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
393 if (mountRoot.empty()) {
394 LOG(ERROR) << "Bad mount point";
395 return kInvalidStorageId;
396 }
397 // Make sure the code removes all crap it may create while still failing.
398 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
399 auto firstCleanupOnFailure =
400 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
401
402 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800403 const auto backing = path::join(mountRoot, constants().backing);
404 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800405 return kInvalidStorageId;
406 }
407
Songchun Fan3c82a302019-11-29 14:23:45 -0800408 IncFsMount::Control control;
409 {
410 std::lock_guard l(mMountOperationLock);
411 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800412
413 if (auto err = rmDirContent(backing.c_str())) {
414 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
415 return kInvalidStorageId;
416 }
417 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
418 return kInvalidStorageId;
419 }
420 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800421 if (!status.isOk()) {
422 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
423 return kInvalidStorageId;
424 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800425 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
426 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800427 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
428 return kInvalidStorageId;
429 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800430 int cmd = controlParcel.cmd.release().release();
431 int pendingReads = controlParcel.pendingReads.release().release();
432 int logs = controlParcel.log.release().release();
433 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800434 }
435
436 std::unique_lock l(mLock);
437 const auto mountIt = getStorageSlotLocked();
438 const auto mountId = mountIt->first;
439 l.unlock();
440
441 auto ifs =
442 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
443 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
444 // is the removal of the |ifs|.
445 firstCleanupOnFailure.release();
446
447 auto secondCleanup = [this, &l](auto itPtr) {
448 if (!l.owns_lock()) {
449 l.lock();
450 }
451 mMounts.erase(*itPtr);
452 };
453 auto secondCleanupOnFailure =
454 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
455
456 const auto storageIt = ifs->makeStorage(ifs->mountId);
457 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800458 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800459 return kInvalidStorageId;
460 }
461
462 {
463 metadata::Mount m;
464 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800465 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Songchun Fan3c82a302019-11-29 14:23:45 -0800466 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800467 m.mutable_loader()->set_class_name(dataLoaderParams.className);
468 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800469 const auto metadata = m.SerializeAsString();
470 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800471 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800472 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800473 if (auto err =
474 mIncFs->makeFile(ifs->control,
475 path::join(ifs->root, constants().mount,
476 constants().infoMdName),
477 0777, idFromMetadata(metadata),
478 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800479 LOG(ERROR) << "Saving mount metadata failed: " << -err;
480 return kInvalidStorageId;
481 }
482 }
483
484 const auto bk =
485 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800486 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
487 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800488 err < 0) {
489 LOG(ERROR) << "adding bind mount failed: " << -err;
490 return kInvalidStorageId;
491 }
492
493 // Done here as well, all data structures are in good state.
494 secondCleanupOnFailure.release();
495
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800496 if (!prepareDataLoader(*ifs, &dataLoaderParams, &dataLoaderStatusListener)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800497 LOG(ERROR) << "prepareDataLoader() failed";
498 deleteStorageLocked(*ifs, std::move(l));
499 return kInvalidStorageId;
500 }
501
502 mountIt->second = std::move(ifs);
503 l.unlock();
504 LOG(INFO) << "created storage " << mountId;
505 return mountId;
506}
507
508StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
509 StorageId linkedStorage,
510 IncrementalService::CreateOptions options) {
511 if (!isValidMountTarget(mountPoint)) {
512 LOG(ERROR) << "Mount point is invalid or missing";
513 return kInvalidStorageId;
514 }
515
516 std::unique_lock l(mLock);
517 const auto& ifs = getIfsLocked(linkedStorage);
518 if (!ifs) {
519 LOG(ERROR) << "Ifs unavailable";
520 return kInvalidStorageId;
521 }
522
523 const auto mountIt = getStorageSlotLocked();
524 const auto storageId = mountIt->first;
525 const auto storageIt = ifs->makeStorage(storageId);
526 if (storageIt == ifs->storages.end()) {
527 LOG(ERROR) << "Can't create a new storage";
528 mMounts.erase(mountIt);
529 return kInvalidStorageId;
530 }
531
532 l.unlock();
533
534 const auto bk =
535 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800536 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
537 std::string(storageIt->second.name), path::normalize(mountPoint),
538 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800539 err < 0) {
540 LOG(ERROR) << "bindMount failed with error: " << err;
541 return kInvalidStorageId;
542 }
543
544 mountIt->second = ifs;
545 return storageId;
546}
547
548IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
549 std::string_view path) const {
550 auto bindPointIt = mBindsByPath.upper_bound(path);
551 if (bindPointIt == mBindsByPath.begin()) {
552 return mBindsByPath.end();
553 }
554 --bindPointIt;
555 if (!path::startsWith(path, bindPointIt->first)) {
556 return mBindsByPath.end();
557 }
558 return bindPointIt;
559}
560
561StorageId IncrementalService::findStorageId(std::string_view path) const {
562 std::lock_guard l(mLock);
563 auto it = findStorageLocked(path);
564 if (it == mBindsByPath.end()) {
565 return kInvalidStorageId;
566 }
567 return it->second->second.storage;
568}
569
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700570int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
571 const auto ifs = getIfs(storageId);
572 if (!ifs) {
573 return -EINVAL;
574 }
575
576 using unique_fd = ::android::base::unique_fd;
577 ::android::os::incremental::IncrementalFileSystemControlParcel control;
578 control.cmd.reset(unique_fd(dup(ifs->control.cmd())));
579 control.pendingReads.reset(unique_fd(dup(ifs->control.pendingReads())));
580 auto logsFd = ifs->control.logs();
581 if (logsFd >= 0) {
582 control.log.reset(unique_fd(dup(logsFd)));
583 }
584
585 std::lock_guard l(mMountOperationLock);
586 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
587 if (!status.isOk()) {
588 LOG(ERROR) << "Calling Vold::setIncFsMountOptions() failed: " << status.toString8();
589 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
590 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
591 : status.serviceSpecificErrorCode() == 0
592 ? -EFAULT
593 : status.serviceSpecificErrorCode()
594 : -EIO;
595 }
596
597 return 0;
598}
599
Songchun Fan3c82a302019-11-29 14:23:45 -0800600void IncrementalService::deleteStorage(StorageId storageId) {
601 const auto ifs = getIfs(storageId);
602 if (!ifs) {
603 return;
604 }
605 deleteStorage(*ifs);
606}
607
608void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
609 std::unique_lock l(ifs.lock);
610 deleteStorageLocked(ifs, std::move(l));
611}
612
613void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
614 std::unique_lock<std::mutex>&& ifsLock) {
615 const auto storages = std::move(ifs.storages);
616 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
617 const auto bindPoints = ifs.bindPoints;
618 ifsLock.unlock();
619
620 std::lock_guard l(mLock);
621 for (auto&& [id, _] : storages) {
622 if (id != ifs.mountId) {
623 mMounts.erase(id);
624 }
625 }
626 for (auto&& [path, _] : bindPoints) {
627 mBindsByPath.erase(path);
628 }
629 mMounts.erase(ifs.mountId);
630}
631
632StorageId IncrementalService::openStorage(std::string_view pathInMount) {
633 if (!path::isAbsolute(pathInMount)) {
634 return kInvalidStorageId;
635 }
636
637 return findStorageId(path::normalize(pathInMount));
638}
639
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800640FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800641 const auto ifs = getIfs(storage);
642 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800643 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800644 }
645 std::unique_lock l(ifs->lock);
646 auto storageIt = ifs->storages.find(storage);
647 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800648 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800649 }
650 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800651 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800652 }
653 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
654 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800655 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800656}
657
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800658std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800659 StorageId storage, std::string_view subpath) const {
660 auto name = path::basename(subpath);
661 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800662 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800663 }
664 auto dir = path::dirname(subpath);
665 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800666 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800667 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800668 auto id = nodeFor(storage, dir);
669 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800670}
671
672IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
673 std::lock_guard l(mLock);
674 return getIfsLocked(storage);
675}
676
677const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
678 auto it = mMounts.find(storage);
679 if (it == mMounts.end()) {
680 static const IfsMountPtr kEmpty = {};
681 return kEmpty;
682 }
683 return it->second;
684}
685
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800686int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
687 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800688 if (!isValidMountTarget(target)) {
689 return -EINVAL;
690 }
691
692 const auto ifs = getIfs(storage);
693 if (!ifs) {
694 return -EINVAL;
695 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800696
Songchun Fan3c82a302019-11-29 14:23:45 -0800697 std::unique_lock l(ifs->lock);
698 const auto storageInfo = ifs->storages.find(storage);
699 if (storageInfo == ifs->storages.end()) {
700 return -EINVAL;
701 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800702 std::string normSource = normalizePathToStorage(ifs, storage, source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800703 l.unlock();
704 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800705 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
706 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800707}
708
709int IncrementalService::unbind(StorageId storage, std::string_view target) {
710 if (!path::isAbsolute(target)) {
711 return -EINVAL;
712 }
713
714 LOG(INFO) << "Removing bind point " << target;
715
716 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
717 // otherwise there's a chance to unmount something completely unrelated
718 const auto norm = path::normalize(target);
719 std::unique_lock l(mLock);
720 const auto storageIt = mBindsByPath.find(norm);
721 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
722 return -EINVAL;
723 }
724 const auto bindIt = storageIt->second;
725 const auto storageId = bindIt->second.storage;
726 const auto ifs = getIfsLocked(storageId);
727 if (!ifs) {
728 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
729 << " is missing";
730 return -EFAULT;
731 }
732 mBindsByPath.erase(storageIt);
733 l.unlock();
734
735 mVold->unmountIncFs(bindIt->first);
736 std::unique_lock l2(ifs->lock);
737 if (ifs->bindPoints.size() <= 1) {
738 ifs->bindPoints.clear();
739 deleteStorageLocked(*ifs, std::move(l2));
740 } else {
741 const std::string savedFile = std::move(bindIt->second.savedFilename);
742 ifs->bindPoints.erase(bindIt);
743 l2.unlock();
744 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800745 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800746 }
747 }
748 return 0;
749}
750
Songchun Fan103ba1d2020-02-03 17:32:32 -0800751std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr ifs,
752 StorageId storage, std::string_view path) {
753 const auto storageInfo = ifs->storages.find(storage);
754 if (storageInfo == ifs->storages.end()) {
755 return {};
756 }
757 std::string normPath;
758 if (path::isAbsolute(path)) {
759 normPath = path::normalize(path);
760 } else {
761 normPath = path::normalize(path::join(storageInfo->second.name, path));
762 }
763 if (!path::startsWith(normPath, storageInfo->second.name)) {
764 return {};
765 }
766 return normPath;
767}
768
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800769int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
770 incfs::NewFileParams params) {
771 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800772 std::string normPath = normalizePathToStorage(ifs, storage, path);
773 if (normPath.empty()) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700774 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800775 return -EINVAL;
776 }
777 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800778 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700779 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800780 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800781 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800782 std::vector<uint8_t> metadataBytes;
783 if (params.metadata.data && params.metadata.size > 0) {
784 metadataBytes.assign(params.metadata.data, params.metadata.data + params.metadata.size);
Songchun Fan3c82a302019-11-29 14:23:45 -0800785 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800786 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800787 }
788 return -EINVAL;
789}
790
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800791int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800792 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800793 std::string normPath = normalizePathToStorage(ifs, storageId, path);
794 if (normPath.empty()) {
795 return -EINVAL;
796 }
797 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800798 }
799 return -EINVAL;
800}
801
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800802int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800803 const auto ifs = getIfs(storageId);
804 if (!ifs) {
805 return -EINVAL;
806 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800807 std::string normPath = normalizePathToStorage(ifs, storageId, path);
808 if (normPath.empty()) {
809 return -EINVAL;
810 }
811 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800812 if (err == -EEXIST) {
813 return 0;
814 } else if (err != -ENOENT) {
815 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800816 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800817 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800818 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800819 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800820 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800821}
822
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800823int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
824 StorageId destStorageId, std::string_view newPath) {
825 if (auto ifsSrc = getIfs(sourceStorageId), ifsDest = getIfs(destStorageId);
826 ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800827 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
828 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
829 if (normOldPath.empty() || normNewPath.empty()) {
830 return -EINVAL;
831 }
832 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800833 }
834 return -EINVAL;
835}
836
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800837int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800838 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800839 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
840 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800841 }
842 return -EINVAL;
843}
844
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800845int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
846 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800847 std::string&& target, BindKind kind,
848 std::unique_lock<std::mutex>& mainLock) {
849 if (!isValidMountTarget(target)) {
850 return -EINVAL;
851 }
852
853 std::string mdFileName;
854 if (kind != BindKind::Temporary) {
855 metadata::BindPoint bp;
856 bp.set_storage_id(storage);
857 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800858 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800859 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800860 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800861 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800862 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800863 auto node =
864 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
865 0444, idFromMetadata(metadata),
866 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
867 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800868 return int(node);
869 }
870 }
871
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800872 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800873 std::move(target), kind, mainLock);
874}
875
876int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800877 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800878 std::string&& target, BindKind kind,
879 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800880 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800881 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800882 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800883 if (!status.isOk()) {
884 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
885 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
886 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
887 : status.serviceSpecificErrorCode() == 0
888 ? -EFAULT
889 : status.serviceSpecificErrorCode()
890 : -EIO;
891 }
892 }
893
894 if (!mainLock.owns_lock()) {
895 mainLock.lock();
896 }
897 std::lock_guard l(ifs.lock);
898 const auto [it, _] =
899 ifs.bindPoints.insert_or_assign(target,
900 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800901 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800902 mBindsByPath[std::move(target)] = it;
903 return 0;
904}
905
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800906RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800907 const auto ifs = getIfs(storage);
908 if (!ifs) {
909 return {};
910 }
911 return mIncFs->getMetadata(ifs->control, node);
912}
913
914std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
915 const auto ifs = getIfs(storage);
916 if (!ifs) {
917 return {};
918 }
919
920 std::unique_lock l(ifs->lock);
921 auto subdirIt = ifs->storages.find(storage);
922 if (subdirIt == ifs->storages.end()) {
923 return {};
924 }
925 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
926 l.unlock();
927
928 const auto prefixSize = dir.size() + 1;
929 std::vector<std::string> todoDirs{std::move(dir)};
930 std::vector<std::string> result;
931 do {
932 auto currDir = std::move(todoDirs.back());
933 todoDirs.pop_back();
934
935 auto d =
936 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
937 while (auto e = ::readdir(d.get())) {
938 if (e->d_type == DT_REG) {
939 result.emplace_back(
940 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
941 continue;
942 }
943 if (e->d_type == DT_DIR) {
944 if (e->d_name == "."sv || e->d_name == ".."sv) {
945 continue;
946 }
947 todoDirs.emplace_back(path::join(currDir, e->d_name));
948 continue;
949 }
950 }
951 } while (!todoDirs.empty());
952 return result;
953}
954
955bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700956 {
957 std::unique_lock l(mLock);
958 const auto& ifs = getIfsLocked(storage);
959 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800960 return false;
961 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700962 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
963 ifs->dataLoaderStartRequested = true;
964 return true;
965 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800966 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700967 return startDataLoader(storage);
968}
969
970bool IncrementalService::startDataLoader(MountId mountId) const {
Songchun Fan68645c42020-02-27 15:57:35 -0800971 sp<IDataLoader> dataloader;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700972 auto status = mDataLoaderManager->getDataLoader(mountId, &dataloader);
Songchun Fan3c82a302019-11-29 14:23:45 -0800973 if (!status.isOk()) {
974 return false;
975 }
Songchun Fan68645c42020-02-27 15:57:35 -0800976 if (!dataloader) {
977 return false;
978 }
Alex Buynytskyyb6e02f72020-03-17 18:12:23 -0700979 status = dataloader->start(mountId);
Songchun Fan68645c42020-02-27 15:57:35 -0800980 if (!status.isOk()) {
981 return false;
982 }
983 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -0800984}
985
986void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -0800987 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
988 const auto path = entry.path().u8string();
989 const auto name = entry.path().filename().u8string();
990 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800991 continue;
992 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800993 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700994 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -0800995 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800996 }
997 }
998}
999
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001000bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001001 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001002 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001003
Songchun Fan3c82a302019-11-29 14:23:45 -08001004 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001005 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001006 if (!status.isOk()) {
1007 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1008 return false;
1009 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001010
1011 int cmd = controlParcel.cmd.release().release();
1012 int pendingReads = controlParcel.pendingReads.release().release();
1013 int logs = controlParcel.log.release().release();
1014 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001015
1016 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1017
1018 auto m = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1019 path::join(mountTarget, constants().infoMdName));
1020 if (!m.has_loader() || !m.has_storage()) {
1021 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1022 return false;
1023 }
1024
1025 ifs->mountId = m.storage().id();
1026 mNextId = std::max(mNextId, ifs->mountId + 1);
1027
1028 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001029 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001030 while (auto e = ::readdir(d.get())) {
1031 if (e->d_type == DT_REG) {
1032 auto name = std::string_view(e->d_name);
1033 if (name.starts_with(constants().mountpointMdPrefix)) {
1034 bindPoints.emplace_back(name,
1035 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1036 ifs->control,
1037 path::join(mountTarget,
1038 name)));
1039 if (bindPoints.back().second.dest_path().empty() ||
1040 bindPoints.back().second.source_subdir().empty()) {
1041 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001042 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001043 }
1044 }
1045 } else if (e->d_type == DT_DIR) {
1046 if (e->d_name == "."sv || e->d_name == ".."sv) {
1047 continue;
1048 }
1049 auto name = std::string_view(e->d_name);
1050 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001051 int storageId;
1052 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1053 name.data() + name.size(), storageId);
1054 if (res.ec != std::errc{} || *res.ptr != '_') {
1055 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1056 << root;
1057 continue;
1058 }
1059 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001060 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001061 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 << " for mount " << root;
1063 continue;
1064 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001065 ifs->storages.insert_or_assign(storageId,
1066 IncFsMount::Storage{
1067 path::join(root, constants().mount, name)});
1068 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001069 }
1070 }
1071 }
1072
1073 if (ifs->storages.empty()) {
1074 LOG(WARNING) << "No valid storages in mount " << root;
1075 return false;
1076 }
1077
1078 int bindCount = 0;
1079 for (auto&& bp : bindPoints) {
1080 std::unique_lock l(mLock, std::defer_lock);
1081 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1082 std::move(*bp.second.mutable_source_subdir()),
1083 std::move(*bp.second.mutable_dest_path()),
1084 BindKind::Permanent, l);
1085 }
1086
1087 if (bindCount == 0) {
1088 LOG(WARNING) << "No valid bind points for mount " << root;
1089 deleteStorage(*ifs);
1090 return false;
1091 }
1092
Songchun Fan3c82a302019-11-29 14:23:45 -08001093 mMounts[ifs->mountId] = std::move(ifs);
1094 return true;
1095}
1096
1097bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001098 DataLoaderParamsParcel* params,
1099 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001100 if (!mSystemReady.load(std::memory_order_relaxed)) {
1101 std::unique_lock l(ifs.lock);
1102 if (params) {
1103 if (ifs.savedDataLoaderParams) {
1104 LOG(WARNING) << "Trying to pass second set of data loader parameters, ignored it";
1105 } else {
1106 ifs.savedDataLoaderParams = std::move(*params);
1107 }
1108 } else {
1109 if (!ifs.savedDataLoaderParams) {
1110 LOG(ERROR) << "Mount " << ifs.mountId
1111 << " is broken: no data loader params (system is not ready yet)";
1112 return false;
1113 }
1114 }
1115 return true; // eventually...
1116 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001117
1118 std::unique_lock l(ifs.lock);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001119 if (ifs.dataLoaderStatus != -1) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001120 LOG(INFO) << "Skipped data loader preparation because it already exists";
1121 return true;
1122 }
1123
1124 auto* dlp = params ? params
1125 : ifs.savedDataLoaderParams ? &ifs.savedDataLoaderParams.value() : nullptr;
1126 if (!dlp) {
1127 LOG(ERROR) << "Mount " << ifs.mountId << " is broken: no data loader params";
1128 return false;
1129 }
1130 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001131 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001132 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001133 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001134 base::unique_fd(::dup(ifs.control.pendingReads())));
1135 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Songchun Fan1124fd32020-02-10 12:49:41 -08001136 sp<IncrementalDataLoaderListener> listener =
Songchun Fan306b7df2020-03-17 12:37:07 -07001137 new IncrementalDataLoaderListener(*this,
1138 externalListener ? *externalListener
1139 : DataLoaderStatusListener());
Songchun Fan3c82a302019-11-29 14:23:45 -08001140 bool created = false;
Songchun Fan68645c42020-02-27 15:57:35 -08001141 auto status = mDataLoaderManager->initializeDataLoader(ifs.mountId, *dlp, fsControlParcel,
1142 listener, &created);
Songchun Fan3c82a302019-11-29 14:23:45 -08001143 if (!status.isOk() || !created) {
1144 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
1145 return false;
1146 }
1147 ifs.savedDataLoaderParams.reset();
1148 return true;
1149}
1150
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001151// Extract lib filse from zip, create new files in incfs and write data to them
1152bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1153 std::string_view libDirRelativePath,
1154 std::string_view abi) {
1155 const auto ifs = getIfs(storage);
1156 // First prepare target directories if they don't exist yet
1157 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1158 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1159 << " errno: " << res;
1160 return false;
1161 }
1162
1163 std::unique_ptr<ZipFileRO> zipFile(ZipFileRO::open(apkFullPath.data()));
1164 if (!zipFile) {
1165 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1166 return false;
1167 }
1168 void* cookie = nullptr;
1169 const auto libFilePrefix = path::join(constants().libDir, abi);
1170 if (!zipFile.get()->startIteration(&cookie, libFilePrefix.c_str() /* prefix */,
1171 constants().libSuffix.data() /* suffix */)) {
1172 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1173 return false;
1174 }
1175 ZipEntryRO entry = nullptr;
1176 bool success = true;
1177 while ((entry = zipFile.get()->nextEntry(cookie)) != nullptr) {
1178 char fileName[PATH_MAX];
1179 if (zipFile.get()->getEntryFileName(entry, fileName, sizeof(fileName))) {
1180 continue;
1181 }
1182 const auto libName = path::basename(fileName);
1183 const auto targetLibPath = path::join(libDirRelativePath, libName);
1184 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1185 // If the extract file already exists, skip
1186 struct stat st;
1187 if (stat(targetLibPathAbsolute.c_str(), &st) == 0) {
1188 LOG(INFO) << "Native lib file already exists: " << targetLibPath
1189 << "; skipping extraction";
1190 continue;
1191 }
1192
1193 uint32_t uncompressedLen;
1194 if (!zipFile.get()->getEntryInfo(entry, nullptr, &uncompressedLen, nullptr, nullptr,
1195 nullptr, nullptr)) {
1196 LOG(ERROR) << "Failed to read native lib entry: " << fileName;
1197 success = false;
1198 break;
1199 }
1200
1201 // Create new lib file without signature info
George Burgess IVdd5275d2020-02-10 11:18:07 -08001202 incfs::NewFileParams libFileParams{};
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001203 libFileParams.size = uncompressedLen;
Alex Buynytskyyf5e605a2020-03-13 13:31:12 -07001204 libFileParams.signature = {};
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001205 // Metadata of the new lib file is its relative path
1206 IncFsSpan libFileMetadata;
1207 libFileMetadata.data = targetLibPath.c_str();
1208 libFileMetadata.size = targetLibPath.size();
1209 libFileParams.metadata = libFileMetadata;
1210 incfs::FileId libFileId = idFromMetadata(targetLibPath);
1211 if (auto res = makeFile(storage, targetLibPath, 0777, libFileId, libFileParams)) {
1212 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
1213 success = false;
1214 // If one lib file fails to be created, abort others as well
1215 break;
1216 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001217 // If it is a zero-byte file, skip data writing
1218 if (uncompressedLen == 0) {
1219 continue;
1220 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001221
1222 // Write extracted data to new file
1223 std::vector<uint8_t> libData(uncompressedLen);
1224 if (!zipFile.get()->uncompressEntry(entry, &libData[0], uncompressedLen)) {
1225 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
1226 success = false;
1227 break;
1228 }
Yurii Zubrytskyie82cdd72020-04-01 12:19:26 -07001229 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1230 if (!writeFd.ok()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001231 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1232 success = false;
1233 break;
1234 }
1235 const int numBlocks = uncompressedLen / constants().blockSize + 1;
1236 std::vector<IncFsDataBlock> instructions;
1237 auto remainingData = std::span(libData);
1238 for (int i = 0; i < numBlocks - 1; i++) {
1239 auto inst = IncFsDataBlock{
1240 .fileFd = writeFd,
1241 .pageIndex = static_cast<IncFsBlockIndex>(i),
1242 .compression = INCFS_COMPRESSION_KIND_NONE,
1243 .kind = INCFS_BLOCK_KIND_DATA,
1244 .dataSize = static_cast<uint16_t>(constants().blockSize),
1245 .data = reinterpret_cast<const char*>(remainingData.data()),
1246 };
1247 instructions.push_back(inst);
1248 remainingData = remainingData.subspan(constants().blockSize);
1249 }
1250 // Last block
1251 auto inst = IncFsDataBlock{
1252 .fileFd = writeFd,
1253 .pageIndex = static_cast<IncFsBlockIndex>(numBlocks - 1),
1254 .compression = INCFS_COMPRESSION_KIND_NONE,
1255 .kind = INCFS_BLOCK_KIND_DATA,
1256 .dataSize = static_cast<uint16_t>(remainingData.size()),
1257 .data = reinterpret_cast<const char*>(remainingData.data()),
1258 };
1259 instructions.push_back(inst);
1260 size_t res = mIncFs->writeBlocks(instructions);
1261 if (res != instructions.size()) {
1262 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1263 success = false;
1264 }
1265 instructions.clear();
1266 }
1267 zipFile.get()->endIteration(cookie);
1268 return success;
1269}
1270
Songchun Fan3c82a302019-11-29 14:23:45 -08001271binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1272 int newStatus) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001273 if (externalListener) {
1274 // Give an external listener a chance to act before we destroy something.
1275 externalListener->onStatusChanged(mountId, newStatus);
1276 }
1277
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001278 bool startRequested = false;
1279 {
1280 std::unique_lock l(incrementalService.mLock);
1281 const auto& ifs = incrementalService.getIfsLocked(mountId);
1282 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001283 LOG(WARNING) << "Received data loader status " << int(newStatus)
1284 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001285 return binder::Status::ok();
1286 }
1287 ifs->dataLoaderStatus = newStatus;
1288
1289 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1290 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1291 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1292 return binder::Status::ok();
1293 }
1294
1295 startRequested = ifs->dataLoaderStartRequested;
Songchun Fan3c82a302019-11-29 14:23:45 -08001296 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001297
Songchun Fan3c82a302019-11-29 14:23:45 -08001298 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001299 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001300 if (startRequested) {
1301 incrementalService.startDataLoader(mountId);
1302 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001303 break;
1304 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001305 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001306 break;
1307 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001308 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001309 break;
1310 }
1311 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1312 break;
1313 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001314 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1315 break;
1316 }
1317 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1318 break;
1319 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001320 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1321 // Nothing for now. Rely on externalListener to handle this.
1322 break;
1323 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001324 default: {
1325 LOG(WARNING) << "Unknown data loader status: " << newStatus
1326 << " for mount: " << mountId;
1327 break;
1328 }
1329 }
1330
1331 return binder::Status::ok();
1332}
1333
1334} // namespace android::incremental