blob: c43328fcdf9d85e6861ef3e73064c4a9dbdbe1bd [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
21#include <android-base/file.h>
22#include <android-base/logging.h>
23#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
25#include <android-base/strings.h>
26#include <android/content/pm/IDataLoaderStatusListener.h>
27#include <android/os/IVold.h>
28#include <androidfw/ZipFileRO.h>
29#include <androidfw/ZipUtils.h>
30#include <binder/BinderService.h>
31#include <binder/ParcelFileDescriptor.h>
32#include <binder/Status.h>
33#include <sys/stat.h>
34#include <uuid/uuid.h>
35#include <zlib.h>
36
37#include <iterator>
38#include <span>
39#include <stack>
40#include <thread>
41#include <type_traits>
42
43#include "Metadata.pb.h"
44
45using namespace std::literals;
46using namespace android::content::pm;
47
48namespace android::incremental {
49
50namespace {
51
52using IncrementalFileSystemControlParcel =
53 ::android::os::incremental::IncrementalFileSystemControlParcel;
54
55struct Constants {
56 static constexpr auto backing = "backing_store"sv;
57 static constexpr auto mount = "mount"sv;
58 static constexpr auto image = "incfs.img"sv;
59 static constexpr auto storagePrefix = "st"sv;
60 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
61 static constexpr auto infoMdName = ".info"sv;
62};
63
64static const Constants& constants() {
65 static Constants c;
66 return c;
67}
68
69template <base::LogSeverity level = base::ERROR>
70bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
71 auto cstr = path::c_str(name);
72 if (::mkdir(cstr, mode)) {
73 if (errno != EEXIST) {
74 PLOG(level) << "Can't create directory '" << name << '\'';
75 return false;
76 }
77 struct stat st;
78 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
79 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
80 return false;
81 }
82 }
83 return true;
84}
85
86static std::string toMountKey(std::string_view path) {
87 if (path.empty()) {
88 return "@none";
89 }
90 if (path == "/"sv) {
91 return "@root";
92 }
93 if (path::isAbsolute(path)) {
94 path.remove_prefix(1);
95 }
96 std::string res(path);
97 std::replace(res.begin(), res.end(), '/', '_');
98 std::replace(res.begin(), res.end(), '@', '_');
99 return res;
100}
101
102static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
103 std::string_view path) {
104 auto mountKey = toMountKey(path);
105 const auto prefixSize = mountKey.size();
106 for (int counter = 0; counter < 1000;
107 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
108 auto mountRoot = path::join(incrementalDir, mountKey);
109 if (mkdirOrLog(mountRoot, 0770, false)) {
110 return {mountKey, mountRoot};
111 }
112 }
113 return {};
114}
115
116template <class ProtoMessage, class Control>
117static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
118 std::string_view path) {
119 struct stat st;
120 if (::stat(path::c_str(path), &st)) {
121 return {};
122 }
123 auto md = incfs->getMetadata(control, st.st_ino);
124 ProtoMessage message;
125 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
126}
127
128static bool isValidMountTarget(std::string_view path) {
129 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
130}
131
132std::string makeBindMdName() {
133 static constexpr auto uuidStringSize = 36;
134
135 uuid_t guid;
136 uuid_generate(guid);
137
138 std::string name;
139 const auto prefixSize = constants().mountpointMdPrefix.size();
140 name.reserve(prefixSize + uuidStringSize);
141
142 name = constants().mountpointMdPrefix;
143 name.resize(prefixSize + uuidStringSize);
144 uuid_unparse(guid, name.data() + prefixSize);
145
146 return name;
147}
148} // namespace
149
150IncrementalService::IncFsMount::~IncFsMount() {
151 incrementalService.mIncrementalManager->destroyDataLoader(mountId);
152 control.reset();
153 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
154 for (auto&& [target, _] : bindPoints) {
155 LOG(INFO) << "\tbind: " << target;
156 incrementalService.mVold->unmountIncFs(target);
157 }
158 LOG(INFO) << "\troot: " << root;
159 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
160 cleanupFilesystem(root);
161}
162
163auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
164 metadata::Storage st;
165 st.set_id(id);
166 auto metadata = st.SerializeAsString();
167
168 std::string name;
169 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
170 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
171 name.clear();
172 base::StringAppendF(&name, "%.*s%d", int(constants().storagePrefix.size()),
173 constants().storagePrefix.data(), no);
174 if (auto node =
175 incrementalService.mIncFs->makeDir(control, name, INCFS_ROOT_INODE, metadata);
176 node >= 0) {
177 std::lock_guard l(lock);
178 return storages.insert_or_assign(id, Storage{std::move(name), node}).first;
179 }
180 }
181 nextStorageDirNo = 0;
182 return storages.end();
183}
184
185void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
186 ::unlink(path::join(root, constants().backing, constants().image).c_str());
187 ::rmdir(path::join(root, constants().backing).c_str());
188 ::rmdir(path::join(root, constants().mount).c_str());
189 ::rmdir(path::c_str(root));
190}
191
192IncrementalService::IncrementalService(const ServiceManagerWrapper& sm, std::string_view rootDir)
193 : mVold(sm.getVoldService()),
194 mIncrementalManager(sm.getIncrementalManager()),
195 mIncFs(sm.getIncFs()),
196 mIncrementalDir(rootDir) {
197 if (!mVold) {
198 LOG(FATAL) << "Vold service is unavailable";
199 }
200 if (!mIncrementalManager) {
201 LOG(FATAL) << "IncrementalManager service is unavailable";
202 }
203 // TODO(b/136132412): check that root dir should already exist
204 // TODO(b/136132412): enable mount existing dirs after SELinux rules are merged
205 // mountExistingImages();
206}
207
208IncrementalService::~IncrementalService() = default;
209
210std::optional<std::future<void>> IncrementalService::onSystemReady() {
211 std::promise<void> threadFinished;
212 if (mSystemReady.exchange(true)) {
213 return {};
214 }
215
216 std::vector<IfsMountPtr> mounts;
217 {
218 std::lock_guard l(mLock);
219 mounts.reserve(mMounts.size());
220 for (auto&& [id, ifs] : mMounts) {
221 if (ifs->mountId == id) {
222 mounts.push_back(ifs);
223 }
224 }
225 }
226
227 std::thread([this, mounts = std::move(mounts)]() {
228 std::vector<IfsMountPtr> failedLoaderMounts;
229 for (auto&& ifs : mounts) {
230 if (prepareDataLoader(*ifs, nullptr)) {
231 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
232 } else {
233 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
234 failedLoaderMounts.push_back(std::move(ifs));
235 }
236 }
237
238 while (!failedLoaderMounts.empty()) {
239 LOG(WARNING) << "Deleting failed mount " << failedLoaderMounts.back()->mountId;
240 deleteStorage(*failedLoaderMounts.back());
241 failedLoaderMounts.pop_back();
242 }
243 mPrepareDataLoaders.set_value_at_thread_exit();
244 }).detach();
245 return mPrepareDataLoaders.get_future();
246}
247
248auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
249 for (;;) {
250 if (mNextId == kMaxStorageId) {
251 mNextId = 0;
252 }
253 auto id = ++mNextId;
254 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
255 if (inserted) {
256 return it;
257 }
258 }
259}
260
261StorageId IncrementalService::createStorage(std::string_view mountPoint,
262 DataLoaderParamsParcel&& dataLoaderParams,
263 CreateOptions options) {
264 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
265 if (!path::isAbsolute(mountPoint)) {
266 LOG(ERROR) << "path is not absolute: " << mountPoint;
267 return kInvalidStorageId;
268 }
269
270 auto mountNorm = path::normalize(mountPoint);
271 {
272 const auto id = findStorageId(mountNorm);
273 if (id != kInvalidStorageId) {
274 if (options & CreateOptions::OpenExisting) {
275 LOG(INFO) << "Opened existing storage " << id;
276 return id;
277 }
278 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
279 return kInvalidStorageId;
280 }
281 }
282
283 if (!(options & CreateOptions::CreateNew)) {
284 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
285 return kInvalidStorageId;
286 }
287
288 if (!path::isEmptyDir(mountNorm)) {
289 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
290 return kInvalidStorageId;
291 }
292 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
293 if (mountRoot.empty()) {
294 LOG(ERROR) << "Bad mount point";
295 return kInvalidStorageId;
296 }
297 // Make sure the code removes all crap it may create while still failing.
298 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
299 auto firstCleanupOnFailure =
300 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
301
302 auto mountTarget = path::join(mountRoot, constants().mount);
303 if (!mkdirOrLog(path::join(mountRoot, constants().backing)) || !mkdirOrLog(mountTarget)) {
304 return kInvalidStorageId;
305 }
306
307 const auto image = path::join(mountRoot, constants().backing, constants().image);
308 IncFsMount::Control control;
309 {
310 std::lock_guard l(mMountOperationLock);
311 IncrementalFileSystemControlParcel controlParcel;
312 auto status = mVold->mountIncFs(image, mountTarget, incfs::truncate, &controlParcel);
313 if (!status.isOk()) {
314 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
315 return kInvalidStorageId;
316 }
317 if (!controlParcel.cmd || !controlParcel.log) {
318 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
319 return kInvalidStorageId;
320 }
321 control.cmdFd = controlParcel.cmd->release();
322 control.logFd = controlParcel.log->release();
323 }
324
325 std::unique_lock l(mLock);
326 const auto mountIt = getStorageSlotLocked();
327 const auto mountId = mountIt->first;
328 l.unlock();
329
330 auto ifs =
331 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
332 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
333 // is the removal of the |ifs|.
334 firstCleanupOnFailure.release();
335
336 auto secondCleanup = [this, &l](auto itPtr) {
337 if (!l.owns_lock()) {
338 l.lock();
339 }
340 mMounts.erase(*itPtr);
341 };
342 auto secondCleanupOnFailure =
343 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
344
345 const auto storageIt = ifs->makeStorage(ifs->mountId);
346 if (storageIt == ifs->storages.end()) {
347 LOG(ERROR) << "Can't create default storage directory";
348 return kInvalidStorageId;
349 }
350
351 {
352 metadata::Mount m;
353 m.mutable_storage()->set_id(ifs->mountId);
354 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
355 m.mutable_loader()->set_arguments(dataLoaderParams.staticArgs);
356 const auto metadata = m.SerializeAsString();
357 m.mutable_loader()->release_arguments();
358 m.mutable_loader()->release_package_name();
359 if (auto err = mIncFs->makeFile(ifs->control, constants().infoMdName, INCFS_ROOT_INODE, 0,
360 metadata);
361 err < 0) {
362 LOG(ERROR) << "Saving mount metadata failed: " << -err;
363 return kInvalidStorageId;
364 }
365 }
366
367 const auto bk =
368 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
369 if (auto err = addBindMount(*ifs, storageIt->first, std::string(storageIt->second.name),
370 std::move(mountNorm), bk, l);
371 err < 0) {
372 LOG(ERROR) << "adding bind mount failed: " << -err;
373 return kInvalidStorageId;
374 }
375
376 // Done here as well, all data structures are in good state.
377 secondCleanupOnFailure.release();
378
379 if (!prepareDataLoader(*ifs, &dataLoaderParams)) {
380 LOG(ERROR) << "prepareDataLoader() failed";
381 deleteStorageLocked(*ifs, std::move(l));
382 return kInvalidStorageId;
383 }
384
385 mountIt->second = std::move(ifs);
386 l.unlock();
387 LOG(INFO) << "created storage " << mountId;
388 return mountId;
389}
390
391StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
392 StorageId linkedStorage,
393 IncrementalService::CreateOptions options) {
394 if (!isValidMountTarget(mountPoint)) {
395 LOG(ERROR) << "Mount point is invalid or missing";
396 return kInvalidStorageId;
397 }
398
399 std::unique_lock l(mLock);
400 const auto& ifs = getIfsLocked(linkedStorage);
401 if (!ifs) {
402 LOG(ERROR) << "Ifs unavailable";
403 return kInvalidStorageId;
404 }
405
406 const auto mountIt = getStorageSlotLocked();
407 const auto storageId = mountIt->first;
408 const auto storageIt = ifs->makeStorage(storageId);
409 if (storageIt == ifs->storages.end()) {
410 LOG(ERROR) << "Can't create a new storage";
411 mMounts.erase(mountIt);
412 return kInvalidStorageId;
413 }
414
415 l.unlock();
416
417 const auto bk =
418 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
419 if (auto err = addBindMount(*ifs, storageIt->first, std::string(storageIt->second.name),
420 path::normalize(mountPoint), bk, l);
421 err < 0) {
422 LOG(ERROR) << "bindMount failed with error: " << err;
423 return kInvalidStorageId;
424 }
425
426 mountIt->second = ifs;
427 return storageId;
428}
429
430IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
431 std::string_view path) const {
432 auto bindPointIt = mBindsByPath.upper_bound(path);
433 if (bindPointIt == mBindsByPath.begin()) {
434 return mBindsByPath.end();
435 }
436 --bindPointIt;
437 if (!path::startsWith(path, bindPointIt->first)) {
438 return mBindsByPath.end();
439 }
440 return bindPointIt;
441}
442
443StorageId IncrementalService::findStorageId(std::string_view path) const {
444 std::lock_guard l(mLock);
445 auto it = findStorageLocked(path);
446 if (it == mBindsByPath.end()) {
447 return kInvalidStorageId;
448 }
449 return it->second->second.storage;
450}
451
452void IncrementalService::deleteStorage(StorageId storageId) {
453 const auto ifs = getIfs(storageId);
454 if (!ifs) {
455 return;
456 }
457 deleteStorage(*ifs);
458}
459
460void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
461 std::unique_lock l(ifs.lock);
462 deleteStorageLocked(ifs, std::move(l));
463}
464
465void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
466 std::unique_lock<std::mutex>&& ifsLock) {
467 const auto storages = std::move(ifs.storages);
468 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
469 const auto bindPoints = ifs.bindPoints;
470 ifsLock.unlock();
471
472 std::lock_guard l(mLock);
473 for (auto&& [id, _] : storages) {
474 if (id != ifs.mountId) {
475 mMounts.erase(id);
476 }
477 }
478 for (auto&& [path, _] : bindPoints) {
479 mBindsByPath.erase(path);
480 }
481 mMounts.erase(ifs.mountId);
482}
483
484StorageId IncrementalService::openStorage(std::string_view pathInMount) {
485 if (!path::isAbsolute(pathInMount)) {
486 return kInvalidStorageId;
487 }
488
489 return findStorageId(path::normalize(pathInMount));
490}
491
492Inode IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
493 const auto ifs = getIfs(storage);
494 if (!ifs) {
495 return -1;
496 }
497 std::unique_lock l(ifs->lock);
498 auto storageIt = ifs->storages.find(storage);
499 if (storageIt == ifs->storages.end()) {
500 return -1;
501 }
502 if (subpath.empty() || subpath == "."sv) {
503 return storageIt->second.node;
504 }
505 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
506 l.unlock();
507 struct stat st;
508 if (::stat(path.c_str(), &st)) {
509 return -1;
510 }
511 return st.st_ino;
512}
513
514std::pair<Inode, std::string_view> IncrementalService::parentAndNameFor(
515 StorageId storage, std::string_view subpath) const {
516 auto name = path::basename(subpath);
517 if (name.empty()) {
518 return {-1, {}};
519 }
520 auto dir = path::dirname(subpath);
521 if (dir.empty() || dir == "/"sv) {
522 return {-1, {}};
523 }
524 auto inode = nodeFor(storage, dir);
525 return {inode, name};
526}
527
528IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
529 std::lock_guard l(mLock);
530 return getIfsLocked(storage);
531}
532
533const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
534 auto it = mMounts.find(storage);
535 if (it == mMounts.end()) {
536 static const IfsMountPtr kEmpty = {};
537 return kEmpty;
538 }
539 return it->second;
540}
541
542int IncrementalService::bind(StorageId storage, std::string_view sourceSubdir,
543 std::string_view target, BindKind kind) {
544 if (!isValidMountTarget(target)) {
545 return -EINVAL;
546 }
547
548 const auto ifs = getIfs(storage);
549 if (!ifs) {
550 return -EINVAL;
551 }
552 std::unique_lock l(ifs->lock);
553 const auto storageInfo = ifs->storages.find(storage);
554 if (storageInfo == ifs->storages.end()) {
555 return -EINVAL;
556 }
557 auto source = path::join(storageInfo->second.name, sourceSubdir);
558 l.unlock();
559 std::unique_lock l2(mLock, std::defer_lock);
560 return addBindMount(*ifs, storage, std::move(source), path::normalize(target), kind, l2);
561}
562
563int IncrementalService::unbind(StorageId storage, std::string_view target) {
564 if (!path::isAbsolute(target)) {
565 return -EINVAL;
566 }
567
568 LOG(INFO) << "Removing bind point " << target;
569
570 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
571 // otherwise there's a chance to unmount something completely unrelated
572 const auto norm = path::normalize(target);
573 std::unique_lock l(mLock);
574 const auto storageIt = mBindsByPath.find(norm);
575 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
576 return -EINVAL;
577 }
578 const auto bindIt = storageIt->second;
579 const auto storageId = bindIt->second.storage;
580 const auto ifs = getIfsLocked(storageId);
581 if (!ifs) {
582 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
583 << " is missing";
584 return -EFAULT;
585 }
586 mBindsByPath.erase(storageIt);
587 l.unlock();
588
589 mVold->unmountIncFs(bindIt->first);
590 std::unique_lock l2(ifs->lock);
591 if (ifs->bindPoints.size() <= 1) {
592 ifs->bindPoints.clear();
593 deleteStorageLocked(*ifs, std::move(l2));
594 } else {
595 const std::string savedFile = std::move(bindIt->second.savedFilename);
596 ifs->bindPoints.erase(bindIt);
597 l2.unlock();
598 if (!savedFile.empty()) {
599 mIncFs->unlink(ifs->control, INCFS_ROOT_INODE, savedFile);
600 }
601 }
602 return 0;
603}
604
605Inode IncrementalService::makeFile(StorageId storageId, std::string_view pathUnderStorage,
606 long size, std::string_view metadata,
607 std::string_view signature) {
608 (void)signature;
609 auto [parentInode, name] = parentAndNameFor(storageId, pathUnderStorage);
610 if (parentInode < 0) {
611 return -EINVAL;
612 }
613 if (auto ifs = getIfs(storageId)) {
614 auto inode = mIncFs->makeFile(ifs->control, name, parentInode, size, metadata);
615 if (inode < 0) {
616 return inode;
617 }
618 auto metadataBytes = std::vector<uint8_t>();
619 if (metadata.data() != nullptr && metadata.size() > 0) {
620 metadataBytes.insert(metadataBytes.end(), &metadata.data()[0],
621 &metadata.data()[metadata.size()]);
622 }
623 mIncrementalManager->newFileForDataLoader(ifs->mountId, inode, metadataBytes);
624 return inode;
625 }
626 return -EINVAL;
627}
628
629Inode IncrementalService::makeDir(StorageId storageId, std::string_view pathUnderStorage,
630 std::string_view metadata) {
631 auto [parentInode, name] = parentAndNameFor(storageId, pathUnderStorage);
632 if (parentInode < 0) {
633 return -EINVAL;
634 }
635 if (auto ifs = getIfs(storageId)) {
636 return mIncFs->makeDir(ifs->control, name, parentInode, metadata);
637 }
638 return -EINVAL;
639}
640
641Inode IncrementalService::makeDirs(StorageId storageId, std::string_view pathUnderStorage,
642 std::string_view metadata) {
643 const auto ifs = getIfs(storageId);
644 if (!ifs) {
645 return -EINVAL;
646 }
647 std::string_view parentDir(pathUnderStorage);
648 auto p = parentAndNameFor(storageId, pathUnderStorage);
649 std::stack<std::string> pathsToCreate;
650 while (p.first < 0) {
651 parentDir = path::dirname(parentDir);
652 pathsToCreate.emplace(parentDir);
653 p = parentAndNameFor(storageId, parentDir);
654 }
655 Inode inode;
656 while (!pathsToCreate.empty()) {
657 p = parentAndNameFor(storageId, pathsToCreate.top());
658 pathsToCreate.pop();
659 inode = mIncFs->makeDir(ifs->control, p.second, p.first, metadata);
660 if (inode < 0) {
661 return inode;
662 }
663 }
664 return mIncFs->makeDir(ifs->control, path::basename(pathUnderStorage), inode, metadata);
665}
666
667int IncrementalService::link(StorageId storage, Inode item, Inode newParent,
668 std::string_view newName) {
669 if (auto ifs = getIfs(storage)) {
670 return mIncFs->link(ifs->control, item, newParent, newName);
671 }
672 return -EINVAL;
673}
674
675int IncrementalService::unlink(StorageId storage, Inode parent, std::string_view name) {
676 if (auto ifs = getIfs(storage)) {
677 return mIncFs->unlink(ifs->control, parent, name);
678 }
679 return -EINVAL;
680}
681
682int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage, std::string&& sourceSubdir,
683 std::string&& target, BindKind kind,
684 std::unique_lock<std::mutex>& mainLock) {
685 if (!isValidMountTarget(target)) {
686 return -EINVAL;
687 }
688
689 std::string mdFileName;
690 if (kind != BindKind::Temporary) {
691 metadata::BindPoint bp;
692 bp.set_storage_id(storage);
693 bp.set_allocated_dest_path(&target);
694 bp.set_allocated_source_subdir(&sourceSubdir);
695 const auto metadata = bp.SerializeAsString();
696 bp.release_source_subdir();
697 bp.release_dest_path();
698 mdFileName = makeBindMdName();
699 auto node = mIncFs->makeFile(ifs.control, mdFileName, INCFS_ROOT_INODE, 0, metadata);
700 if (node < 0) {
701 return int(node);
702 }
703 }
704
705 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(sourceSubdir),
706 std::move(target), kind, mainLock);
707}
708
709int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
710 std::string&& metadataName, std::string&& sourceSubdir,
711 std::string&& target, BindKind kind,
712 std::unique_lock<std::mutex>& mainLock) {
713 LOG(INFO) << "Adding bind mount: " << sourceSubdir << " -> " << target;
714 {
715 auto path = path::join(ifs.root, constants().mount, sourceSubdir);
716 std::lock_guard l(mMountOperationLock);
717 const auto status = mVold->bindMount(path, target);
718 if (!status.isOk()) {
719 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
720 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
721 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
722 : status.serviceSpecificErrorCode() == 0
723 ? -EFAULT
724 : status.serviceSpecificErrorCode()
725 : -EIO;
726 }
727 }
728
729 if (!mainLock.owns_lock()) {
730 mainLock.lock();
731 }
732 std::lock_guard l(ifs.lock);
733 const auto [it, _] =
734 ifs.bindPoints.insert_or_assign(target,
735 IncFsMount::Bind{storage, std::move(metadataName),
736 std::move(sourceSubdir), kind});
737 mBindsByPath[std::move(target)] = it;
738 return 0;
739}
740
741RawMetadata IncrementalService::getMetadata(StorageId storage, Inode node) const {
742 const auto ifs = getIfs(storage);
743 if (!ifs) {
744 return {};
745 }
746 return mIncFs->getMetadata(ifs->control, node);
747}
748
749std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
750 const auto ifs = getIfs(storage);
751 if (!ifs) {
752 return {};
753 }
754
755 std::unique_lock l(ifs->lock);
756 auto subdirIt = ifs->storages.find(storage);
757 if (subdirIt == ifs->storages.end()) {
758 return {};
759 }
760 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
761 l.unlock();
762
763 const auto prefixSize = dir.size() + 1;
764 std::vector<std::string> todoDirs{std::move(dir)};
765 std::vector<std::string> result;
766 do {
767 auto currDir = std::move(todoDirs.back());
768 todoDirs.pop_back();
769
770 auto d =
771 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
772 while (auto e = ::readdir(d.get())) {
773 if (e->d_type == DT_REG) {
774 result.emplace_back(
775 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
776 continue;
777 }
778 if (e->d_type == DT_DIR) {
779 if (e->d_name == "."sv || e->d_name == ".."sv) {
780 continue;
781 }
782 todoDirs.emplace_back(path::join(currDir, e->d_name));
783 continue;
784 }
785 }
786 } while (!todoDirs.empty());
787 return result;
788}
789
790bool IncrementalService::startLoading(StorageId storage) const {
791 const auto ifs = getIfs(storage);
792 if (!ifs) {
793 return false;
794 }
795 bool started = false;
796 std::unique_lock l(ifs->lock);
797 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_READY) {
798 if (ifs->dataLoaderReady.wait_for(l, Seconds(5)) == std::cv_status::timeout) {
799 LOG(ERROR) << "Timeout waiting for data loader to be ready";
800 return false;
801 }
802 }
803 auto status = mIncrementalManager->startDataLoader(ifs->mountId, &started);
804 if (!status.isOk()) {
805 return false;
806 }
807 return started;
808}
809
810void IncrementalService::mountExistingImages() {
811 auto d = std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(mIncrementalDir.c_str()),
812 ::closedir);
813 while (auto e = ::readdir(d.get())) {
814 if (e->d_type != DT_DIR) {
815 continue;
816 }
817 if (e->d_name == "."sv || e->d_name == ".."sv) {
818 continue;
819 }
820 auto root = path::join(mIncrementalDir, e->d_name);
821 if (!mountExistingImage(root, e->d_name)) {
822 IncFsMount::cleanupFilesystem(root);
823 }
824 }
825}
826
827bool IncrementalService::mountExistingImage(std::string_view root, std::string_view key) {
828 LOG(INFO) << "Trying to mount: " << key;
829
830 auto mountTarget = path::join(root, constants().mount);
831 const auto image = path::join(root, constants().backing, constants().image);
832
833 IncFsMount::Control control;
834 IncrementalFileSystemControlParcel controlParcel;
835 auto status = mVold->mountIncFs(image, mountTarget, 0, &controlParcel);
836 if (!status.isOk()) {
837 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
838 return false;
839 }
840 if (controlParcel.cmd) {
841 control.cmdFd = controlParcel.cmd->release();
842 }
843 if (controlParcel.log) {
844 control.logFd = controlParcel.log->release();
845 }
846
847 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
848
849 auto m = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
850 path::join(mountTarget, constants().infoMdName));
851 if (!m.has_loader() || !m.has_storage()) {
852 LOG(ERROR) << "Bad mount metadata in mount at " << root;
853 return false;
854 }
855
856 ifs->mountId = m.storage().id();
857 mNextId = std::max(mNextId, ifs->mountId + 1);
858
859 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
860 auto d = std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(path::c_str(mountTarget)),
861 ::closedir);
862 while (auto e = ::readdir(d.get())) {
863 if (e->d_type == DT_REG) {
864 auto name = std::string_view(e->d_name);
865 if (name.starts_with(constants().mountpointMdPrefix)) {
866 bindPoints.emplace_back(name,
867 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
868 ifs->control,
869 path::join(mountTarget,
870 name)));
871 if (bindPoints.back().second.dest_path().empty() ||
872 bindPoints.back().second.source_subdir().empty()) {
873 bindPoints.pop_back();
874 mIncFs->unlink(ifs->control, INCFS_ROOT_INODE, name);
875 }
876 }
877 } else if (e->d_type == DT_DIR) {
878 if (e->d_name == "."sv || e->d_name == ".."sv) {
879 continue;
880 }
881 auto name = std::string_view(e->d_name);
882 if (name.starts_with(constants().storagePrefix)) {
883 auto md = parseFromIncfs<metadata::Storage>(mIncFs.get(), ifs->control,
884 path::join(mountTarget, name));
885 auto [_, inserted] = mMounts.try_emplace(md.id(), ifs);
886 if (!inserted) {
887 LOG(WARNING) << "Ignoring storage with duplicate id " << md.id()
888 << " for mount " << root;
889 continue;
890 }
891 ifs->storages.insert_or_assign(md.id(),
892 IncFsMount::Storage{std::string(name),
893 Inode(e->d_ino)});
894 mNextId = std::max(mNextId, md.id() + 1);
895 }
896 }
897 }
898
899 if (ifs->storages.empty()) {
900 LOG(WARNING) << "No valid storages in mount " << root;
901 return false;
902 }
903
904 int bindCount = 0;
905 for (auto&& bp : bindPoints) {
906 std::unique_lock l(mLock, std::defer_lock);
907 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
908 std::move(*bp.second.mutable_source_subdir()),
909 std::move(*bp.second.mutable_dest_path()),
910 BindKind::Permanent, l);
911 }
912
913 if (bindCount == 0) {
914 LOG(WARNING) << "No valid bind points for mount " << root;
915 deleteStorage(*ifs);
916 return false;
917 }
918
919 DataLoaderParamsParcel dlParams;
920 dlParams.packageName = std::move(*m.mutable_loader()->mutable_package_name());
921 dlParams.staticArgs = std::move(*m.mutable_loader()->mutable_arguments());
922 if (!prepareDataLoader(*ifs, &dlParams)) {
923 deleteStorage(*ifs);
924 return false;
925 }
926
927 mMounts[ifs->mountId] = std::move(ifs);
928 return true;
929}
930
931bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
932 DataLoaderParamsParcel* params) {
933 if (!mSystemReady.load(std::memory_order_relaxed)) {
934 std::unique_lock l(ifs.lock);
935 if (params) {
936 if (ifs.savedDataLoaderParams) {
937 LOG(WARNING) << "Trying to pass second set of data loader parameters, ignored it";
938 } else {
939 ifs.savedDataLoaderParams = std::move(*params);
940 }
941 } else {
942 if (!ifs.savedDataLoaderParams) {
943 LOG(ERROR) << "Mount " << ifs.mountId
944 << " is broken: no data loader params (system is not ready yet)";
945 return false;
946 }
947 }
948 return true; // eventually...
949 }
950 if (base::GetBoolProperty("incremental.skip_loader", false)) {
951 LOG(INFO) << "Skipped data loader because of incremental.skip_loader property";
952 std::unique_lock l(ifs.lock);
953 ifs.savedDataLoaderParams.reset();
954 return true;
955 }
956
957 std::unique_lock l(ifs.lock);
958 if (ifs.dataLoaderStatus == IDataLoaderStatusListener::DATA_LOADER_READY) {
959 LOG(INFO) << "Skipped data loader preparation because it already exists";
960 return true;
961 }
962
963 auto* dlp = params ? params
964 : ifs.savedDataLoaderParams ? &ifs.savedDataLoaderParams.value() : nullptr;
965 if (!dlp) {
966 LOG(ERROR) << "Mount " << ifs.mountId << " is broken: no data loader params";
967 return false;
968 }
969 FileSystemControlParcel fsControlParcel;
970 fsControlParcel.incremental = std::make_unique<IncrementalFileSystemControlParcel>();
971 fsControlParcel.incremental->cmd =
972 std::make_unique<os::ParcelFileDescriptor>(base::unique_fd(::dup(ifs.control.cmdFd)));
973 fsControlParcel.incremental->log =
974 std::make_unique<os::ParcelFileDescriptor>(base::unique_fd(::dup(ifs.control.logFd)));
975 sp<IncrementalDataLoaderListener> listener = new IncrementalDataLoaderListener(*this);
976 bool created = false;
977 auto status = mIncrementalManager->prepareDataLoader(ifs.mountId, fsControlParcel, *dlp,
978 listener, &created);
979 if (!status.isOk() || !created) {
980 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
981 return false;
982 }
983 ifs.savedDataLoaderParams.reset();
984 return true;
985}
986
987binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
988 int newStatus) {
989 std::unique_lock l(incrementalService.mLock);
990 const auto& ifs = incrementalService.getIfsLocked(mountId);
991 if (!ifs) {
992 LOG(WARNING) << "Received data loader status " << int(newStatus) << " for unknown mount "
993 << mountId;
994 return binder::Status::ok();
995 }
996 ifs->dataLoaderStatus = newStatus;
997 switch (newStatus) {
998 case IDataLoaderStatusListener::DATA_LOADER_NO_CONNECTION: {
999 auto now = Clock::now();
1000 if (ifs->connectionLostTime.time_since_epoch().count() == 0) {
1001 ifs->connectionLostTime = now;
1002 break;
1003 }
1004 auto duration =
1005 std::chrono::duration_cast<Seconds>(now - ifs->connectionLostTime).count();
1006 if (duration >= 10) {
1007 incrementalService.mIncrementalManager->showHealthBlockedUI(mountId);
1008 }
1009 break;
1010 }
1011 case IDataLoaderStatusListener::DATA_LOADER_READY: {
1012 ifs->dataLoaderReady.notify_one();
1013 break;
1014 }
1015 case IDataLoaderStatusListener::DATA_LOADER_NOT_READY: {
1016 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1017 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1018 break;
1019 }
1020 case IDataLoaderStatusListener::DATA_LOADER_RUNNING: {
1021 break;
1022 }
1023 case IDataLoaderStatusListener::DATA_LOADER_CONNECTION_OK: {
1024 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_RUNNING;
1025 break;
1026 }
1027 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1028 break;
1029 }
1030 default: {
1031 LOG(WARNING) << "Unknown data loader status: " << newStatus
1032 << " for mount: " << mountId;
1033 break;
1034 }
1035 }
1036
1037 return binder::Status::ok();
1038}
1039
1040} // namespace android::incremental