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_io.h"
17
18 #include <cstdlib>
19 #include "ability_base_log_wrapper.h"
20
21
22 namespace OHOS {
23 namespace AbilityBase {
24 namespace {
25 constexpr size_t BIG_FILE_SIZE = 1u << 31;
26 }
ReadBuffer(size_t startPos,size_t bufferSize)27 std::string ZipFileReaderIo::ReadBuffer(size_t startPos, size_t bufferSize)
28 {
29 std::string result;
30 if (fd_ < 0 || startPos >= fileLen_ || bufferSize > fileLen_ - startPos) {
31 ABILITYBASE_LOGE("failed: %{public}s, startPos: %{public}zu, bufferSize: %{public}zu, fileLen: %{public}zu",
32 filePath_.c_str(), startPos, bufferSize, fileLen_);
33 return result;
34 }
35
36 result.resize(bufferSize);
37 if (!ReadBuffer((uint8_t*)result.data(), startPos, bufferSize)) {
38 result.clear();
39 }
40
41 return result;
42 }
43
ReadBuffer(uint8_t * dst,size_t startPos,size_t bufferSize)44 bool ZipFileReaderIo::ReadBuffer(uint8_t *dst, size_t startPos, size_t bufferSize)
45 {
46 if (dst == nullptr || fd_ < 0 || startPos >= fileLen_ || bufferSize > fileLen_ - startPos) {
47 ABILITYBASE_LOGE("failed: %{public}s, startPos: %{public}zu, bufferSize: %{public}zu, fileLen: %{public}zu",
48 filePath_.c_str(), startPos, bufferSize, fileLen_);
49 return false;
50 }
51
52 auto remainSize = bufferSize;
53 ssize_t nread = 0;
54 do {
55 nread = pread(fd_, dst, remainSize, startPos);
56 if (nread <= 0) {
57 break;
58 }
59 startPos += static_cast<size_t>(nread);
60 dst += nread;
61 if (remainSize > static_cast<size_t>(nread)) {
62 remainSize -= static_cast<size_t>(nread);
63 } else {
64 remainSize = 0;
65 }
66 } while (remainSize > 0);
67 if (remainSize > 0) {
68 ABILITYBASE_LOGE("readfile error: %{public}s-%{public}d", filePath_.c_str(), errno);
69 return false;
70 }
71
72 if (bufferSize > BIG_FILE_SIZE) {
73 ABILITYBASE_LOGW("big file io success: %{public}zu", bufferSize);
74 }
75 return true;
76 }
77 }
78 }
79