blob: 5e3c337da11eb4c0fca454c8fddcfa1f7d4c6e25 [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 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
161 for (auto&& [target, _] : bindPoints) {
162 LOG(INFO) << "\tbind: " << target;
163 incrementalService.mVold->unmountIncFs(target);
164 }
165 LOG(INFO) << "\troot: " << root;
166 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
167 cleanupFilesystem(root);
168}
169
170auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800171 std::string name;
172 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
173 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
174 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800175 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
176 constants().storagePrefix.data(), id, no);
177 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800178 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800179 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800180 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
181 } else if (err != EEXIST) {
182 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
183 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800184 }
185 }
186 nextStorageDirNo = 0;
187 return storages.end();
188}
189
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800190static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
191 return {::opendir(path), ::closedir};
192}
193
194static int rmDirContent(const char* path) {
195 auto dir = openDir(path);
196 if (!dir) {
197 return -EINVAL;
198 }
199 while (auto entry = ::readdir(dir.get())) {
200 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
201 continue;
202 }
203 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
204 if (entry->d_type == DT_DIR) {
205 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
206 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
207 return err;
208 }
209 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
210 PLOG(WARNING) << "Failed to rmdir " << fullPath;
211 return err;
212 }
213 } else {
214 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
215 PLOG(WARNING) << "Failed to delete " << fullPath;
216 return err;
217 }
218 }
219 }
220 return 0;
221}
222
Songchun Fan3c82a302019-11-29 14:23:45 -0800223void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800224 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800225 ::rmdir(path::join(root, constants().backing).c_str());
226 ::rmdir(path::join(root, constants().mount).c_str());
227 ::rmdir(path::c_str(root));
228}
229
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800230IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800231 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800232 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800233 mIncFs(sm.getIncFs()),
234 mIncrementalDir(rootDir) {
235 if (!mVold) {
236 LOG(FATAL) << "Vold service is unavailable";
237 }
Songchun Fan68645c42020-02-27 15:57:35 -0800238 if (!mDataLoaderManager) {
239 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800240 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800241 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800242}
243
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800244FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800245 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800246}
247
Songchun Fan3c82a302019-11-29 14:23:45 -0800248IncrementalService::~IncrementalService() = default;
249
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800250inline const char* toString(TimePoint t) {
251 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800252 time_t time = SystemClock::to_time_t(
253 SystemClock::now() +
254 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800255 return std::ctime(&time);
256}
257
258inline const char* toString(IncrementalService::BindKind kind) {
259 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800260 case IncrementalService::BindKind::Temporary:
261 return "Temporary";
262 case IncrementalService::BindKind::Permanent:
263 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800264 }
265}
266
267void IncrementalService::onDump(int fd) {
268 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
269 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
270
271 std::unique_lock l(mLock);
272
273 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
274 for (auto&& [id, ifs] : mMounts) {
275 const IncFsMount& mnt = *ifs.get();
276 dprintf(fd, "\t[%d]:\n", id);
277 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
278 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
279 dprintf(fd, "\t\tdataLoaderStatus: %d\n", mnt.dataLoaderStatus.load());
280 dprintf(fd, "\t\tconnectionLostTime: %s\n", toString(mnt.connectionLostTime));
281 if (mnt.savedDataLoaderParams) {
282 const auto& params = mnt.savedDataLoaderParams.value();
283 dprintf(fd, "\t\tsavedDataLoaderParams:\n");
284 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
285 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
286 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
287 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800288 }
289 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
290 for (auto&& [storageId, storage] : mnt.storages) {
291 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
292 }
293
294 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
295 for (auto&& [target, bind] : mnt.bindPoints) {
296 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
297 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
298 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
299 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
300 }
301 }
302
303 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
304 for (auto&& [target, mountPairIt] : mBindsByPath) {
305 const auto& bind = mountPairIt->second;
306 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
307 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
308 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
309 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
310 }
311}
312
Songchun Fan3c82a302019-11-29 14:23:45 -0800313std::optional<std::future<void>> IncrementalService::onSystemReady() {
314 std::promise<void> threadFinished;
315 if (mSystemReady.exchange(true)) {
316 return {};
317 }
318
319 std::vector<IfsMountPtr> mounts;
320 {
321 std::lock_guard l(mLock);
322 mounts.reserve(mMounts.size());
323 for (auto&& [id, ifs] : mMounts) {
324 if (ifs->mountId == id) {
325 mounts.push_back(ifs);
326 }
327 }
328 }
329
330 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800331 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800332 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800333 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
334 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800335 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800336 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800337 }
338 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800339 mPrepareDataLoaders.set_value_at_thread_exit();
340 }).detach();
341 return mPrepareDataLoaders.get_future();
342}
343
344auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
345 for (;;) {
346 if (mNextId == kMaxStorageId) {
347 mNextId = 0;
348 }
349 auto id = ++mNextId;
350 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
351 if (inserted) {
352 return it;
353 }
354 }
355}
356
Songchun Fan1124fd32020-02-10 12:49:41 -0800357StorageId IncrementalService::createStorage(
358 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
359 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800360 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
361 if (!path::isAbsolute(mountPoint)) {
362 LOG(ERROR) << "path is not absolute: " << mountPoint;
363 return kInvalidStorageId;
364 }
365
366 auto mountNorm = path::normalize(mountPoint);
367 {
368 const auto id = findStorageId(mountNorm);
369 if (id != kInvalidStorageId) {
370 if (options & CreateOptions::OpenExisting) {
371 LOG(INFO) << "Opened existing storage " << id;
372 return id;
373 }
374 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
375 return kInvalidStorageId;
376 }
377 }
378
379 if (!(options & CreateOptions::CreateNew)) {
380 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
381 return kInvalidStorageId;
382 }
383
384 if (!path::isEmptyDir(mountNorm)) {
385 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
386 return kInvalidStorageId;
387 }
388 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
389 if (mountRoot.empty()) {
390 LOG(ERROR) << "Bad mount point";
391 return kInvalidStorageId;
392 }
393 // Make sure the code removes all crap it may create while still failing.
394 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
395 auto firstCleanupOnFailure =
396 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
397
398 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800399 const auto backing = path::join(mountRoot, constants().backing);
400 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800401 return kInvalidStorageId;
402 }
403
Songchun Fan3c82a302019-11-29 14:23:45 -0800404 IncFsMount::Control control;
405 {
406 std::lock_guard l(mMountOperationLock);
407 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800408
409 if (auto err = rmDirContent(backing.c_str())) {
410 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
411 return kInvalidStorageId;
412 }
413 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
414 return kInvalidStorageId;
415 }
416 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800417 if (!status.isOk()) {
418 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
419 return kInvalidStorageId;
420 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800421 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
422 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800423 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
424 return kInvalidStorageId;
425 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800426 int cmd = controlParcel.cmd.release().release();
427 int pendingReads = controlParcel.pendingReads.release().release();
428 int logs = controlParcel.log.release().release();
429 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800430 }
431
432 std::unique_lock l(mLock);
433 const auto mountIt = getStorageSlotLocked();
434 const auto mountId = mountIt->first;
435 l.unlock();
436
437 auto ifs =
438 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
439 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
440 // is the removal of the |ifs|.
441 firstCleanupOnFailure.release();
442
443 auto secondCleanup = [this, &l](auto itPtr) {
444 if (!l.owns_lock()) {
445 l.lock();
446 }
447 mMounts.erase(*itPtr);
448 };
449 auto secondCleanupOnFailure =
450 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
451
452 const auto storageIt = ifs->makeStorage(ifs->mountId);
453 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800454 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800455 return kInvalidStorageId;
456 }
457
458 {
459 metadata::Mount m;
460 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800461 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Songchun Fan3c82a302019-11-29 14:23:45 -0800462 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800463 m.mutable_loader()->set_class_name(dataLoaderParams.className);
464 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800465 const auto metadata = m.SerializeAsString();
466 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800467 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800468 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800469 if (auto err =
470 mIncFs->makeFile(ifs->control,
471 path::join(ifs->root, constants().mount,
472 constants().infoMdName),
473 0777, idFromMetadata(metadata),
474 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800475 LOG(ERROR) << "Saving mount metadata failed: " << -err;
476 return kInvalidStorageId;
477 }
478 }
479
480 const auto bk =
481 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800482 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
483 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800484 err < 0) {
485 LOG(ERROR) << "adding bind mount failed: " << -err;
486 return kInvalidStorageId;
487 }
488
489 // Done here as well, all data structures are in good state.
490 secondCleanupOnFailure.release();
491
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800492 if (!prepareDataLoader(*ifs, &dataLoaderParams, &dataLoaderStatusListener)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800493 LOG(ERROR) << "prepareDataLoader() failed";
494 deleteStorageLocked(*ifs, std::move(l));
495 return kInvalidStorageId;
496 }
497
498 mountIt->second = std::move(ifs);
499 l.unlock();
500 LOG(INFO) << "created storage " << mountId;
501 return mountId;
502}
503
504StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
505 StorageId linkedStorage,
506 IncrementalService::CreateOptions options) {
507 if (!isValidMountTarget(mountPoint)) {
508 LOG(ERROR) << "Mount point is invalid or missing";
509 return kInvalidStorageId;
510 }
511
512 std::unique_lock l(mLock);
513 const auto& ifs = getIfsLocked(linkedStorage);
514 if (!ifs) {
515 LOG(ERROR) << "Ifs unavailable";
516 return kInvalidStorageId;
517 }
518
519 const auto mountIt = getStorageSlotLocked();
520 const auto storageId = mountIt->first;
521 const auto storageIt = ifs->makeStorage(storageId);
522 if (storageIt == ifs->storages.end()) {
523 LOG(ERROR) << "Can't create a new storage";
524 mMounts.erase(mountIt);
525 return kInvalidStorageId;
526 }
527
528 l.unlock();
529
530 const auto bk =
531 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800532 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
533 std::string(storageIt->second.name), path::normalize(mountPoint),
534 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800535 err < 0) {
536 LOG(ERROR) << "bindMount failed with error: " << err;
537 return kInvalidStorageId;
538 }
539
540 mountIt->second = ifs;
541 return storageId;
542}
543
544IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
545 std::string_view path) const {
546 auto bindPointIt = mBindsByPath.upper_bound(path);
547 if (bindPointIt == mBindsByPath.begin()) {
548 return mBindsByPath.end();
549 }
550 --bindPointIt;
551 if (!path::startsWith(path, bindPointIt->first)) {
552 return mBindsByPath.end();
553 }
554 return bindPointIt;
555}
556
557StorageId IncrementalService::findStorageId(std::string_view path) const {
558 std::lock_guard l(mLock);
559 auto it = findStorageLocked(path);
560 if (it == mBindsByPath.end()) {
561 return kInvalidStorageId;
562 }
563 return it->second->second.storage;
564}
565
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700566int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
567 const auto ifs = getIfs(storageId);
568 if (!ifs) {
569 return -EINVAL;
570 }
571
572 using unique_fd = ::android::base::unique_fd;
573 ::android::os::incremental::IncrementalFileSystemControlParcel control;
574 control.cmd.reset(unique_fd(dup(ifs->control.cmd())));
575 control.pendingReads.reset(unique_fd(dup(ifs->control.pendingReads())));
576 auto logsFd = ifs->control.logs();
577 if (logsFd >= 0) {
578 control.log.reset(unique_fd(dup(logsFd)));
579 }
580
581 std::lock_guard l(mMountOperationLock);
582 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
583 if (!status.isOk()) {
584 LOG(ERROR) << "Calling Vold::setIncFsMountOptions() failed: " << status.toString8();
585 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
586 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
587 : status.serviceSpecificErrorCode() == 0
588 ? -EFAULT
589 : status.serviceSpecificErrorCode()
590 : -EIO;
591 }
592
593 return 0;
594}
595
Songchun Fan3c82a302019-11-29 14:23:45 -0800596void IncrementalService::deleteStorage(StorageId storageId) {
597 const auto ifs = getIfs(storageId);
598 if (!ifs) {
599 return;
600 }
601 deleteStorage(*ifs);
602}
603
604void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
605 std::unique_lock l(ifs.lock);
606 deleteStorageLocked(ifs, std::move(l));
607}
608
609void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
610 std::unique_lock<std::mutex>&& ifsLock) {
611 const auto storages = std::move(ifs.storages);
612 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
613 const auto bindPoints = ifs.bindPoints;
614 ifsLock.unlock();
615
616 std::lock_guard l(mLock);
617 for (auto&& [id, _] : storages) {
618 if (id != ifs.mountId) {
619 mMounts.erase(id);
620 }
621 }
622 for (auto&& [path, _] : bindPoints) {
623 mBindsByPath.erase(path);
624 }
625 mMounts.erase(ifs.mountId);
626}
627
628StorageId IncrementalService::openStorage(std::string_view pathInMount) {
629 if (!path::isAbsolute(pathInMount)) {
630 return kInvalidStorageId;
631 }
632
633 return findStorageId(path::normalize(pathInMount));
634}
635
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800636FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800637 const auto ifs = getIfs(storage);
638 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800639 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800640 }
641 std::unique_lock l(ifs->lock);
642 auto storageIt = ifs->storages.find(storage);
643 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800644 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800645 }
646 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800647 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800648 }
649 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
650 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800651 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800652}
653
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800654std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800655 StorageId storage, std::string_view subpath) const {
656 auto name = path::basename(subpath);
657 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800658 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800659 }
660 auto dir = path::dirname(subpath);
661 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800662 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800663 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800664 auto id = nodeFor(storage, dir);
665 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800666}
667
668IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
669 std::lock_guard l(mLock);
670 return getIfsLocked(storage);
671}
672
673const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
674 auto it = mMounts.find(storage);
675 if (it == mMounts.end()) {
676 static const IfsMountPtr kEmpty = {};
677 return kEmpty;
678 }
679 return it->second;
680}
681
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800682int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
683 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800684 if (!isValidMountTarget(target)) {
685 return -EINVAL;
686 }
687
688 const auto ifs = getIfs(storage);
689 if (!ifs) {
690 return -EINVAL;
691 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800692
Songchun Fan3c82a302019-11-29 14:23:45 -0800693 std::unique_lock l(ifs->lock);
694 const auto storageInfo = ifs->storages.find(storage);
695 if (storageInfo == ifs->storages.end()) {
696 return -EINVAL;
697 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800698 std::string normSource = normalizePathToStorage(ifs, storage, source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800699 l.unlock();
700 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800701 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
702 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800703}
704
705int IncrementalService::unbind(StorageId storage, std::string_view target) {
706 if (!path::isAbsolute(target)) {
707 return -EINVAL;
708 }
709
710 LOG(INFO) << "Removing bind point " << target;
711
712 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
713 // otherwise there's a chance to unmount something completely unrelated
714 const auto norm = path::normalize(target);
715 std::unique_lock l(mLock);
716 const auto storageIt = mBindsByPath.find(norm);
717 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
718 return -EINVAL;
719 }
720 const auto bindIt = storageIt->second;
721 const auto storageId = bindIt->second.storage;
722 const auto ifs = getIfsLocked(storageId);
723 if (!ifs) {
724 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
725 << " is missing";
726 return -EFAULT;
727 }
728 mBindsByPath.erase(storageIt);
729 l.unlock();
730
731 mVold->unmountIncFs(bindIt->first);
732 std::unique_lock l2(ifs->lock);
733 if (ifs->bindPoints.size() <= 1) {
734 ifs->bindPoints.clear();
735 deleteStorageLocked(*ifs, std::move(l2));
736 } else {
737 const std::string savedFile = std::move(bindIt->second.savedFilename);
738 ifs->bindPoints.erase(bindIt);
739 l2.unlock();
740 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800741 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800742 }
743 }
744 return 0;
745}
746
Songchun Fan103ba1d2020-02-03 17:32:32 -0800747std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr ifs,
748 StorageId storage, std::string_view path) {
749 const auto storageInfo = ifs->storages.find(storage);
750 if (storageInfo == ifs->storages.end()) {
751 return {};
752 }
753 std::string normPath;
754 if (path::isAbsolute(path)) {
755 normPath = path::normalize(path);
756 } else {
757 normPath = path::normalize(path::join(storageInfo->second.name, path));
758 }
759 if (!path::startsWith(normPath, storageInfo->second.name)) {
760 return {};
761 }
762 return normPath;
763}
764
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800765int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
766 incfs::NewFileParams params) {
767 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800768 std::string normPath = normalizePathToStorage(ifs, storage, path);
769 if (normPath.empty()) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700770 LOG(ERROR) << "Internal error: storageId " << storage << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800771 return -EINVAL;
772 }
773 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800774 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700775 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800776 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800777 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800778 std::vector<uint8_t> metadataBytes;
779 if (params.metadata.data && params.metadata.size > 0) {
780 metadataBytes.assign(params.metadata.data, params.metadata.data + params.metadata.size);
Songchun Fan3c82a302019-11-29 14:23:45 -0800781 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800782 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800783 }
784 return -EINVAL;
785}
786
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800787int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800788 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800789 std::string normPath = normalizePathToStorage(ifs, storageId, path);
790 if (normPath.empty()) {
791 return -EINVAL;
792 }
793 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800794 }
795 return -EINVAL;
796}
797
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800798int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800799 const auto ifs = getIfs(storageId);
800 if (!ifs) {
801 return -EINVAL;
802 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800803 std::string normPath = normalizePathToStorage(ifs, storageId, path);
804 if (normPath.empty()) {
805 return -EINVAL;
806 }
807 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800808 if (err == -EEXIST) {
809 return 0;
810 } else if (err != -ENOENT) {
811 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800812 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800813 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800814 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800815 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800816 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800817}
818
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800819int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
820 StorageId destStorageId, std::string_view newPath) {
821 if (auto ifsSrc = getIfs(sourceStorageId), ifsDest = getIfs(destStorageId);
822 ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800823 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
824 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
825 if (normOldPath.empty() || normNewPath.empty()) {
826 return -EINVAL;
827 }
828 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800829 }
830 return -EINVAL;
831}
832
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800833int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800834 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800835 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
836 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800837 }
838 return -EINVAL;
839}
840
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800841int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
842 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800843 std::string&& target, BindKind kind,
844 std::unique_lock<std::mutex>& mainLock) {
845 if (!isValidMountTarget(target)) {
846 return -EINVAL;
847 }
848
849 std::string mdFileName;
850 if (kind != BindKind::Temporary) {
851 metadata::BindPoint bp;
852 bp.set_storage_id(storage);
853 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800854 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800855 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800856 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800857 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800858 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800859 auto node =
860 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
861 0444, idFromMetadata(metadata),
862 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
863 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800864 return int(node);
865 }
866 }
867
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800868 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800869 std::move(target), kind, mainLock);
870}
871
872int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800873 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800874 std::string&& target, BindKind kind,
875 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800876 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800877 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800878 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800879 if (!status.isOk()) {
880 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
881 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
882 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
883 : status.serviceSpecificErrorCode() == 0
884 ? -EFAULT
885 : status.serviceSpecificErrorCode()
886 : -EIO;
887 }
888 }
889
890 if (!mainLock.owns_lock()) {
891 mainLock.lock();
892 }
893 std::lock_guard l(ifs.lock);
894 const auto [it, _] =
895 ifs.bindPoints.insert_or_assign(target,
896 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800897 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800898 mBindsByPath[std::move(target)] = it;
899 return 0;
900}
901
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800902RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800903 const auto ifs = getIfs(storage);
904 if (!ifs) {
905 return {};
906 }
907 return mIncFs->getMetadata(ifs->control, node);
908}
909
910std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
911 const auto ifs = getIfs(storage);
912 if (!ifs) {
913 return {};
914 }
915
916 std::unique_lock l(ifs->lock);
917 auto subdirIt = ifs->storages.find(storage);
918 if (subdirIt == ifs->storages.end()) {
919 return {};
920 }
921 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
922 l.unlock();
923
924 const auto prefixSize = dir.size() + 1;
925 std::vector<std::string> todoDirs{std::move(dir)};
926 std::vector<std::string> result;
927 do {
928 auto currDir = std::move(todoDirs.back());
929 todoDirs.pop_back();
930
931 auto d =
932 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
933 while (auto e = ::readdir(d.get())) {
934 if (e->d_type == DT_REG) {
935 result.emplace_back(
936 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
937 continue;
938 }
939 if (e->d_type == DT_DIR) {
940 if (e->d_name == "."sv || e->d_name == ".."sv) {
941 continue;
942 }
943 todoDirs.emplace_back(path::join(currDir, e->d_name));
944 continue;
945 }
946 }
947 } while (!todoDirs.empty());
948 return result;
949}
950
951bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700952 {
953 std::unique_lock l(mLock);
954 const auto& ifs = getIfsLocked(storage);
955 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800956 return false;
957 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700958 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
959 ifs->dataLoaderStartRequested = true;
960 return true;
961 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800962 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700963 return startDataLoader(storage);
964}
965
966bool IncrementalService::startDataLoader(MountId mountId) const {
Songchun Fan68645c42020-02-27 15:57:35 -0800967 sp<IDataLoader> dataloader;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700968 auto status = mDataLoaderManager->getDataLoader(mountId, &dataloader);
Songchun Fan3c82a302019-11-29 14:23:45 -0800969 if (!status.isOk()) {
970 return false;
971 }
Songchun Fan68645c42020-02-27 15:57:35 -0800972 if (!dataloader) {
973 return false;
974 }
Alex Buynytskyyb6e02f72020-03-17 18:12:23 -0700975 status = dataloader->start(mountId);
Songchun Fan68645c42020-02-27 15:57:35 -0800976 if (!status.isOk()) {
977 return false;
978 }
979 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -0800980}
981
982void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -0800983 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
984 const auto path = entry.path().u8string();
985 const auto name = entry.path().filename().u8string();
986 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800987 continue;
988 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800989 const auto root = path::join(mIncrementalDir, name);
990 if (!mountExistingImage(root, name)) {
991 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800992 }
993 }
994}
995
996bool IncrementalService::mountExistingImage(std::string_view root, std::string_view key) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800997 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800998 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -0800999
Songchun Fan3c82a302019-11-29 14:23:45 -08001000 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001001 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001002 if (!status.isOk()) {
1003 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1004 return false;
1005 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001006
1007 int cmd = controlParcel.cmd.release().release();
1008 int pendingReads = controlParcel.pendingReads.release().release();
1009 int logs = controlParcel.log.release().release();
1010 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001011
1012 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1013
1014 auto m = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1015 path::join(mountTarget, constants().infoMdName));
1016 if (!m.has_loader() || !m.has_storage()) {
1017 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1018 return false;
1019 }
1020
1021 ifs->mountId = m.storage().id();
1022 mNextId = std::max(mNextId, ifs->mountId + 1);
1023
1024 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001025 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001026 while (auto e = ::readdir(d.get())) {
1027 if (e->d_type == DT_REG) {
1028 auto name = std::string_view(e->d_name);
1029 if (name.starts_with(constants().mountpointMdPrefix)) {
1030 bindPoints.emplace_back(name,
1031 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1032 ifs->control,
1033 path::join(mountTarget,
1034 name)));
1035 if (bindPoints.back().second.dest_path().empty() ||
1036 bindPoints.back().second.source_subdir().empty()) {
1037 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001038 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001039 }
1040 }
1041 } else if (e->d_type == DT_DIR) {
1042 if (e->d_name == "."sv || e->d_name == ".."sv) {
1043 continue;
1044 }
1045 auto name = std::string_view(e->d_name);
1046 if (name.starts_with(constants().storagePrefix)) {
1047 auto md = parseFromIncfs<metadata::Storage>(mIncFs.get(), ifs->control,
1048 path::join(mountTarget, name));
1049 auto [_, inserted] = mMounts.try_emplace(md.id(), ifs);
1050 if (!inserted) {
1051 LOG(WARNING) << "Ignoring storage with duplicate id " << md.id()
1052 << " for mount " << root;
1053 continue;
1054 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001055 ifs->storages.insert_or_assign(md.id(), IncFsMount::Storage{std::string(name)});
Songchun Fan3c82a302019-11-29 14:23:45 -08001056 mNextId = std::max(mNextId, md.id() + 1);
1057 }
1058 }
1059 }
1060
1061 if (ifs->storages.empty()) {
1062 LOG(WARNING) << "No valid storages in mount " << root;
1063 return false;
1064 }
1065
1066 int bindCount = 0;
1067 for (auto&& bp : bindPoints) {
1068 std::unique_lock l(mLock, std::defer_lock);
1069 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1070 std::move(*bp.second.mutable_source_subdir()),
1071 std::move(*bp.second.mutable_dest_path()),
1072 BindKind::Permanent, l);
1073 }
1074
1075 if (bindCount == 0) {
1076 LOG(WARNING) << "No valid bind points for mount " << root;
1077 deleteStorage(*ifs);
1078 return false;
1079 }
1080
Songchun Fan3c82a302019-11-29 14:23:45 -08001081 mMounts[ifs->mountId] = std::move(ifs);
1082 return true;
1083}
1084
1085bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001086 DataLoaderParamsParcel* params,
1087 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001088 if (!mSystemReady.load(std::memory_order_relaxed)) {
1089 std::unique_lock l(ifs.lock);
1090 if (params) {
1091 if (ifs.savedDataLoaderParams) {
1092 LOG(WARNING) << "Trying to pass second set of data loader parameters, ignored it";
1093 } else {
1094 ifs.savedDataLoaderParams = std::move(*params);
1095 }
1096 } else {
1097 if (!ifs.savedDataLoaderParams) {
1098 LOG(ERROR) << "Mount " << ifs.mountId
1099 << " is broken: no data loader params (system is not ready yet)";
1100 return false;
1101 }
1102 }
1103 return true; // eventually...
1104 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001105
1106 std::unique_lock l(ifs.lock);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001107 if (ifs.dataLoaderStatus != -1) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001108 LOG(INFO) << "Skipped data loader preparation because it already exists";
1109 return true;
1110 }
1111
1112 auto* dlp = params ? params
1113 : ifs.savedDataLoaderParams ? &ifs.savedDataLoaderParams.value() : nullptr;
1114 if (!dlp) {
1115 LOG(ERROR) << "Mount " << ifs.mountId << " is broken: no data loader params";
1116 return false;
1117 }
1118 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001119 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001120 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001121 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001122 base::unique_fd(::dup(ifs.control.pendingReads())));
1123 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Songchun Fan1124fd32020-02-10 12:49:41 -08001124 sp<IncrementalDataLoaderListener> listener =
Songchun Fan306b7df2020-03-17 12:37:07 -07001125 new IncrementalDataLoaderListener(*this,
1126 externalListener ? *externalListener
1127 : DataLoaderStatusListener());
Songchun Fan3c82a302019-11-29 14:23:45 -08001128 bool created = false;
Songchun Fan68645c42020-02-27 15:57:35 -08001129 auto status = mDataLoaderManager->initializeDataLoader(ifs.mountId, *dlp, fsControlParcel,
1130 listener, &created);
Songchun Fan3c82a302019-11-29 14:23:45 -08001131 if (!status.isOk() || !created) {
1132 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
1133 return false;
1134 }
1135 ifs.savedDataLoaderParams.reset();
1136 return true;
1137}
1138
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001139// Extract lib filse from zip, create new files in incfs and write data to them
1140bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1141 std::string_view libDirRelativePath,
1142 std::string_view abi) {
1143 const auto ifs = getIfs(storage);
1144 // First prepare target directories if they don't exist yet
1145 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1146 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1147 << " errno: " << res;
1148 return false;
1149 }
1150
1151 std::unique_ptr<ZipFileRO> zipFile(ZipFileRO::open(apkFullPath.data()));
1152 if (!zipFile) {
1153 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1154 return false;
1155 }
1156 void* cookie = nullptr;
1157 const auto libFilePrefix = path::join(constants().libDir, abi);
1158 if (!zipFile.get()->startIteration(&cookie, libFilePrefix.c_str() /* prefix */,
1159 constants().libSuffix.data() /* suffix */)) {
1160 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1161 return false;
1162 }
1163 ZipEntryRO entry = nullptr;
1164 bool success = true;
1165 while ((entry = zipFile.get()->nextEntry(cookie)) != nullptr) {
1166 char fileName[PATH_MAX];
1167 if (zipFile.get()->getEntryFileName(entry, fileName, sizeof(fileName))) {
1168 continue;
1169 }
1170 const auto libName = path::basename(fileName);
1171 const auto targetLibPath = path::join(libDirRelativePath, libName);
1172 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1173 // If the extract file already exists, skip
1174 struct stat st;
1175 if (stat(targetLibPathAbsolute.c_str(), &st) == 0) {
1176 LOG(INFO) << "Native lib file already exists: " << targetLibPath
1177 << "; skipping extraction";
1178 continue;
1179 }
1180
1181 uint32_t uncompressedLen;
1182 if (!zipFile.get()->getEntryInfo(entry, nullptr, &uncompressedLen, nullptr, nullptr,
1183 nullptr, nullptr)) {
1184 LOG(ERROR) << "Failed to read native lib entry: " << fileName;
1185 success = false;
1186 break;
1187 }
1188
1189 // Create new lib file without signature info
George Burgess IVdd5275d2020-02-10 11:18:07 -08001190 incfs::NewFileParams libFileParams{};
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001191 libFileParams.size = uncompressedLen;
Alex Buynytskyyf5e605a2020-03-13 13:31:12 -07001192 libFileParams.signature = {};
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001193 // Metadata of the new lib file is its relative path
1194 IncFsSpan libFileMetadata;
1195 libFileMetadata.data = targetLibPath.c_str();
1196 libFileMetadata.size = targetLibPath.size();
1197 libFileParams.metadata = libFileMetadata;
1198 incfs::FileId libFileId = idFromMetadata(targetLibPath);
1199 if (auto res = makeFile(storage, targetLibPath, 0777, libFileId, libFileParams)) {
1200 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
1201 success = false;
1202 // If one lib file fails to be created, abort others as well
1203 break;
1204 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001205 // If it is a zero-byte file, skip data writing
1206 if (uncompressedLen == 0) {
1207 continue;
1208 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001209
1210 // Write extracted data to new file
1211 std::vector<uint8_t> libData(uncompressedLen);
1212 if (!zipFile.get()->uncompressEntry(entry, &libData[0], uncompressedLen)) {
1213 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
1214 success = false;
1215 break;
1216 }
Yurii Zubrytskyie82cdd72020-04-01 12:19:26 -07001217 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1218 if (!writeFd.ok()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001219 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1220 success = false;
1221 break;
1222 }
1223 const int numBlocks = uncompressedLen / constants().blockSize + 1;
1224 std::vector<IncFsDataBlock> instructions;
1225 auto remainingData = std::span(libData);
1226 for (int i = 0; i < numBlocks - 1; i++) {
1227 auto inst = IncFsDataBlock{
1228 .fileFd = writeFd,
1229 .pageIndex = static_cast<IncFsBlockIndex>(i),
1230 .compression = INCFS_COMPRESSION_KIND_NONE,
1231 .kind = INCFS_BLOCK_KIND_DATA,
1232 .dataSize = static_cast<uint16_t>(constants().blockSize),
1233 .data = reinterpret_cast<const char*>(remainingData.data()),
1234 };
1235 instructions.push_back(inst);
1236 remainingData = remainingData.subspan(constants().blockSize);
1237 }
1238 // Last block
1239 auto inst = IncFsDataBlock{
1240 .fileFd = writeFd,
1241 .pageIndex = static_cast<IncFsBlockIndex>(numBlocks - 1),
1242 .compression = INCFS_COMPRESSION_KIND_NONE,
1243 .kind = INCFS_BLOCK_KIND_DATA,
1244 .dataSize = static_cast<uint16_t>(remainingData.size()),
1245 .data = reinterpret_cast<const char*>(remainingData.data()),
1246 };
1247 instructions.push_back(inst);
1248 size_t res = mIncFs->writeBlocks(instructions);
1249 if (res != instructions.size()) {
1250 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1251 success = false;
1252 }
1253 instructions.clear();
1254 }
1255 zipFile.get()->endIteration(cookie);
1256 return success;
1257}
1258
Songchun Fan3c82a302019-11-29 14:23:45 -08001259binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1260 int newStatus) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001261 if (externalListener) {
1262 // Give an external listener a chance to act before we destroy something.
1263 externalListener->onStatusChanged(mountId, newStatus);
1264 }
1265
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001266 bool startRequested = false;
1267 {
1268 std::unique_lock l(incrementalService.mLock);
1269 const auto& ifs = incrementalService.getIfsLocked(mountId);
1270 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001271 LOG(WARNING) << "Received data loader status " << int(newStatus)
1272 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001273 return binder::Status::ok();
1274 }
1275 ifs->dataLoaderStatus = newStatus;
1276
1277 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1278 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1279 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1280 return binder::Status::ok();
1281 }
1282
1283 startRequested = ifs->dataLoaderStartRequested;
Songchun Fan3c82a302019-11-29 14:23:45 -08001284 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001285
Songchun Fan3c82a302019-11-29 14:23:45 -08001286 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001287 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001288 if (startRequested) {
1289 incrementalService.startDataLoader(mountId);
1290 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001291 break;
1292 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001293 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001294 break;
1295 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001296 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001297 break;
1298 }
1299 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1300 break;
1301 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001302 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1303 break;
1304 }
1305 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1306 break;
1307 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001308 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1309 // Nothing for now. Rely on externalListener to handle this.
1310 break;
1311 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001312 default: {
1313 LOG(WARNING) << "Unknown data loader status: " << newStatus
1314 << " for mount: " << mountId;
1315 break;
1316 }
1317 }
1318
1319 return binder::Status::ok();
1320}
1321
1322} // namespace android::incremental