blob: b9264c5d0f2dddc2b5f74c1ed1567d784f8a2085 [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 Mitchellc0416692021-05-11 12:21:29 -070088 package_property_t flags, time_t last_mod_time)
Ryan Mitchell1a48fa62021-01-10 08:36:36 -080089 : zip_handle_(handle, ::CloseArchive),
90 name_(std::forward<PathOrDebugName>(path)),
Ryan Mitchellc0416692021-05-11 12:21:29 -070091 flags_(flags),
Ryan Mitchell1a48fa62021-01-10 08:36:36 -080092 last_mod_time_(last_mod_time) {}
93
Ryan Mitchellc0416692021-05-11 12:21:29 -070094std::unique_ptr<ZipAssetsProvider> ZipAssetsProvider::Create(std::string path,
Yurii Zubrytskyi801c4412022-11-30 16:47:23 -080095 package_property_t flags,
96 base::unique_fd fd) {
97 const auto released_fd = fd.ok() ? fd.release() : -1;
Ryan Mitchell1a48fa62021-01-10 08:36:36 -080098 ZipArchiveHandle handle;
Yurii Zubrytskyi801c4412022-11-30 16:47:23 -080099 if (int32_t result = released_fd < 0 ? OpenArchive(path.c_str(), &handle)
100 : OpenArchiveFd(released_fd, path.c_str(), &handle)) {
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800101 LOG(ERROR) << "Failed to open APK '" << path << "': " << ::ErrorCodeString(result);
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800102 CloseArchive(handle);
103 return {};
104 }
105
106 struct stat sb{.st_mtime = -1};
Yurii Zubrytskyi2ab44472022-11-30 00:56:22 -0800107 // Skip all up-to-date checks if the file won't ever change.
108 if (!isReadonlyFilesystem(path.c_str())) {
109 if ((released_fd < 0 ? stat(path.c_str(), &sb) : fstat(released_fd, &sb)) < 0) {
110 // Stat requires execute permissions on all directories path to the file. If the process does
111 // not have execute permissions on this file, allow the zip to be opened but IsUpToDate() will
112 // always have to return true.
113 LOG(WARNING) << "Failed to stat file '" << path << "': "
114 << base::SystemErrorCodeToString(errno);
115 }
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800116 }
117
118 return std::unique_ptr<ZipAssetsProvider>(
119 new ZipAssetsProvider(handle, PathOrDebugName{std::move(path),
Ryan Mitchellc0416692021-05-11 12:21:29 -0700120 true /* is_path */}, flags, sb.st_mtime));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800121}
122
123std::unique_ptr<ZipAssetsProvider> ZipAssetsProvider::Create(base::unique_fd fd,
124 std::string friendly_name,
Ryan Mitchellc0416692021-05-11 12:21:29 -0700125 package_property_t flags,
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800126 off64_t offset,
127 off64_t len) {
128 ZipArchiveHandle handle;
129 const int released_fd = fd.release();
130 const int32_t result = (len == AssetsProvider::kUnknownLength)
131 ? ::OpenArchiveFd(released_fd, friendly_name.c_str(), &handle)
132 : ::OpenArchiveFdRange(released_fd, friendly_name.c_str(), &handle, len, offset);
133
134 if (result != 0) {
135 LOG(ERROR) << "Failed to open APK '" << friendly_name << "' through FD with offset " << offset
136 << " and length " << len << ": " << ::ErrorCodeString(result);
137 CloseArchive(handle);
138 return {};
139 }
140
141 struct stat sb{.st_mtime = -1};
Yurii Zubrytskyi2ab44472022-11-30 00:56:22 -0800142 // Skip all up-to-date checks if the file won't ever change.
143 if (!isReadonlyFilesystem(released_fd)) {
144 if (fstat(released_fd, &sb) < 0) {
145 // Stat requires execute permissions on all directories path to the file. If the process does
146 // not have execute permissions on this file, allow the zip to be opened but IsUpToDate() will
147 // always have to return true.
148 LOG(WARNING) << "Failed to fstat file '" << friendly_name
149 << "': " << base::SystemErrorCodeToString(errno);
150 }
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800151 }
152
153 return std::unique_ptr<ZipAssetsProvider>(
154 new ZipAssetsProvider(handle, PathOrDebugName{std::move(friendly_name),
Ryan Mitchellc0416692021-05-11 12:21:29 -0700155 false /* is_path */}, flags, sb.st_mtime));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800156}
157
158std::unique_ptr<Asset> ZipAssetsProvider::OpenInternal(const std::string& path,
159 Asset::AccessMode mode,
160 bool* file_exists) const {
161 if (file_exists != nullptr) {
162 *file_exists = false;
163 }
164
165 ZipEntry entry;
166 if (FindEntry(zip_handle_.get(), path, &entry) != 0) {
167 return {};
168 }
169
170 if (file_exists != nullptr) {
171 *file_exists = true;
172 }
173
174 const int fd = GetFileDescriptor(zip_handle_.get());
175 const off64_t fd_offset = GetFileDescriptorOffset(zip_handle_.get());
Ryan Mitchellc0416692021-05-11 12:21:29 -0700176 const bool incremental_hardening = (flags_ & PROPERTY_DISABLE_INCREMENTAL_HARDENING) == 0U;
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800177 incfs::IncFsFileMap asset_map;
178 if (entry.method == kCompressDeflated) {
179 if (!asset_map.Create(fd, entry.offset + fd_offset, entry.compressed_length,
Ryan Mitchellc0416692021-05-11 12:21:29 -0700180 name_.GetDebugName().c_str(), incremental_hardening)) {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800181 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName()
182 << "'";
183 return {};
184 }
185
186 std::unique_ptr<Asset> asset =
187 Asset::createFromCompressedMap(std::move(asset_map), entry.uncompressed_length, mode);
188 if (asset == nullptr) {
189 LOG(ERROR) << "Failed to decompress '" << path << "' in APK '" << name_.GetDebugName()
190 << "'";
191 return {};
192 }
193 return asset;
194 }
195
196 if (!asset_map.Create(fd, entry.offset + fd_offset, entry.uncompressed_length,
Ryan Mitchellc0416692021-05-11 12:21:29 -0700197 name_.GetDebugName().c_str(), incremental_hardening)) {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800198 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName() << "'";
199 return {};
200 }
201
202 base::unique_fd ufd;
203 if (name_.GetPath() == nullptr) {
204 // If the zip name does not represent a path, create a new `fd` for the new Asset to own in
205 // order to create new file descriptors using Asset::openFileDescriptor. If the zip name is a
206 // path, it will be used to create new file descriptors.
207 ufd = base::unique_fd(dup(fd));
208 if (!ufd.ok()) {
209 LOG(ERROR) << "Unable to dup fd '" << path << "' in APK '" << name_.GetDebugName() << "'";
210 return {};
211 }
212 }
213
214 auto asset = Asset::createFromUncompressedMap(std::move(asset_map), mode, std::move(ufd));
215 if (asset == nullptr) {
216 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName() << "'";
217 return {};
218 }
219 return asset;
220}
221
222bool ZipAssetsProvider::ForEachFile(const std::string& root_path,
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700223 const std::function<void(StringPiece, FileType)>& f) const {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800224 std::string root_path_full = root_path;
225 if (root_path_full.back() != '/') {
226 root_path_full += '/';
227 }
228
229 void* cookie;
230 if (StartIteration(zip_handle_.get(), &cookie, root_path_full, "") != 0) {
231 return false;
232 }
233
234 std::string name;
235 ::ZipEntry entry{};
236
237 // We need to hold back directories because many paths will contain them and we want to only
238 // surface one.
239 std::set<std::string> dirs{};
240
241 int32_t result;
242 while ((result = Next(cookie, &entry, &name)) == 0) {
243 StringPiece full_file_path(name);
244 StringPiece leaf_file_path = full_file_path.substr(root_path_full.size());
245
246 if (!leaf_file_path.empty()) {
247 auto iter = std::find(leaf_file_path.begin(), leaf_file_path.end(), '/');
248 if (iter != leaf_file_path.end()) {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700249 std::string dir(leaf_file_path.substr(0, std::distance(leaf_file_path.begin(), iter)));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800250 dirs.insert(std::move(dir));
251 } else {
252 f(leaf_file_path, kFileTypeRegular);
253 }
254 }
255 }
256 EndIteration(cookie);
257
258 // Now present the unique directories.
259 for (const std::string& dir : dirs) {
260 f(dir, kFileTypeDirectory);
261 }
262
263 // -1 is end of iteration, anything else is an error.
264 return result == -1;
265}
266
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800267std::optional<uint32_t> ZipAssetsProvider::GetCrc(std::string_view path) const {
268 ::ZipEntry entry;
269 if (FindEntry(zip_handle_.get(), path, &entry) != 0) {
270 return {};
271 }
272 return entry.crc32;
273}
274
Ryan Mitchellef538432021-03-01 14:52:14 -0800275std::optional<std::string_view> ZipAssetsProvider::GetPath() const {
276 if (name_.GetPath() != nullptr) {
277 return *name_.GetPath();
278 }
279 return {};
280}
281
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800282const std::string& ZipAssetsProvider::GetDebugName() const {
283 return name_.GetDebugName();
284}
285
286bool ZipAssetsProvider::IsUpToDate() const {
Yurii Zubrytskyi2ab44472022-11-30 00:56:22 -0800287 if (last_mod_time_ == -1) {
288 return true;
289 }
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800290 struct stat sb{};
291 if (fstat(GetFileDescriptor(zip_handle_.get()), &sb) < 0) {
292 // If fstat fails on the zip archive, return true so the zip archive the resource system does
293 // attempt to refresh the ApkAsset.
294 return true;
295 }
296 return last_mod_time_ == sb.st_mtime;
297}
298
299DirectoryAssetsProvider::DirectoryAssetsProvider(std::string&& path, time_t last_mod_time)
300 : dir_(std::forward<std::string>(path)), last_mod_time_(last_mod_time) {}
301
302std::unique_ptr<DirectoryAssetsProvider> DirectoryAssetsProvider::Create(std::string path) {
Yurii Zubrytskyi2ab44472022-11-30 00:56:22 -0800303 struct stat sb;
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800304 const int result = stat(path.c_str(), &sb);
305 if (result == -1) {
306 LOG(ERROR) << "Failed to find directory '" << path << "'.";
307 return nullptr;
308 }
309
310 if (!S_ISDIR(sb.st_mode)) {
311 LOG(ERROR) << "Path '" << path << "' is not a directory.";
312 return nullptr;
313 }
314
315 if (path[path.size() - 1] != OS_PATH_SEPARATOR) {
316 path += OS_PATH_SEPARATOR;
317 }
318
Yurii Zubrytskyi2ab44472022-11-30 00:56:22 -0800319 const bool isReadonly = isReadonlyFilesystem(path.c_str());
320 return std::unique_ptr<DirectoryAssetsProvider>(
321 new DirectoryAssetsProvider(std::move(path), isReadonly ? -1 : sb.st_mtime));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800322}
323
324std::unique_ptr<Asset> DirectoryAssetsProvider::OpenInternal(const std::string& path,
325 Asset::AccessMode /* mode */,
326 bool* file_exists) const {
327 const std::string resolved_path = dir_ + path;
328 if (file_exists != nullptr) {
329 struct stat sb{};
330 *file_exists = (stat(resolved_path.c_str(), &sb) != -1) && S_ISREG(sb.st_mode);
331 }
332
333 return CreateAssetFromFile(resolved_path);
334}
335
336bool DirectoryAssetsProvider::ForEachFile(
337 const std::string& /* root_path */,
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700338 const std::function<void(StringPiece, FileType)>& /* f */) const {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800339 return true;
340}
341
Ryan Mitchellef538432021-03-01 14:52:14 -0800342std::optional<std::string_view> DirectoryAssetsProvider::GetPath() const {
343 return dir_;
344}
345
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800346const std::string& DirectoryAssetsProvider::GetDebugName() const {
347 return dir_;
348}
349
350bool DirectoryAssetsProvider::IsUpToDate() const {
Yurii Zubrytskyi2ab44472022-11-30 00:56:22 -0800351 if (last_mod_time_ == -1) {
352 return true;
353 }
354 struct stat sb;
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800355 if (stat(dir_.c_str(), &sb) < 0) {
356 // If stat fails on the zip archive, return true so the zip archive the resource system does
357 // attempt to refresh the ApkAsset.
358 return true;
359 }
360 return last_mod_time_ == sb.st_mtime;
361}
362
363MultiAssetsProvider::MultiAssetsProvider(std::unique_ptr<AssetsProvider>&& primary,
364 std::unique_ptr<AssetsProvider>&& secondary)
365 : primary_(std::forward<std::unique_ptr<AssetsProvider>>(primary)),
366 secondary_(std::forward<std::unique_ptr<AssetsProvider>>(secondary)) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800367 debug_name_ = primary_->GetDebugName() + " and " + secondary_->GetDebugName();
368 path_ = (primary_->GetDebugName() != kEmptyDebugString) ? primary_->GetPath()
369 : secondary_->GetPath();
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800370}
371
372std::unique_ptr<AssetsProvider> MultiAssetsProvider::Create(
373 std::unique_ptr<AssetsProvider>&& primary, std::unique_ptr<AssetsProvider>&& secondary) {
374 if (primary == nullptr || secondary == nullptr) {
375 return nullptr;
376 }
377 return std::unique_ptr<MultiAssetsProvider>(new MultiAssetsProvider(std::move(primary),
378 std::move(secondary)));
379}
380
381std::unique_ptr<Asset> MultiAssetsProvider::OpenInternal(const std::string& path,
382 Asset::AccessMode mode,
383 bool* file_exists) const {
384 auto asset = primary_->Open(path, mode, file_exists);
385 return (asset) ? std::move(asset) : secondary_->Open(path, mode, file_exists);
386}
387
388bool MultiAssetsProvider::ForEachFile(const std::string& root_path,
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700389 const std::function<void(StringPiece, FileType)>& f) const {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800390 return primary_->ForEachFile(root_path, f) && secondary_->ForEachFile(root_path, f);
391}
392
Ryan Mitchellef538432021-03-01 14:52:14 -0800393std::optional<std::string_view> MultiAssetsProvider::GetPath() const {
394 return path_;
395}
396
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800397const std::string& MultiAssetsProvider::GetDebugName() const {
398 return debug_name_;
399}
400
401bool MultiAssetsProvider::IsUpToDate() const {
402 return primary_->IsUpToDate() && secondary_->IsUpToDate();
403}
404
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800405EmptyAssetsProvider::EmptyAssetsProvider(std::optional<std::string>&& path) :
406 path_(std::move(path)) {}
407
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800408std::unique_ptr<AssetsProvider> EmptyAssetsProvider::Create() {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800409 return std::unique_ptr<EmptyAssetsProvider>(new EmptyAssetsProvider({}));
410}
411
Yurii Zubrytskyid0c22cc2022-11-10 14:11:05 -0800412std::unique_ptr<AssetsProvider> EmptyAssetsProvider::Create(std::string path) {
413 return std::unique_ptr<EmptyAssetsProvider>(new EmptyAssetsProvider(std::move(path)));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800414}
415
416std::unique_ptr<Asset> EmptyAssetsProvider::OpenInternal(const std::string& /* path */,
417 Asset::AccessMode /* mode */,
418 bool* file_exists) const {
419 if (file_exists) {
420 *file_exists = false;
421 }
422 return nullptr;
423}
424
425bool EmptyAssetsProvider::ForEachFile(
426 const std::string& /* root_path */,
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700427 const std::function<void(StringPiece, FileType)>& /* f */) const {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800428 return true;
429}
430
Ryan Mitchellef538432021-03-01 14:52:14 -0800431std::optional<std::string_view> EmptyAssetsProvider::GetPath() const {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800432 if (path_.has_value()) {
433 return *path_;
434 }
Ryan Mitchellef538432021-03-01 14:52:14 -0800435 return {};
436}
437
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800438const std::string& EmptyAssetsProvider::GetDebugName() const {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800439 if (path_.has_value()) {
440 return *path_;
441 }
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800442 const static std::string kEmpty = kEmptyDebugString;
443 return kEmpty;
444}
445
446bool EmptyAssetsProvider::IsUpToDate() const {
447 return true;
448}
449
Yurii Zubrytskyi2ab44472022-11-30 00:56:22 -0800450} // namespace android