blob: 24460a4c08679d46ce62ad220114846521380ea1 [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 Zubrytskyi801c4412022-11-30 16:47:23 -0800107 if ((released_fd < 0 ? stat(path.c_str(), &sb) : fstat(released_fd, &sb)) < 0) {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800108 // Stat requires execute permissions on all directories path to the file. If the process does
109 // not have execute permissions on this file, allow the zip to be opened but IsUpToDate() will
110 // always have to return true.
111 LOG(WARNING) << "Failed to stat file '" << path << "': "
112 << base::SystemErrorCodeToString(errno);
113 }
114
115 return std::unique_ptr<ZipAssetsProvider>(
116 new ZipAssetsProvider(handle, PathOrDebugName{std::move(path),
Ryan Mitchellc0416692021-05-11 12:21:29 -0700117 true /* is_path */}, flags, sb.st_mtime));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800118}
119
120std::unique_ptr<ZipAssetsProvider> ZipAssetsProvider::Create(base::unique_fd fd,
121 std::string friendly_name,
Ryan Mitchellc0416692021-05-11 12:21:29 -0700122 package_property_t flags,
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800123 off64_t offset,
124 off64_t len) {
125 ZipArchiveHandle handle;
126 const int released_fd = fd.release();
127 const int32_t result = (len == AssetsProvider::kUnknownLength)
128 ? ::OpenArchiveFd(released_fd, friendly_name.c_str(), &handle)
129 : ::OpenArchiveFdRange(released_fd, friendly_name.c_str(), &handle, len, offset);
130
131 if (result != 0) {
132 LOG(ERROR) << "Failed to open APK '" << friendly_name << "' through FD with offset " << offset
133 << " and length " << len << ": " << ::ErrorCodeString(result);
134 CloseArchive(handle);
135 return {};
136 }
137
138 struct stat sb{.st_mtime = -1};
139 if (fstat(released_fd, &sb) < 0) {
140 // Stat requires execute permissions on all directories path to the file. If the process does
141 // not have execute permissions on this file, allow the zip to be opened but IsUpToDate() will
142 // always have to return true.
143 LOG(WARNING) << "Failed to fstat file '" << friendly_name << "': "
144 << base::SystemErrorCodeToString(errno);
145 }
146
147 return std::unique_ptr<ZipAssetsProvider>(
148 new ZipAssetsProvider(handle, PathOrDebugName{std::move(friendly_name),
Ryan Mitchellc0416692021-05-11 12:21:29 -0700149 false /* is_path */}, flags, sb.st_mtime));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800150}
151
152std::unique_ptr<Asset> ZipAssetsProvider::OpenInternal(const std::string& path,
153 Asset::AccessMode mode,
154 bool* file_exists) const {
155 if (file_exists != nullptr) {
156 *file_exists = false;
157 }
158
159 ZipEntry entry;
160 if (FindEntry(zip_handle_.get(), path, &entry) != 0) {
161 return {};
162 }
163
164 if (file_exists != nullptr) {
165 *file_exists = true;
166 }
167
168 const int fd = GetFileDescriptor(zip_handle_.get());
169 const off64_t fd_offset = GetFileDescriptorOffset(zip_handle_.get());
Ryan Mitchellc0416692021-05-11 12:21:29 -0700170 const bool incremental_hardening = (flags_ & PROPERTY_DISABLE_INCREMENTAL_HARDENING) == 0U;
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800171 incfs::IncFsFileMap asset_map;
172 if (entry.method == kCompressDeflated) {
173 if (!asset_map.Create(fd, entry.offset + fd_offset, entry.compressed_length,
Ryan Mitchellc0416692021-05-11 12:21:29 -0700174 name_.GetDebugName().c_str(), incremental_hardening)) {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800175 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName()
176 << "'";
177 return {};
178 }
179
180 std::unique_ptr<Asset> asset =
181 Asset::createFromCompressedMap(std::move(asset_map), entry.uncompressed_length, mode);
182 if (asset == nullptr) {
183 LOG(ERROR) << "Failed to decompress '" << path << "' in APK '" << name_.GetDebugName()
184 << "'";
185 return {};
186 }
187 return asset;
188 }
189
190 if (!asset_map.Create(fd, entry.offset + fd_offset, entry.uncompressed_length,
Ryan Mitchellc0416692021-05-11 12:21:29 -0700191 name_.GetDebugName().c_str(), incremental_hardening)) {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800192 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName() << "'";
193 return {};
194 }
195
196 base::unique_fd ufd;
197 if (name_.GetPath() == nullptr) {
198 // If the zip name does not represent a path, create a new `fd` for the new Asset to own in
199 // order to create new file descriptors using Asset::openFileDescriptor. If the zip name is a
200 // path, it will be used to create new file descriptors.
201 ufd = base::unique_fd(dup(fd));
202 if (!ufd.ok()) {
203 LOG(ERROR) << "Unable to dup fd '" << path << "' in APK '" << name_.GetDebugName() << "'";
204 return {};
205 }
206 }
207
208 auto asset = Asset::createFromUncompressedMap(std::move(asset_map), mode, std::move(ufd));
209 if (asset == nullptr) {
210 LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << name_.GetDebugName() << "'";
211 return {};
212 }
213 return asset;
214}
215
216bool ZipAssetsProvider::ForEachFile(const std::string& root_path,
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700217 const std::function<void(StringPiece, FileType)>& f) const {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800218 std::string root_path_full = root_path;
219 if (root_path_full.back() != '/') {
220 root_path_full += '/';
221 }
222
223 void* cookie;
224 if (StartIteration(zip_handle_.get(), &cookie, root_path_full, "") != 0) {
225 return false;
226 }
227
228 std::string name;
229 ::ZipEntry entry{};
230
231 // We need to hold back directories because many paths will contain them and we want to only
232 // surface one.
233 std::set<std::string> dirs{};
234
235 int32_t result;
236 while ((result = Next(cookie, &entry, &name)) == 0) {
237 StringPiece full_file_path(name);
238 StringPiece leaf_file_path = full_file_path.substr(root_path_full.size());
239
240 if (!leaf_file_path.empty()) {
241 auto iter = std::find(leaf_file_path.begin(), leaf_file_path.end(), '/');
242 if (iter != leaf_file_path.end()) {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700243 std::string dir(leaf_file_path.substr(0, std::distance(leaf_file_path.begin(), iter)));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800244 dirs.insert(std::move(dir));
245 } else {
246 f(leaf_file_path, kFileTypeRegular);
247 }
248 }
249 }
250 EndIteration(cookie);
251
252 // Now present the unique directories.
253 for (const std::string& dir : dirs) {
254 f(dir, kFileTypeDirectory);
255 }
256
257 // -1 is end of iteration, anything else is an error.
258 return result == -1;
259}
260
Ryan Mitchell2ed8bfa2021-01-08 13:34:28 -0800261std::optional<uint32_t> ZipAssetsProvider::GetCrc(std::string_view path) const {
262 ::ZipEntry entry;
263 if (FindEntry(zip_handle_.get(), path, &entry) != 0) {
264 return {};
265 }
266 return entry.crc32;
267}
268
Ryan Mitchellef538432021-03-01 14:52:14 -0800269std::optional<std::string_view> ZipAssetsProvider::GetPath() const {
270 if (name_.GetPath() != nullptr) {
271 return *name_.GetPath();
272 }
273 return {};
274}
275
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800276const std::string& ZipAssetsProvider::GetDebugName() const {
277 return name_.GetDebugName();
278}
279
280bool ZipAssetsProvider::IsUpToDate() const {
281 struct stat sb{};
282 if (fstat(GetFileDescriptor(zip_handle_.get()), &sb) < 0) {
283 // If fstat fails on the zip archive, return true so the zip archive the resource system does
284 // attempt to refresh the ApkAsset.
285 return true;
286 }
287 return last_mod_time_ == sb.st_mtime;
288}
289
290DirectoryAssetsProvider::DirectoryAssetsProvider(std::string&& path, time_t last_mod_time)
291 : dir_(std::forward<std::string>(path)), last_mod_time_(last_mod_time) {}
292
293std::unique_ptr<DirectoryAssetsProvider> DirectoryAssetsProvider::Create(std::string path) {
294 struct stat sb{};
295 const int result = stat(path.c_str(), &sb);
296 if (result == -1) {
297 LOG(ERROR) << "Failed to find directory '" << path << "'.";
298 return nullptr;
299 }
300
301 if (!S_ISDIR(sb.st_mode)) {
302 LOG(ERROR) << "Path '" << path << "' is not a directory.";
303 return nullptr;
304 }
305
306 if (path[path.size() - 1] != OS_PATH_SEPARATOR) {
307 path += OS_PATH_SEPARATOR;
308 }
309
310 return std::unique_ptr<DirectoryAssetsProvider>(new DirectoryAssetsProvider(std::move(path),
311 sb.st_mtime));
312}
313
314std::unique_ptr<Asset> DirectoryAssetsProvider::OpenInternal(const std::string& path,
315 Asset::AccessMode /* mode */,
316 bool* file_exists) const {
317 const std::string resolved_path = dir_ + path;
318 if (file_exists != nullptr) {
319 struct stat sb{};
320 *file_exists = (stat(resolved_path.c_str(), &sb) != -1) && S_ISREG(sb.st_mode);
321 }
322
323 return CreateAssetFromFile(resolved_path);
324}
325
326bool DirectoryAssetsProvider::ForEachFile(
327 const std::string& /* root_path */,
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700328 const std::function<void(StringPiece, FileType)>& /* f */) const {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800329 return true;
330}
331
Ryan Mitchellef538432021-03-01 14:52:14 -0800332std::optional<std::string_view> DirectoryAssetsProvider::GetPath() const {
333 return dir_;
334}
335
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800336const std::string& DirectoryAssetsProvider::GetDebugName() const {
337 return dir_;
338}
339
340bool DirectoryAssetsProvider::IsUpToDate() const {
341 struct stat sb{};
342 if (stat(dir_.c_str(), &sb) < 0) {
343 // If stat fails on the zip archive, return true so the zip archive the resource system does
344 // attempt to refresh the ApkAsset.
345 return true;
346 }
347 return last_mod_time_ == sb.st_mtime;
348}
349
350MultiAssetsProvider::MultiAssetsProvider(std::unique_ptr<AssetsProvider>&& primary,
351 std::unique_ptr<AssetsProvider>&& secondary)
352 : primary_(std::forward<std::unique_ptr<AssetsProvider>>(primary)),
353 secondary_(std::forward<std::unique_ptr<AssetsProvider>>(secondary)) {
Ryan Mitchellef538432021-03-01 14:52:14 -0800354 debug_name_ = primary_->GetDebugName() + " and " + secondary_->GetDebugName();
355 path_ = (primary_->GetDebugName() != kEmptyDebugString) ? primary_->GetPath()
356 : secondary_->GetPath();
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800357}
358
359std::unique_ptr<AssetsProvider> MultiAssetsProvider::Create(
360 std::unique_ptr<AssetsProvider>&& primary, std::unique_ptr<AssetsProvider>&& secondary) {
361 if (primary == nullptr || secondary == nullptr) {
362 return nullptr;
363 }
364 return std::unique_ptr<MultiAssetsProvider>(new MultiAssetsProvider(std::move(primary),
365 std::move(secondary)));
366}
367
368std::unique_ptr<Asset> MultiAssetsProvider::OpenInternal(const std::string& path,
369 Asset::AccessMode mode,
370 bool* file_exists) const {
371 auto asset = primary_->Open(path, mode, file_exists);
372 return (asset) ? std::move(asset) : secondary_->Open(path, mode, file_exists);
373}
374
375bool MultiAssetsProvider::ForEachFile(const std::string& root_path,
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700376 const std::function<void(StringPiece, FileType)>& f) const {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800377 return primary_->ForEachFile(root_path, f) && secondary_->ForEachFile(root_path, f);
378}
379
Ryan Mitchellef538432021-03-01 14:52:14 -0800380std::optional<std::string_view> MultiAssetsProvider::GetPath() const {
381 return path_;
382}
383
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800384const std::string& MultiAssetsProvider::GetDebugName() const {
385 return debug_name_;
386}
387
388bool MultiAssetsProvider::IsUpToDate() const {
389 return primary_->IsUpToDate() && secondary_->IsUpToDate();
390}
391
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800392EmptyAssetsProvider::EmptyAssetsProvider(std::optional<std::string>&& path) :
393 path_(std::move(path)) {}
394
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800395std::unique_ptr<AssetsProvider> EmptyAssetsProvider::Create() {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800396 return std::unique_ptr<EmptyAssetsProvider>(new EmptyAssetsProvider({}));
397}
398
Yurii Zubrytskyid0c22cc2022-11-10 14:11:05 -0800399std::unique_ptr<AssetsProvider> EmptyAssetsProvider::Create(std::string path) {
400 return std::unique_ptr<EmptyAssetsProvider>(new EmptyAssetsProvider(std::move(path)));
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800401}
402
403std::unique_ptr<Asset> EmptyAssetsProvider::OpenInternal(const std::string& /* path */,
404 Asset::AccessMode /* mode */,
405 bool* file_exists) const {
406 if (file_exists) {
407 *file_exists = false;
408 }
409 return nullptr;
410}
411
412bool EmptyAssetsProvider::ForEachFile(
413 const std::string& /* root_path */,
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700414 const std::function<void(StringPiece, FileType)>& /* f */) const {
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800415 return true;
416}
417
Ryan Mitchellef538432021-03-01 14:52:14 -0800418std::optional<std::string_view> EmptyAssetsProvider::GetPath() const {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800419 if (path_.has_value()) {
420 return *path_;
421 }
Ryan Mitchellef538432021-03-01 14:52:14 -0800422 return {};
423}
424
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800425const std::string& EmptyAssetsProvider::GetDebugName() const {
Ryan Mitchellbdc0ae12021-03-01 15:18:15 -0800426 if (path_.has_value()) {
427 return *path_;
428 }
Ryan Mitchell1a48fa62021-01-10 08:36:36 -0800429 const static std::string kEmpty = kEmptyDebugString;
430 return kEmpty;
431}
432
433bool EmptyAssetsProvider::IsUpToDate() const {
434 return true;
435}
436
437} // namespace android