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
60 startPos += (size_t)nread;
61 dst += nread;
62 remainSize -= (size_t)nread;
63 } while (remainSize > 0);
64 if (remainSize > 0) {
65 ABILITYBASE_LOGE("readfile error: %{public}s-%{public}d", filePath_.c_str(), errno);
66 return false;
67 }
68
69 if (bufferSize > BIG_FILE_SIZE) {
70 ABILITYBASE_LOGW("big file io success: %{public}zu", bufferSize);
71 }
72 return true;
73 }
74 }
75 }