• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 "zip_file_reader_io.h"
23 #include "zip_file_reader_mem.h"
24 
25 namespace OHOS {
26 namespace AbilityBase {
27 constexpr size_t MEM_MAX_FILE_SIZE = 1u;
28 
CreateZipFileReader(const std::string & filePath)29 std::shared_ptr<ZipFileReader> ZipFileReader::CreateZipFileReader(const std::string &filePath)
30 {
31     size_t fileSize = GetFileLen(filePath);
32     if (fileSize == 0) {
33         ABILITYBASE_LOGE("filelen error: %{public}s", filePath.c_str());
34         return nullptr;
35     }
36 
37     std::shared_ptr<ZipFileReader> result;
38     if (fileSize <= MEM_MAX_FILE_SIZE) {
39         result = std::make_shared<ZipFileReaderMem>(filePath);
40     } else {
41         result = std::make_shared<ZipFileReaderIo>(filePath);
42     }
43 
44     result->fileLen_ = fileSize;
45     if (result->init()) {
46         return result;
47     }
48     return nullptr;
49 }
50 
~ZipFileReader()51 ZipFileReader::~ZipFileReader()
52 {
53     if (fd_ >= 0 && closable_) {
54         close(fd_);
55         fd_ = -1;
56     }
57 }
58 
GetFileLen(const std::string & filePath)59 size_t ZipFileReader::GetFileLen(const std::string &filePath)
60 {
61     if (filePath.empty()) {
62         return 0;
63     }
64 
65     struct stat fileStat{};
66     if (stat(filePath.c_str(), &fileStat) == 0) {
67         return fileStat.st_size;
68     }
69 
70     ABILITYBASE_LOGE("file oppen error: %{public}s : %{public}d", filePath.c_str(), errno);
71     return 0;
72 }
73 
init()74 bool ZipFileReader::init()
75 {
76     if (filePath_.empty()) {
77         return false;
78     }
79     char resolvePath[PATH_MAX] = {0};
80     if (realpath(filePath_.c_str(), resolvePath) == nullptr) {
81         ABILITYBASE_LOGE("realpath error: %{public}s : %{public}d", resolvePath, errno);
82         return false;
83     }
84     fd_ = open(resolvePath, O_RDONLY);
85     if (fd_ < 0) {
86         ABILITYBASE_LOGE("open file error: %{public}s : %{public}d", resolvePath, errno);
87         return false;
88     }
89 
90     return true;
91 }
92 }
93 }