1 /*
2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "zip_file_reader.h"
17
18 #include <memory>
19 #include <sys/stat.h>
20
21 #include "ability_base_log_wrapper.h"
22 #include "constants.h"
23 #include "hitrace_meter.h"
24 #include "zip_file_reader_io.h"
25
26 namespace OHOS {
27 namespace AbilityBase {
CreateZipFileReader(const std::string & filePath)28 std::shared_ptr<ZipFileReader> ZipFileReader::CreateZipFileReader(const std::string &filePath)
29 {
30 size_t fileSize = GetFileLen(filePath);
31 if (fileSize == 0) {
32 ABILITYBASE_LOGE("fileSize error: %{public}s", filePath.c_str());
33 return nullptr;
34 }
35
36 std::shared_ptr<ZipFileReader> result = std::make_shared<ZipFileReaderIo>(filePath);
37 result->fileLen_ = fileSize;
38 if (result->init()) {
39 return result;
40 }
41 return nullptr;
42 }
43
~ZipFileReader()44 ZipFileReader::~ZipFileReader()
45 {
46 if (fd_ >= 0 && closable_) {
47 close(fd_);
48 fd_ = -1;
49 }
50 }
51
GetFileLen(const std::string & filePath)52 size_t ZipFileReader::GetFileLen(const std::string &filePath)
53 {
54 if (filePath.empty()) {
55 return 0;
56 }
57
58 struct stat fileStat{};
59 if (stat(filePath.c_str(), &fileStat) == 0) {
60 return fileStat.st_size;
61 }
62
63 ABILITYBASE_LOGE("error: %{public}s : %{public}d", filePath.c_str(), errno);
64 return 0;
65 }
66
init()67 bool ZipFileReader::init()
68 {
69 if (filePath_.empty()) {
70 return false;
71 }
72 std::string resolvePath;
73 resolvePath.reserve(PATH_MAX);
74 resolvePath.resize(PATH_MAX - 1);
75 if (filePath_.substr(0, Constants::GetProcPrefix().size()) == Constants::GetProcPrefix()) {
76 resolvePath = filePath_;
77 } else {
78 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "realpath_file");
79 if (realpath(filePath_.c_str(), &(resolvePath[0])) == nullptr) {
80 ABILITYBASE_LOGE("realpath error: %{public}s : %{public}d", resolvePath.c_str(), errno);
81 return false;
82 }
83 }
84 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "open_file");
85 fd_ = open(resolvePath.c_str(), O_RDONLY);
86 if (fd_ < 0) {
87 ABILITYBASE_LOGE("open file error: %{public}s : %{public}d", resolvePath.c_str(), errno);
88 return false;
89 }
90
91 return true;
92 }
93 }
94 }