blob: f3c48f7f9fc84a69c4d080065084e7e52263350c [file] [log] [blame]
Ryan Mitchell1a48fa62021-01-10 08:36:36 -08001/*
2 * Copyright (C) 2021 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 "androidfw/AssetsProvider.h"
18
19#include <sys/stat.h>
20
21#include <android-base/errors.h>
22#include <android-base/stringprintf.h>
23#include <android-base/utf8.h>
24#include <ziparchive/zip_archive.h>
25
26namespace android {
27namespace {
28constexpr const char* kEmptyDebugString = "<empty>";
29} // namespace
30
31std::unique_ptr<Asset> AssetsProvider::Open(const std::string& path, Asset::AccessMode mode,
32 bool* file_exists) const {
33 return OpenInternal(path, mode, file_exists);
34}
35
36std::unique_ptr<Asset> AssetsProvider::CreateAssetFromFile(const std::string& path) {
37 base::unique_fd fd(base::utf8::open(path.c_str(), O_RDONLY | O_CLOEXEC));
38 if (!fd.ok()) {
39 LOG(ERROR) << "Failed to open file '" << path << "': " << base::SystemErrorCodeToString(errno);
40 return {};
41 }
42
43 return CreateAssetFromFd(std::move(fd), path.c_str());
44}
45
46std::unique_ptr<Asset> AssetsProvider::CreateAssetFromFd(base::unique_fd fd,
47 const char* path,
48 off64_t offset,
49 off64_t length) {
50 CHECK(length >= kUnknownLength) << "length must be greater than or equal to " << kUnknownLength;
51 CHECK(length != kUnknownLength || offset == 0) << "offset must be 0 if length is "
52 << kUnknownLength;
53 if (length == kUnknownLength) {
54 length = lseek64(fd, 0, SEEK_END);
55 if (length < 0) {
56 LOG(ERROR) << "Failed to get size of file '" << ((path) ? path : "anon") << "': "
57 << base::SystemErrorCodeToString(errno);
58 return {};
59 }
60 }
61
62 incfs::IncFsFileMap file_map;
63 if (!file_map.Create(fd, offset, static_cast<size_t>(length), path)) {
64 LOG(ERROR) << "Failed to mmap file '" << ((path != nullptr) ? path : "anon") << "': "
65 << base::SystemErrorCodeToString(errno);
66 return {};
67 }
68
69 // If `path` is set, do not pass ownership of the `fd` to the new Asset since
70 // Asset::openFileDescriptor can use `path` to create new file descriptors.
71 return Asset::createFromUncompressedMap(std::move(file_map),
72 Asset::AccessMode::ACCESS_RANDOM,
73 (path != nullptr) ? base::unique_fd(-1) : std::move(fd));
74}
75
76ZipAssetsProvider::PathOrDebugName::PathOrDebugName(std::string&& value, bool is_path)
77 : value_(std::forward<std::string>(value)), is_path_(is_path) {}
78
79const std::string* ZipAssetsProvider::PathOrDebugName::GetPath() const {
80 return is_path_ ? &value_ : nullptr;
81}
82
83const std::string& ZipAssetsProvider::PathOrDebugName::GetDebugName() const {
84 return value_;
85}
86
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -080087ZipAssetsProvider::ZipAssetsProvider(ZipArchiveHandle handle, PathOrDebugName&& path,
Ryan Mitchell1a48fa62021-01-10 08:36:36 -080088 time_t last_mod_time)
89 : zip_handle_(handle, ::CloseArchive),
90 name_(std::forward<PathOrDebugName>(path)),
91 last_mod_time_(last_mod_time) {}
92
93std::unique_ptr<ZipAssetsProvider> ZipAssetsProvider::Create(std::string path) {
94 ZipArchiveHandle handle;
95 if (int32_t result = OpenArchive(path.c_str(), &handle); result != 0) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -080096 LOG(ERROR) << "Failed to open APK '" << path << "': " << ::ErrorCodeString(result);
Ryan Mitchell1a48fa62021-01-10 08:36:36 -080097 CloseArchive(handle);
98 return {};
99 }
100
101 struct stat sb{.st_mtime = -1};
102 if (stat(path.c_str(), &sb) < 0) {
103 // Stat requires execute permissions on all directories path to the file. If the process does
104 // not have execute permissions on this file, allow the zip to be opened but IsUpToDate() will
105 // always have to return true.
106 LOG(WARNING) << "Failed to stat file '" << path << "': "
107 << base::SystemErrorCodeToString(errno);
108 }
109
110 return std::unique_ptr<ZipAssetsProvider>(
111 new ZipAssetsProvider(handle, PathOrDebugName{std::move(path),
112 true /* is_path */}, sb.st_mtime));
113}
114
115std::unique_ptr<ZipAssetsProvider> ZipAssetsProvider::Create(base::unique_fd fd,
116 std::string friendly_name,
117 off64_t offset,
118 off64_t len) {
119 ZipArchiveHandle handle;
120 const int released_fd = fd.release();
121 const int32_t result = (len == AssetsProvider::kUnknownLength)
122 ? ::OpenArchiveFd(released_fd, friendly_name.c_str(), &handle)
123 : ::OpenArchiveFdRange(released_fd, friendly_name.c_str(), &handle, len, offset);
124
125 if (result != 0) {
126 LOG(ERROR) << "Failed to open APK '" << friendly_name << "' through FD with offset " << offset
127 << " and length " << len << ": " << ::ErrorCodeString(result);
128 CloseArchive(handle);
129 return {};
130 }
131
132 struct stat sb{.st_mtime = -1};
133 if (fstat(released_fd, &sb) < 0) {
134 // Stat requires execute permissions on all directories path to the file. If the process does
135 // not have execute permissions on this file, allow the zip to be opened but IsUpToDate() will
136 // always have to return true.
137 LOG(WARNING) << "Failed to fstat file '" << friendly_name << "': "
138 << base::SystemErrorCodeToString(errno);
139 }
140
141 return std::unique_ptr<ZipAssetsProvider>(
142 new ZipAssetsProvider(handle, PathOrDebugName{std::move(friendly_name),
143 false /* is_path */}, sb.st_mtime));
144}
145
146std::unique_ptr<Asset> ZipAssetsProvider::OpenInternal(const std::string& path,
147 Asset::AccessMode mode,
148 bool* file_exists) const {
149 if (file_exists != nullptr) {
150 *file_exists = false;
151 }
152
153 ZipEntry entry;
154 if (FindEntry(zip_handle_.get(), path, &entry) != 0) {
155 return {};
156 }
157
158 if (file_exists != nullptr) {
159 *file_exists = true;
160 }
161
162 const int fd = GetFileDescriptor(zip_handle_.get());
163 const off64_t fd_offset = GetFileDescriptorOffset(zip_handle_.get());
164 incfs::IncFsFileMap asset_map;
165 if (entry.method == kCompressDeflated) {
166 if (!asset_map.Create(fd, entry.offset + fd_offset, entry.compressed_length,
167 name_.GetDebugName().c_str())) {
168 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName()
169 << "'";
170 return {};
171 }
172
173 std::unique_ptr<Asset> asset =
174 Asset::createFromCompressedMap(std::move(asset_map), entry.uncompressed_length, mode);
175 if (asset == nullptr) {
176 LOG(ERROR) << "Failed to decompress '" << path << "' in APK '" << name_.GetDebugName()
177 << "'";
178 return {};
179 }
180 return asset;
181 }
182
183 if (!asset_map.Create(fd, entry.offset + fd_offset, entry.uncompressed_length,
184 name_.GetDebugName().c_str())) {
185 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName() << "'";
186 return {};
187 }
188
189 base::unique_fd ufd;
190 if (name_.GetPath() == nullptr) {
191 // If the zip name does not represent a path, create a new `fd` for the new Asset to own in
192 // order to create new file descriptors using Asset::openFileDescriptor. If the zip name is a
193 // path, it will be used to create new file descriptors.
194 ufd = base::unique_fd(dup(fd));
195 if (!ufd.ok()) {
196 LOG(ERROR) << "Unable to dup fd '" << path << "' in APK '" << name_.GetDebugName() << "'";
197 return {};
198 }
199 }
200
201 auto asset = Asset::createFromUncompressedMap(std::move(asset_map), mode, std::move(ufd));
202 if (asset == nullptr) {
203 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName() << "'";
204 return {};
205 }
206 return asset;
207}
208
209bool ZipAssetsProvider::ForEachFile(const std::string& root_path,
210 const std::function<void(const StringPiece&, FileType)>& f)
211 const {
212 std::string root_path_full = root_path;
213 if (root_path_full.back() != '/') {
214 root_path_full += '/';
215 }
216
217 void* cookie;
218 if (StartIteration(zip_handle_.get(), &cookie, root_path_full, "") != 0) {
219 return false;
220 }
221
222 std::string name;
223 ::ZipEntry entry{};
224
225 // We need to hold back directories because many paths will contain them and we want to only
226 // surface one.
227 std::set<std::string> dirs{};
228
229 int32_t result;
230 while ((result = Next(cookie, &entry, &name)) == 0) {
231 StringPiece full_file_path(name);
232 StringPiece leaf_file_path = full_file_path.substr(root_path_full.size());
233
234 if (!leaf_file_path.empty()) {
235 auto iter = std::find(leaf_file_path.begin(), leaf_file_path.end(), '/');
236 if (iter != leaf_file_path.end()) {
237 std::string dir =
238 leaf_file_path.substr(0, std::distance(leaf_file_path.begin(), iter)).to_string();
239 dirs.insert(std::move(dir));
240 } else {
241 f(leaf_file_path, kFileTypeRegular);
242 }
243 }
244 }
245 EndIteration(cookie);
246
247 // Now present the unique directories.
248 for (const std::string& dir : dirs) {
249 f(dir, kFileTypeDirectory);
250 }
251
252 // -1 is end of iteration, anything else is an error.
253 return result == -1;
254}
255
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800256std::optional<uint32_t> ZipAssetsProvider::GetCrc(std::string_view path) const {
257 ::ZipEntry entry;
258 if (FindEntry(zip_handle_.get(), path, &entry) != 0) {
259 return {};
260 }
261 return entry.crc32;
262}
263
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800264const std::string& ZipAssetsProvider::GetDebugName() const {
265 return name_.GetDebugName();
266}
267
268bool ZipAssetsProvider::IsUpToDate() const {
269 struct stat sb{};
270 if (fstat(GetFileDescriptor(zip_handle_.get()), &sb) < 0) {
271 // If fstat fails on the zip archive, return true so the zip archive the resource system does
272 // attempt to refresh the ApkAsset.
273 return true;
274 }
275 return last_mod_time_ == sb.st_mtime;
276}
277
278DirectoryAssetsProvider::DirectoryAssetsProvider(std::string&& path, time_t last_mod_time)
279 : dir_(std::forward<std::string>(path)), last_mod_time_(last_mod_time) {}
280
281std::unique_ptr<DirectoryAssetsProvider> DirectoryAssetsProvider::Create(std::string path) {
282 struct stat sb{};
283 const int result = stat(path.c_str(), &sb);
284 if (result == -1) {
285 LOG(ERROR) << "Failed to find directory '" << path << "'.";
286 return nullptr;
287 }
288
289 if (!S_ISDIR(sb.st_mode)) {
290 LOG(ERROR) << "Path '" << path << "' is not a directory.";
291 return nullptr;
292 }
293
294 if (path[path.size() - 1] != OS_PATH_SEPARATOR) {
295 path += OS_PATH_SEPARATOR;
296 }
297
298 return std::unique_ptr<DirectoryAssetsProvider>(new DirectoryAssetsProvider(std::move(path),
299 sb.st_mtime));
300}
301
302std::unique_ptr<Asset> DirectoryAssetsProvider::OpenInternal(const std::string& path,
303 Asset::AccessMode /* mode */,
304 bool* file_exists) const {
305 const std::string resolved_path = dir_ + path;
306 if (file_exists != nullptr) {
307 struct stat sb{};
308 *file_exists = (stat(resolved_path.c_str(), &sb) != -1) && S_ISREG(sb.st_mode);
309 }
310
311 return CreateAssetFromFile(resolved_path);
312}
313
314bool DirectoryAssetsProvider::ForEachFile(
315 const std::string& /* root_path */,
316 const std::function<void(const StringPiece&, FileType)>& /* f */)
317 const {
318 return true;
319}
320
321const std::string& DirectoryAssetsProvider::GetDebugName() const {
322 return dir_;
323}
324
325bool DirectoryAssetsProvider::IsUpToDate() const {
326 struct stat sb{};
327 if (stat(dir_.c_str(), &sb) < 0) {
328 // If stat fails on the zip archive, return true so the zip archive the resource system does
329 // attempt to refresh the ApkAsset.
330 return true;
331 }
332 return last_mod_time_ == sb.st_mtime;
333}
334
335MultiAssetsProvider::MultiAssetsProvider(std::unique_ptr<AssetsProvider>&& primary,
336 std::unique_ptr<AssetsProvider>&& secondary)
337 : primary_(std::forward<std::unique_ptr<AssetsProvider>>(primary)),
338 secondary_(std::forward<std::unique_ptr<AssetsProvider>>(secondary)) {
339 if (primary_->GetDebugName() == kEmptyDebugString) {
340 debug_name_ = secondary_->GetDebugName();
341 } else if (secondary_->GetDebugName() == kEmptyDebugString) {
342 debug_name_ = primary_->GetDebugName();
343 } else {
344 debug_name_ = primary_->GetDebugName() + " and " + secondary_->GetDebugName();
345 }
346}
347
348std::unique_ptr<AssetsProvider> MultiAssetsProvider::Create(
349 std::unique_ptr<AssetsProvider>&& primary, std::unique_ptr<AssetsProvider>&& secondary) {
350 if (primary == nullptr || secondary == nullptr) {
351 return nullptr;
352 }
353 return std::unique_ptr<MultiAssetsProvider>(new MultiAssetsProvider(std::move(primary),
354 std::move(secondary)));
355}
356
357std::unique_ptr<Asset> MultiAssetsProvider::OpenInternal(const std::string& path,
358 Asset::AccessMode mode,
359 bool* file_exists) const {
360 auto asset = primary_->Open(path, mode, file_exists);
361 return (asset) ? std::move(asset) : secondary_->Open(path, mode, file_exists);
362}
363
364bool MultiAssetsProvider::ForEachFile(const std::string& root_path,
365 const std::function<void(const StringPiece&, FileType)>& f)
366 const {
367 return primary_->ForEachFile(root_path, f) && secondary_->ForEachFile(root_path, f);
368}
369
370const std::string& MultiAssetsProvider::GetDebugName() const {
371 return debug_name_;
372}
373
374bool MultiAssetsProvider::IsUpToDate() const {
375 return primary_->IsUpToDate() && secondary_->IsUpToDate();
376}
377
378std::unique_ptr<AssetsProvider> EmptyAssetsProvider::Create() {
379 return std::make_unique<EmptyAssetsProvider>();
380}
381
382std::unique_ptr<Asset> EmptyAssetsProvider::OpenInternal(const std::string& /* path */,
383 Asset::AccessMode /* mode */,
384 bool* file_exists) const {
385 if (file_exists) {
386 *file_exists = false;
387 }
388 return nullptr;
389}
390
391bool EmptyAssetsProvider::ForEachFile(
392 const std::string& /* root_path */,
393 const std::function<void(const StringPiece&, FileType)>& /* f */) const {
394 return true;
395}
396
397const std::string& EmptyAssetsProvider::GetDebugName() const {
398 const static std::string kEmpty = kEmptyDebugString;
399 return kEmpty;
400}
401
402bool EmptyAssetsProvider::IsUpToDate() const {
403 return true;
404}
405
406} // namespace android