1 /*
2  * Copyright (c) 2020 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 "extractor_util.h"
17 
18 #include <dirent.h>
19 #include <fcntl.h>
20 #include <fstream>
21 #include <sys/stat.h>
22 #include <unistd.h>
23 
24 #include "bundle_log.h"
25 
26 namespace OHOS {
ExtractorUtil(const std::string & filePath)27 ExtractorUtil::ExtractorUtil(const std::string &filePath) : zipFile_(filePath) {}
28 
~ExtractorUtil()29 ExtractorUtil::~ExtractorUtil() {}
30 
Init()31 bool ExtractorUtil::Init()
32 {
33     if (!zipFile_.Open()) {
34         HILOG_ERROR(HILOG_MODULE_APP, "zipfile open fail");
35         return false;
36     }
37     initial_ = true;
38     return true;
39 }
40 
ExtractFileByName(const std::string & fileName,std::ostream & dest) const41 bool ExtractorUtil::ExtractFileByName(const std::string &fileName, std::ostream &dest) const
42 {
43     if (!initial_) {
44         return false;
45     }
46     if (!zipFile_.ExtractFile(fileName, dest)) {
47         HILOG_ERROR(HILOG_MODULE_APP, "ExtractFile open fail");
48         return false;
49     }
50     return true;
51 }
52 
ExtractFileToPath(const std::string & filePath,const std::string & fileName) const53 bool ExtractorUtil::ExtractFileToPath(const std::string &filePath, const std::string &fileName) const
54 {
55     std::ofstream fileStream;
56     fileStream.open(filePath, std::ios_base::out | std::ios_base::binary);
57     if (!fileStream.is_open()) {
58         HILOG_ERROR(HILOG_MODULE_APP, "ExtractFileToPath fileStream open fail");
59         return false;
60     }
61     if ((!zipFile_.ExtractFile(fileName, fileStream)) || (!fileStream.good())) {
62         fileStream.clear();
63         fileStream.close();
64         remove(filePath.c_str());
65         return false;
66     }
67     fileStream.clear();
68     fileStream.close();
69 
70     int fd = open(filePath.c_str(), O_RDWR, S_IRUSR | S_IWUSR);
71     if (fd < 0) {
72         HILOG_ERROR(HILOG_MODULE_APP, "ExtractFileToPath open fail");
73         return false;
74     }
75     fsync(fd);
76     close(fd);
77     return true;
78 }
79 
GetZipFileNames() const80 const std::vector<std::string> &ExtractorUtil::GetZipFileNames() const
81 {
82     return zipFile_.GetFileNames();
83 }
84 } // namespace OHOS