1 /*
2 * Copyright (c) 2022 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 #include "zip.h"
16
17 #include <fcntl.h>
18 #include <list>
19 #include <stdio.h>
20 #include <string>
21 #include <unistd.h>
22 #include <vector>
23
24 #include "app_log_wrapper.h"
25 #include "appexecfwk_errors.h"
26 #include "bundle_errors.h"
27 #include "directory_ex.h"
28 #include "event_handler.h"
29 #include "ffrt.h"
30 #include "file_path.h"
31 #include "zip_internal.h"
32 #include "zip_reader.h"
33 #include "zip_writer.h"
34
35 using namespace OHOS::AppExecFwk;
36
37 namespace OHOS {
38 namespace AppExecFwk {
39 namespace LIBZIP {
40 namespace {
41 using FilterCallback = std::function<bool(const FilePath &)>;
42 using DirectoryCreator = std::function<bool(FilePath &, FilePath &)>;
43 using WriterFactory = std::function<std::unique_ptr<WriterDelegate>(FilePath &, FilePath &)>;
44
45 const std::string SEPARATOR = "/";
46 const char HIDDEN_SEPARATOR = '.';
47 const std::string ZIP = ".zip";
48
49 struct UnzipParam {
50 FilterCallback filterCB = nullptr;
51 bool logSkippedFiles = false;
52 };
IsHiddenFile(const FilePath & filePath)53 bool IsHiddenFile(const FilePath &filePath)
54 {
55 FilePath localFilePath = filePath;
56 if (!localFilePath.Value().empty()) {
57 return localFilePath.Value()[0] == HIDDEN_SEPARATOR;
58 } else {
59 return false;
60 }
61 }
ExcludeNoFilesFilter(const FilePath & filePath)62 bool ExcludeNoFilesFilter(const FilePath &filePath)
63 {
64 return true;
65 }
66
ExcludeHiddenFilesFilter(const FilePath & filePath)67 bool ExcludeHiddenFilesFilter(const FilePath &filePath)
68 {
69 return !IsHiddenFile(filePath);
70 }
71
ListDirectoryContent(const FilePath & filePath,bool & isSuccess)72 std::vector<FileAccessor::DirectoryContentEntry> ListDirectoryContent(const FilePath &filePath, bool& isSuccess)
73 {
74 FilePath curPath = filePath;
75 std::vector<FileAccessor::DirectoryContentEntry> fileDirectoryVector;
76 std::vector<std::string> filelist;
77 isSuccess = FilePath::GetZipAllDirFiles(curPath.Value(), filelist);
78 if (isSuccess) {
79 APP_LOGD("f.size=%{public}zu", filelist.size());
80 for (size_t i = 0; i < filelist.size(); i++) {
81 std::string str(filelist[i]);
82 if (!str.empty()) {
83 fileDirectoryVector.push_back(
84 FileAccessor::DirectoryContentEntry(FilePath(str), FilePath::DirectoryExists(FilePath(str))));
85 }
86 }
87 }
88 return fileDirectoryVector;
89 }
90
91 // Creates a directory at |extractDir|/|entryPath|, including any parents.
CreateDirectory(FilePath & extractDir,FilePath & entryPath)92 bool CreateDirectory(FilePath &extractDir, FilePath &entryPath)
93 {
94 std::string path = extractDir.Value();
95 if (EndsWith(path, SEPARATOR)) {
96 return FilePath::CreateDirectory(FilePath(extractDir.Value() + entryPath.Value()));
97 } else {
98 return FilePath::CreateDirectory(FilePath(extractDir.Value() + "/" + entryPath.Value()));
99 }
100 }
101
102 // Creates a WriterDelegate that can write a file at |extractDir|/|entryPath|.
CreateFilePathWriterDelegate(FilePath & extractDir,FilePath entryPath)103 std::unique_ptr<WriterDelegate> CreateFilePathWriterDelegate(FilePath &extractDir, FilePath entryPath)
104 {
105 if (EndsWith(extractDir.Value(), SEPARATOR)) {
106 return std::make_unique<FilePathWriterDelegate>(FilePath(extractDir.Value() + entryPath.Value()));
107 } else {
108 return std::make_unique<FilePathWriterDelegate>(FilePath(extractDir.Value() + "/" + entryPath.Value()));
109 }
110 }
111 } // namespace
112
ZipParams(const std::vector<FilePath> & srcDir,const FilePath & destFile)113 ZipParams::ZipParams(const std::vector<FilePath>& srcDir, const FilePath& destFile)
114 : srcDir_(srcDir), destFile_(destFile)
115 {}
116
117 // Does not take ownership of |fd|.
ZipParams(const std::vector<FilePath> & srcDir,int destFd)118 ZipParams::ZipParams(const std::vector<FilePath> &srcDir, int destFd) : srcDir_(srcDir), destFd_(destFd)
119 {}
120
FilePathEndIsSeparator(FilePath paramPath)121 FilePath FilePathEndIsSeparator(FilePath paramPath)
122 {
123 bool endIsSeparator = EndsWith(paramPath.Value(), SEPARATOR);
124 if (FilePath::IsDir(paramPath)) {
125 if (!endIsSeparator) {
126 paramPath.AppendSeparator();
127 }
128 }
129 return paramPath;
130 }
131
Zip(const ZipParams & params,const OPTIONS & options)132 bool Zip(const ZipParams ¶ms, const OPTIONS &options)
133 {
134 const std::vector<std::pair<FilePath, FilePath>> *filesToAdd = ¶ms.GetFilesTozip();
135 std::vector<std::pair<FilePath, FilePath>> allRelativeFiles;
136 FilePath srcDir = params.SrcDir().front();
137 FilePath paramPath = FilePathEndIsSeparator(srcDir);
138 if (filesToAdd->empty()) {
139 filesToAdd = &allRelativeFiles;
140 std::list<FileAccessor::DirectoryContentEntry> entries;
141 if (EndsWith(paramPath.Value(), SEPARATOR)) {
142 entries.push_back(FileAccessor::DirectoryContentEntry(srcDir, true));
143 FilterCallback filterCallback = params.GetFilterCallback();
144 for (auto iter = entries.begin(); iter != entries.end(); ++iter) {
145 if (iter != entries.begin() && ((!params.GetIncludeHiddenFiles() && IsHiddenFile(iter->path)) ||
146 (filterCallback && !filterCallback(iter->path)))) {
147 continue;
148 }
149 if (iter != entries.begin()) {
150 FilePath relativePath;
151 FilePath paramsSrcPath = srcDir;
152 if (paramsSrcPath.AppendRelativePath(iter->path, &relativePath)) {
153 allRelativeFiles.push_back(std::make_pair(relativePath, iter->path));
154 }
155 }
156 if (iter->isDirectory) {
157 bool isSuccess = false;
158 std::vector<FileAccessor::DirectoryContentEntry> subEntries =
159 ListDirectoryContent(iter->path, isSuccess);
160 entries.insert(entries.end(), subEntries.begin(), subEntries.end());
161 }
162 }
163 } else {
164 allRelativeFiles.push_back(std::make_pair(paramPath.BaseName(), paramPath));
165 }
166 }
167 std::unique_ptr<ZipWriter> zipWriter = nullptr;
168 if (params.DestFd() != kInvalidPlatformFile) {
169 zipWriter = std::make_unique<ZipWriter>(ZipWriter::InitZipFileWithFd(params.DestFd()));
170 } else {
171 zipWriter = std::make_unique<ZipWriter>(ZipWriter::InitZipFileWithFile(params.DestFile()));
172 }
173 if (zipWriter == nullptr) {
174 APP_LOGE("Init zipWriter failed");
175 return false;
176 }
177 return zipWriter->WriteEntries(*filesToAdd, options);
178 }
179
GetZipsAllRelativeFilesInner(const ZipParams & params,const FilePath & iterPath,std::list<FileAccessor::DirectoryContentEntry> & entries,std::vector<std::pair<FilePath,FilePath>> & allRelativeFiles)180 void GetZipsAllRelativeFilesInner(const ZipParams ¶ms, const FilePath &iterPath,
181 std::list<FileAccessor::DirectoryContentEntry> &entries,
182 std::vector<std::pair<FilePath, FilePath>> &allRelativeFiles)
183 {
184 FilterCallback filterCallback = params.GetFilterCallback();
185 for (auto iter = entries.begin(); iter != entries.end(); ++iter) {
186 if (iter != entries.begin() && ((!params.GetIncludeHiddenFiles() && IsHiddenFile(iter->path)) ||
187 (filterCallback && !filterCallback(iter->path)))) {
188 continue;
189 }
190 if (iter != entries.begin()) {
191 FilePath relativePath;
192 FilePath paramsSrcPath = iterPath;
193 if (paramsSrcPath.AppendRelativePath(iter->path, &relativePath)) {
194 allRelativeFiles.push_back(std::make_pair(relativePath, iter->path));
195 }
196 }
197 if (iter->isDirectory) {
198 bool isSuccess = false;
199 std::vector<FileAccessor::DirectoryContentEntry> subEntries = ListDirectoryContent(iter->path, isSuccess);
200 entries.insert(entries.end(), subEntries.begin(), subEntries.end());
201 }
202 }
203 }
204
GetZipsAllRelativeFiles(const ZipParams & params,std::vector<std::pair<FilePath,FilePath>> & allRelativeFiles,std::vector<FilePath> & srcFiles)205 void GetZipsAllRelativeFiles(const ZipParams ¶ms, std::vector<std::pair<FilePath, FilePath>> &allRelativeFiles,
206 std::vector<FilePath> &srcFiles)
207 {
208 std::list<FileAccessor::DirectoryContentEntry> entries;
209 for (auto iterPath = srcFiles.begin(); iterPath != srcFiles.end(); ++iterPath) {
210 FilePath paramPath = FilePathEndIsSeparator(*iterPath);
211 if (!EndsWith(paramPath.Value(), SEPARATOR)) {
212 allRelativeFiles.push_back(std::make_pair(paramPath.BaseName(), paramPath));
213 continue;
214 }
215 entries.clear();
216 entries.push_back(FileAccessor::DirectoryContentEntry(*iterPath, true));
217 GetZipsAllRelativeFilesInner(params, *iterPath, entries, allRelativeFiles);
218 }
219 }
220
Zips(const ZipParams & params,const OPTIONS & options)221 bool Zips(const ZipParams ¶ms, const OPTIONS &options)
222 {
223 const std::vector<std::pair<FilePath, FilePath>> *filesToAdd = ¶ms.GetFilesTozip();
224 std::vector<std::pair<FilePath, FilePath>> allRelativeFiles;
225 std::vector<FilePath> srcFiles = params.SrcDir();
226 if (filesToAdd->empty()) {
227 filesToAdd = &allRelativeFiles;
228 GetZipsAllRelativeFiles(params, allRelativeFiles, srcFiles);
229 }
230 std::unique_ptr<ZipWriter> zipWriter = nullptr;
231 if (params.DestFd() != kInvalidPlatformFile) {
232 zipWriter = std::make_unique<ZipWriter>(ZipWriter::InitZipFileWithFd(params.DestFd()));
233 } else {
234 zipWriter = std::make_unique<ZipWriter>(ZipWriter::InitZipFileWithFile(params.DestFile()));
235 }
236 if (zipWriter == nullptr) {
237 APP_LOGE("Init zipWriter failed");
238 return false;
239 }
240 return zipWriter->WriteEntries(*filesToAdd, options);
241 }
242
UnzipWithFilterAndWriters(const PlatformFile & srcFile,FilePath & destDir,WriterFactory writerFactory,DirectoryCreator directoryCreator,UnzipParam & unzipParam)243 ErrCode UnzipWithFilterAndWriters(const PlatformFile &srcFile, FilePath &destDir, WriterFactory writerFactory,
244 DirectoryCreator directoryCreator, UnzipParam &unzipParam)
245 {
246 APP_LOGD("destDir=%{private}s", destDir.Value().c_str());
247 ZipReader reader;
248 if (!reader.OpenFromPlatformFile(srcFile)) {
249 APP_LOGI("Failed to open srcFile");
250 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
251 }
252 while (reader.HasMore()) {
253 if (!reader.OpenCurrentEntryInZip()) {
254 APP_LOGI("Failed to open the current file in zip");
255 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
256 }
257 const FilePath &constEntryPath = reader.CurrentEntryInfo()->GetFilePath();
258 FilePath entryPath = constEntryPath;
259 if (reader.CurrentEntryInfo()->IsUnsafe()) {
260 APP_LOGI("Found an unsafe file in zip");
261 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
262 }
263 // callback
264 if (unzipParam.filterCB(entryPath)) {
265 if (reader.CurrentEntryInfo()->IsDirectory()) {
266 if (!directoryCreator(destDir, entryPath)) {
267 APP_LOGI("directory_creator(%{private}s) Failed", entryPath.Value().c_str());
268 return ERR_ZLIB_DEST_FILE_DISABLED;
269 }
270 } else {
271 std::unique_ptr<WriterDelegate> writer = writerFactory(destDir, entryPath);
272 if (!writer->PrepareOutput()) {
273 APP_LOGE("PrepareOutput err");
274 return ERR_ZLIB_DEST_FILE_DISABLED;
275 }
276 if (!reader.ExtractCurrentEntry(writer.get(), std::numeric_limits<uint64_t>::max())) {
277 APP_LOGI("Failed to extract");
278 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
279 }
280 }
281 } else if (unzipParam.logSkippedFiles) {
282 APP_LOGI("Skipped file");
283 }
284
285 if (!reader.AdvanceToNextEntry()) {
286 APP_LOGI("Failed to advance to the next file");
287 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
288 }
289 }
290 return ERR_OK;
291 }
292
UnzipWithFilterAndWritersParallel(const FilePath & srcFile,FilePath & destDir,WriterFactory writerFactory,DirectoryCreator directoryCreator,UnzipParam & unzipParam)293 ErrCode UnzipWithFilterAndWritersParallel(const FilePath &srcFile, FilePath &destDir, WriterFactory writerFactory,
294 DirectoryCreator directoryCreator, UnzipParam &unzipParam)
295 {
296 APP_LOGD("destDir=%{private}s", destDir.Value().c_str());
297 ZipParallelReader reader;
298 FilePath src = srcFile;
299
300 if (!reader.Open(src)) {
301 APP_LOGI("Failed to open srcFile");
302 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
303 }
304 ErrCode ret = ERR_OK;
305 for (int32_t i = 0; i < reader.num_entries(); i++) {
306 if (!reader.OpenCurrentEntryInZip()) {
307 APP_LOGI("Failed to open the current file in zip");
308 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
309 }
310 const FilePath &constEntryPath = reader.CurrentEntryInfo()->GetFilePath();
311 if (reader.CurrentEntryInfo()->IsUnsafe()) {
312 APP_LOGI("Found an unsafe file in zip");
313 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
314 }
315 unz_file_pos position = {};
316 if (!reader.GetCurrentEntryPos(position)) {
317 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
318 }
319 bool isDirectory = reader.CurrentEntryInfo()->IsDirectory();
320 ffrt::submit([&, position, isDirectory, constEntryPath] () {
321 if (ret != ERR_OK) {
322 return;
323 }
324 int resourceId = sched_getcpu();
325 unzFile zipFile = reader.GetZipHandler(resourceId);
326 if (!reader.GotoEntry(zipFile, position)) {
327 APP_LOGI("Failed to go to entry");
328 ret = ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
329 return;
330 }
331 FilePath entryPath = constEntryPath;
332 if (unzipParam.filterCB(entryPath)) {
333 if (isDirectory) {
334 if (!directoryCreator(destDir, entryPath)) {
335 APP_LOGI("directory_creator(%{private}s) Failed", entryPath.Value().c_str());
336 reader.ReleaseZipHandler(resourceId);
337 ret = ERR_ZLIB_DEST_FILE_DISABLED;
338 return;
339 }
340 } else {
341 std::unique_ptr<WriterDelegate> writer = writerFactory(destDir, entryPath);
342 if (!writer->PrepareOutput()) {
343 APP_LOGE("PrepareOutput err");
344 reader.ReleaseZipHandler(resourceId);
345 ret = ERR_ZLIB_DEST_FILE_DISABLED;
346 return;
347 }
348 if (!reader.ExtractEntry(writer.get(), zipFile, std::numeric_limits<uint64_t>::max())) {
349 APP_LOGI("Failed to extract");
350 reader.ReleaseZipHandler(resourceId);
351 ret = ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
352 return;
353 }
354 }
355 } else if (unzipParam.logSkippedFiles) {
356 APP_LOGI("Skipped file");
357 }
358 reader.ReleaseZipHandler(resourceId);
359 }, {}, {});
360 if (!reader.AdvanceToNextEntry()) {
361 APP_LOGI("Failed to advance to the next file");
362 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
363 }
364 }
365 ffrt::wait();
366 return ERR_OK;
367 }
368
UnzipWithFilterCallback(const FilePath & srcFile,const FilePath & destDir,const OPTIONS & options,UnzipParam & unzipParam)369 ErrCode UnzipWithFilterCallback(
370 const FilePath &srcFile, const FilePath &destDir, const OPTIONS &options, UnzipParam &unzipParam)
371 {
372 FilePath src = srcFile;
373 if (!FilePathCheckValid(src.Value())) {
374 APP_LOGI("FilePathCheckValid returnValue is false");
375 return ERR_ZLIB_SRC_FILE_DISABLED;
376 }
377
378 FilePath dest = destDir;
379
380 APP_LOGD("srcFile=%{private}s, destFile=%{private}s", src.Value().c_str(), dest.Value().c_str());
381
382 if (!FilePath::PathIsValid(srcFile)) {
383 APP_LOGI("PathIsValid return value is false");
384 return ERR_ZLIB_SRC_FILE_DISABLED;
385 }
386
387 ErrCode ret = ERR_OK;
388 if (options.parallel == PARALLEL_STRATEGY_PARALLEL_DECOMPRESSION) {
389 ret = UnzipWithFilterAndWritersParallel(src,
390 dest,
391 std::bind(&CreateFilePathWriterDelegate, std::placeholders::_1, std::placeholders::_2),
392 std::bind(&CreateDirectory, std::placeholders::_1, std::placeholders::_2),
393 unzipParam);
394 } else {
395 PlatformFile zipFd = open(src.Value().c_str(), S_IREAD, O_CREAT);
396 if (zipFd == kInvalidPlatformFile) {
397 APP_LOGE("Failed to open");
398 return ERR_ZLIB_SRC_FILE_DISABLED;
399 }
400 ret = UnzipWithFilterAndWriters(zipFd,
401 dest,
402 std::bind(&CreateFilePathWriterDelegate, std::placeholders::_1, std::placeholders::_2),
403 std::bind(&CreateDirectory, std::placeholders::_1, std::placeholders::_2),
404 unzipParam);
405 close(zipFd);
406 }
407 return ret;
408 }
409
Unzip(const std::string & srcFile,const std::string & destFile,OPTIONS options,std::shared_ptr<ZlibCallbackInfo> zlibCallbackInfo)410 bool Unzip(const std::string &srcFile, const std::string &destFile, OPTIONS options,
411 std::shared_ptr<ZlibCallbackInfo> zlibCallbackInfo)
412 {
413 if (zlibCallbackInfo == nullptr) {
414 APP_LOGE("zlibCallbackInfo is nullptr");
415 return false;
416 }
417 FilePath srcFileDir(srcFile);
418 FilePath destDir(destFile);
419 if ((destDir.Value().size() == 0) || FilePath::HasRelativePathBaseOnAPIVersion(destFile)) {
420 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_DEST_FILE_DISABLED);
421 return false;
422 }
423 if ((srcFileDir.Value().size() == 0) || FilePath::HasRelativePathBaseOnAPIVersion(srcFile)) {
424 APP_LOGI("srcFile isn't Exist");
425 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_SRC_FILE_DISABLED);
426 return false;
427 }
428 if (!FilePath::PathIsValid(srcFileDir)) {
429 APP_LOGI("srcFile invalid");
430 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_SRC_FILE_DISABLED);
431 return false;
432 }
433 if (FilePath::DirectoryExists(destDir)) {
434 if (!FilePath::PathIsWriteable(destDir)) {
435 APP_LOGI("FilePath::PathIsWriteable(destDir) fail");
436 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_DEST_FILE_DISABLED);
437 return false;
438 }
439 } else {
440 APP_LOGI("destDir isn't path");
441 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_DEST_FILE_DISABLED);
442 return false;
443 }
444 auto innerTask = [srcFileDir, destDir, options, zlibCallbackInfo]() {
445 UnzipParam unzipParam {
446 .filterCB = ExcludeNoFilesFilter,
447 .logSkippedFiles = true
448 };
449 ErrCode err = UnzipWithFilterCallback(srcFileDir, destDir, options, unzipParam);
450 if (zlibCallbackInfo != nullptr) {
451 zlibCallbackInfo->OnZipUnZipFinish(err);
452 }
453 };
454 PostTask(innerTask);
455 return true;
456 }
457
ZipWithFilterCallback(const FilePath & srcDir,const FilePath & destFile,const OPTIONS & options,FilterCallback filterCB)458 ErrCode ZipWithFilterCallback(const FilePath &srcDir, const FilePath &destFile,
459 const OPTIONS &options, FilterCallback filterCB)
460 {
461 FilePath destPath = destFile;
462 if (!FilePath::DirectoryExists(destPath.DirName())) {
463 APP_LOGE("The destPath not exist");
464 return ERR_ZLIB_DEST_FILE_DISABLED;
465 }
466 if (!FilePath::PathIsWriteable(destPath.DirName())) {
467 APP_LOGE("The destPath not writeable");
468 return ERR_ZLIB_DEST_FILE_DISABLED;
469 }
470
471 if (!FilePath::PathIsValid(srcDir)) {
472 APP_LOGI("srcDir isn't Exist");
473 return ERR_ZLIB_SRC_FILE_DISABLED;
474 } else {
475 if (!FilePath::PathIsReadable(srcDir)) {
476 APP_LOGI("srcDir not readable");
477 return ERR_ZLIB_SRC_FILE_DISABLED;
478 }
479 }
480
481 std::vector<FilePath> srcFile = {srcDir};
482 ZipParams params(srcFile, FilePath(destPath.CheckDestDirTail()));
483 params.SetFilterCallback(filterCB);
484 bool result = Zip(params, options);
485 if (result) {
486 return ERR_OK;
487 } else {
488 return ERR_ZLIB_DEST_FILE_DISABLED;
489 }
490 }
491
ZipsWithFilterCallback(const std::vector<FilePath> & srcFiles,const FilePath & destFile,const OPTIONS & options,FilterCallback filterCB)492 ErrCode ZipsWithFilterCallback(const std::vector<FilePath> &srcFiles, const FilePath &destFile,
493 const OPTIONS &options, FilterCallback filterCB)
494 {
495 FilePath destPath = destFile;
496 if (!FilePath::DirectoryExists(destPath.DirName())) {
497 APP_LOGE("The destPath not exist");
498 return ERR_ZLIB_DEST_FILE_DISABLED;
499 }
500 if (!FilePath::PathIsWriteable(destPath.DirName())) {
501 APP_LOGE("The destPath not writeable");
502 return ERR_ZLIB_DEST_FILE_DISABLED;
503 }
504
505 for (auto iter = srcFiles.begin(); iter != srcFiles.end(); ++iter) {
506 if (!FilePath::PathIsValid(*iter)) {
507 APP_LOGI("srcDir isn't Exist");
508 return ERR_ZLIB_SRC_FILE_DISABLED;
509 } else {
510 if (!FilePath::PathIsReadable(*iter)) {
511 APP_LOGI("srcDir not readable");
512 return ERR_ZLIB_SRC_FILE_DISABLED;
513 }
514 }
515 }
516
517 ZipParams params(srcFiles, FilePath(destPath.CheckDestDirTail()));
518 params.SetFilterCallback(filterCB);
519 bool result = Zips(params, options);
520 if (result) {
521 return ERR_OK;
522 } else {
523 return ERR_ZLIB_DEST_FILE_DISABLED;
524 }
525 }
526
Zip(const std::string & srcPath,const std::string & destPath,const OPTIONS & options,bool includeHiddenFiles,std::shared_ptr<ZlibCallbackInfo> zlibCallbackInfo)527 bool Zip(const std::string &srcPath, const std::string &destPath, const OPTIONS &options,
528 bool includeHiddenFiles, std::shared_ptr<ZlibCallbackInfo> zlibCallbackInfo)
529 {
530 if (zlibCallbackInfo == nullptr) {
531 return false;
532 }
533 FilePath srcDir(srcPath);
534 FilePath destFile(destPath);
535 APP_LOGD("srcDir=%{private}s, destFile=%{private}s", srcDir.Value().c_str(), destFile.Value().c_str());
536
537 if ((srcDir.Value().size() == 0) || FilePath::HasRelativePathBaseOnAPIVersion(srcPath)) {
538 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_SRC_FILE_DISABLED);
539 return false;
540 }
541 if ((destFile.Value().size() == 0) || FilePath::HasRelativePathBaseOnAPIVersion(destPath)) {
542 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_DEST_FILE_DISABLED);
543 return false;
544 }
545
546 auto innerTask = [srcDir, destFile, includeHiddenFiles, zlibCallbackInfo, options]() {
547 if (includeHiddenFiles) {
548 ErrCode err = ZipWithFilterCallback(srcDir, destFile, options, ExcludeNoFilesFilter);
549 if (zlibCallbackInfo != nullptr) {
550 zlibCallbackInfo->OnZipUnZipFinish(err);
551 }
552 } else {
553 ErrCode err = ZipWithFilterCallback(srcDir, destFile, options, ExcludeHiddenFilesFilter);
554 if (zlibCallbackInfo != nullptr) {
555 zlibCallbackInfo->OnZipUnZipFinish(err);
556 }
557 }
558 };
559
560 PostTask(innerTask);
561 return true;
562 }
563
ZipFileIsValid(const std::string & srcFile)564 bool ZipFileIsValid(const std::string &srcFile)
565 {
566 if ((srcFile.size() == 0) || FilePath::HasRelativePathBaseOnAPIVersion(srcFile)) {
567 APP_LOGE("srcFile len is 0 or ../");
568 return false;
569 }
570 if (!FilePathCheckValid(srcFile)) {
571 APP_LOGE("FilePathCheckValid return false");
572 return false;
573 }
574 FilePath srcFileDir(srcFile);
575 if (!FilePath::PathIsValid(srcFileDir)) {
576 APP_LOGE("PathIsValid return false");
577 return false;
578 }
579 if (!FilePath::PathIsReadable(srcFileDir)) {
580 APP_LOGE("PathIsReadable return false");
581 return false;
582 }
583 return true;
584 }
585
GetOriginalSize(PlatformFile zipFd,int64_t & originalSize)586 ErrCode GetOriginalSize(PlatformFile zipFd, int64_t &originalSize)
587 {
588 ZipReader reader;
589 if (!reader.OpenFromPlatformFile(zipFd)) {
590 APP_LOGE("Failed to open, not ZIP format or damaged");
591 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
592 }
593 int64_t totalSize = 0;
594 while (reader.HasMore()) {
595 if (!reader.OpenCurrentEntryInZip()) {
596 APP_LOGE("Failed to open the current file in zip");
597 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
598 }
599 const FilePath &constEntryPath = reader.CurrentEntryInfo()->GetFilePath();
600 FilePath entryPath = constEntryPath;
601 if (reader.CurrentEntryInfo()->IsUnsafe()) {
602 APP_LOGE("Found an unsafe file in zip");
603 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
604 }
605 totalSize += reader.CurrentEntryInfo()->GetOriginalSize();
606 if (!reader.AdvanceToNextEntry()) {
607 APP_LOGE("Failed to advance to the next file");
608 return ERR_ZLIB_SRC_FILE_FORMAT_ERROR;
609 }
610 }
611 originalSize = totalSize;
612 return ERR_OK;
613 }
614
GetOriginalSize(const std::string & srcFile,int64_t & originalSize)615 ErrCode GetOriginalSize(const std::string &srcFile, int64_t &originalSize)
616 {
617 if (!ZipFileIsValid(srcFile)) {
618 return ERR_ZLIB_SRC_FILE_DISABLED;
619 }
620 PlatformFile zipFd = open(srcFile.c_str(), S_IREAD, O_CREAT);
621 if (zipFd == kInvalidPlatformFile) {
622 APP_LOGE("Failed to open file, errno: %{public}d, %{public}s", errno, strerror(errno));
623 return ERR_ZLIB_SRC_FILE_DISABLED;
624 }
625 ErrCode ret = GetOriginalSize(zipFd, originalSize);
626 close(zipFd);
627 return ret;
628 }
629
Zips(const std::vector<std::string> & srcFiles,const std::string & destPath,const OPTIONS & options,bool includeHiddenFiles,std::shared_ptr<ZlibCallbackInfo> zlibCallbackInfo)630 bool Zips(const std::vector<std::string> &srcFiles, const std::string &destPath, const OPTIONS &options,
631 bool includeHiddenFiles, std::shared_ptr<ZlibCallbackInfo> zlibCallbackInfo)
632 {
633 if (zlibCallbackInfo == nullptr) {
634 return false;
635 }
636 if (FilePath::HasRelativePathBaseOnAPIVersion(srcFiles)) {
637 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_SRC_FILE_DISABLED);
638 return false;
639 }
640 std::vector<FilePath> srcFilesPath;
641 for (auto iter = srcFiles.begin(); iter != srcFiles.end(); ++iter) {
642 FilePath srcFile(*iter);
643 if (srcFile.Value().size() == 0) {
644 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_SRC_FILE_DISABLED);
645 return false;
646 }
647 srcFilesPath.push_back(srcFile);
648 }
649 FilePath destFile(destPath);
650 if ((destFile.Value().size() == 0) || FilePath::HasRelativePathBaseOnAPIVersion(destPath)) {
651 zlibCallbackInfo->OnZipUnZipFinish(ERR_ZLIB_DEST_FILE_DISABLED);
652 return false;
653 }
654
655 auto innerTask = [srcFilesPath, destFile, includeHiddenFiles, zlibCallbackInfo, options]() {
656 if (includeHiddenFiles) {
657 ErrCode err = ZipsWithFilterCallback(srcFilesPath, destFile, options, ExcludeNoFilesFilter);
658 if (zlibCallbackInfo != nullptr) {
659 zlibCallbackInfo->OnZipUnZipFinish(err);
660 }
661 } else {
662 ErrCode err = ZipsWithFilterCallback(srcFilesPath, destFile, options, ExcludeHiddenFilesFilter);
663 if (zlibCallbackInfo != nullptr) {
664 zlibCallbackInfo->OnZipUnZipFinish(err);
665 }
666 }
667 };
668
669 PostTask(innerTask);
670 return true;
671 }
672 } // namespace LIBZIP
673 } // namespace AppExecFwk
674 } // namespace OHOS
675