1 /*
2  * Copyright (C) 2020 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 #include <vintf/HostFileSystem.h>
18 
19 #include <android-base/logging.h>
20 #include <android-base/strings.h>
21 
22 namespace android::vintf::details {
23 
24 HostFileSystem::HostFileSystem(const Dirmap& dirmap, status_t missingError)
25     : HostFileSystem(dirmap, missingError, std::make_unique<FileSystemImpl>()) {}
26 
27 HostFileSystem::HostFileSystem(const Dirmap& dirmap, status_t missingError,
28                                std::unique_ptr<FileSystem>&& impl)
29     : HostFileSystem(dirmap, missingError, impl.get()) {
30     mImplUniq = std::move(impl);
31 }
32 
33 HostFileSystem::HostFileSystem(const Dirmap& dirmap, status_t missingError, FileSystem* impl)
34     : mDirMap(dirmap), mMissingError(missingError), mImpl(impl) {}
35 
36 status_t HostFileSystem::fetch(const std::string& path, std::string* fetched,
37                                std::string* error) const {
38     auto resolved = resolve(path, error);
39     if (resolved.empty()) {
40         return mMissingError;
41     }
42     status_t status = mImpl->fetch(resolved, fetched, error);
43     LOG(INFO) << "Fetch '" << resolved << "': " << statusToString(status);
44     return status;
45 }
46 
47 status_t HostFileSystem::listFiles(const std::string& path, std::vector<std::string>* out,
48                                    std::string* error) const {
49     auto resolved = resolve(path, error);
50     if (resolved.empty()) {
51         return mMissingError;
52     }
53     status_t status = mImpl->listFiles(resolved, out, error);
54     LOG(INFO) << "List '" << resolved << "': " << statusToString(status);
55     return status;
56 }
57 
58 std::string HostFileSystem::resolve(const std::string& path, std::string* error) const {
59     for (auto [prefix, mappedPath] : mDirMap) {
60         if (path == prefix) {
61             return mappedPath;
62         }
63         if (android::base::StartsWith(path, prefix + "/")) {
64             return mappedPath + "/" + path.substr(prefix.size() + 1);
65         }
66     }
67     if (error) {
68         *error = "Cannot resolve path " + path;
69     } else {
70         LOG(mMissingError == NAME_NOT_FOUND ? INFO : ERROR) << "Cannot resolve path " << path;
71     }
72     return "";
73 }
74 
75 }  // namespace android::vintf::details
76