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 "file_utils.h"
17
18 #include <fstream>
19 #include <iostream>
20 #include <sstream>
21 #include <stack>
22 #include <string>
23 #include <sys/stat.h>
24 #include <sys/statfs.h>
25 #include <unistd.h>
26 #include <vector>
27
28 #include "constant.h"
29 #include "update_helper.h"
30 #include "update_log.h"
31
32 namespace OHOS {
33 namespace UpdateEngine {
34 std::map<std::string, int32_t> FileUtils::baseDirMap_;
35
GetFileSize(const std::string & fileName)36 int64_t FileUtils::GetFileSize(const std::string &fileName)
37 {
38 std::error_code errorCode;
39 int64_t fileSize = static_cast<int64_t>(std::filesystem::file_size(fileName, errorCode));
40 if (errorCode.operator bool()) {
41 ENGINE_LOGE("get file size error, file = %{public}s", fileName.c_str());
42 return 0;
43 }
44 return fileSize;
45 }
46
IsFileExist(const std::string & fileName)47 bool FileUtils::IsFileExist(const std::string &fileName)
48 {
49 std::ifstream f(fileName.c_str());
50 return f.good();
51 }
52
IsSpaceEnough(const std::string & filePath,const int64_t requiredSpace)53 bool FileUtils::IsSpaceEnough(const std::string &filePath, const int64_t requiredSpace)
54 {
55 std::error_code errorCode;
56 uint64_t freeSpace = 0;
57 const std::filesystem::space_info spaceInfo = std::filesystem::space(filePath, errorCode);
58 if (errorCode.operator bool()) {
59 ENGINE_LOGE("get disk free error, error code = %d", errorCode.value());
60 } else {
61 freeSpace = static_cast<std::uint64_t>(spaceInfo.free);
62 ENGINE_LOGI("free space of [%s] is [%lu]", filePath.c_str(), (unsigned long long)freeSpace);
63 }
64 ENGINE_LOGI("free space=%{public}lu, required space=%{public}ld", static_cast<uint64_t>(freeSpace),
65 static_cast<int64_t>(requiredSpace));
66 return freeSpace >= static_cast<uint64_t>(requiredSpace);
67 }
68
SaveDataToFile(const std::string & filePath,const std::string & data)69 bool FileUtils::SaveDataToFile(const std::string &filePath, const std::string &data)
70 {
71 std::ofstream os;
72 os.open(filePath, std::ios::trunc);
73 if (os.is_open()) {
74 ENGINE_LOGI("SaveDataToFile success, file = %{public}s", filePath.c_str());
75 os << data;
76 os.close();
77 return true;
78 }
79 ENGINE_LOGE("SaveDataToFile fail, file = %{public}s", filePath.c_str());
80 os.close();
81 return false;
82 }
83
DeleteFile(const std::string & rootPath,bool isDeleteRootDir)84 void FileUtils::DeleteFile(const std::string &rootPath, bool isDeleteRootDir)
85 {
86 if (!IsFileExist(rootPath)) {
87 ENGINE_LOGE("dir[%{public}s] is not exist", rootPath.c_str());
88 return;
89 }
90
91 auto myPath = std::filesystem::path(rootPath);
92 if (isDeleteRootDir) {
93 RemoveAll(myPath);
94 return;
95 }
96
97 for (auto const &dirEntry : std::filesystem::directory_iterator { myPath }) {
98 RemoveAll(dirEntry.path());
99 }
100 }
101
RemoveAll(const std::filesystem::path & path)102 void FileUtils::RemoveAll(const std::filesystem::path &path)
103 {
104 std::error_code errorCode;
105 std::filesystem::remove_all(path, errorCode);
106 if (errorCode.operator bool()) {
107 ENGINE_LOGE("remove dir[%{public}s] fail, error message : %{public}s", path.c_str(),
108 errorCode.message().c_str());
109 } else {
110 ENGINE_LOGI("remove dir[%{public}s] success", path.c_str());
111 }
112 }
113
114 // 此函数功能为创建多层目录,支持a/b和a/b/这两种形式,最终的结果为创建a目录以及b目录
CreateMultiDirWithPermission(const std::string & fileDir,int32_t permission)115 bool FileUtils::CreateMultiDirWithPermission(const std::string &fileDir, int32_t permission)
116 {
117 std::string curDir = GetCurrentDir(fileDir);
118 if (IsFileExist(curDir)) {
119 return true;
120 }
121 std::stack<std::string> dirStack;
122 do {
123 dirStack.push(curDir);
124 curDir = GetParentDir(curDir);
125 } while (!curDir.empty() && !IsFileExist(curDir));
126
127 while (!dirStack.empty()) {
128 if (!CreatDirWithPermission(dirStack.top(), baseDirMap_.count(fileDir) ? baseDirMap_[fileDir] : permission)) {
129 return false;
130 };
131 dirStack.pop();
132 }
133 return true;
134 }
135
GetParentDir(const std::string & fileDir)136 std::string FileUtils::GetParentDir(const std::string &fileDir)
137 {
138 auto curDir = std::filesystem::path(fileDir);
139 ENGINE_LOGI("dirPath = %s", curDir.parent_path().string().c_str());
140 return curDir.parent_path().string();
141 }
142
GetCurrentDir(const std::string & fileDir)143 std::string FileUtils::GetCurrentDir(const std::string &fileDir)
144 {
145 // 兼容传递的文件夹路径,末尾带0-N个'/'均ok
146 if (fileDir[fileDir.length() - 1] == '/') {
147 return GetParentDir(fileDir);
148 }
149 return fileDir;
150 }
151
152 // 按需创建基础目录,并且将需要创建的基础目录放在baseDirMap中,用于后续创建目录判断权限
InitAndCreateBaseDirs(const std::vector<DirInfo> & dirInfos)153 void FileUtils::InitAndCreateBaseDirs(const std::vector<DirInfo> &dirInfos)
154 {
155 if (dirInfos.empty()) {
156 ENGINE_LOGE("dirInfo is empty");
157 return;
158 }
159 for (const auto &dirInfo : dirInfos) {
160 baseDirMap_[dirInfo.dirName] = dirInfo.dirPermissions;
161 if (!IsFileExist(dirInfo.dirName)) {
162 CreatDirWithPermission(dirInfo.dirName, dirInfo.dirPermissions);
163 }
164 }
165 }
166
DestroyBaseDirectory(const std::vector<DirInfo> & dirInfos)167 void FileUtils::DestroyBaseDirectory(const std::vector<DirInfo> &dirInfos)
168 {
169 ENGINE_LOGI("destroy base directory");
170 if (dirInfos.empty()) {
171 ENGINE_LOGE("dirInfo is empty");
172 return;
173 }
174
175 for (const auto &dir : dirInfos) {
176 if (dir.isAllowDestroyContents) {
177 DeleteFile(dir.dirName, false);
178 }
179 }
180 }
181
CreatDirWithPermission(const std::string & fileDir,int32_t dirPermission)182 bool FileUtils::CreatDirWithPermission(const std::string &fileDir, int32_t dirPermission)
183 {
184 if (fileDir.empty() || strstr(fileDir.c_str(), "/.") != NULL || strstr(fileDir.c_str(), "./") != NULL) {
185 ENGINE_LOGE("dirName %{public}s is invalid", fileDir.c_str());
186 return false;
187 }
188 std::error_code errorCode;
189 std::filesystem::create_directory(fileDir, errorCode);
190 if (errorCode.operator bool()) {
191 ENGINE_LOGE("Create directory dir[%s] fail, error message : %{public}s", fileDir.c_str(),
192 errorCode.message().c_str());
193 return false;
194 }
195 std::filesystem::permissions(fileDir, static_cast<std::filesystem::perms>(dirPermission),
196 std::filesystem::perm_options::replace, errorCode);
197 if (errorCode.operator bool()) {
198 ENGINE_LOGE("Assign permissions failed, path = %{public}s,error message : %{public}s", fileDir.c_str(),
199 errorCode.message().c_str());
200 return false;
201 }
202 return true;
203 }
204
ReadDataFromFile(const std::string & filePath)205 std::string FileUtils::ReadDataFromFile(const std::string &filePath)
206 {
207 std::ifstream readFile;
208 readFile.open(filePath);
209 if (readFile.fail()) {
210 ENGINE_LOGI("open file from %{public}s err", filePath.c_str());
211 return "";
212 }
213 std::stringstream streamBuffer;
214 streamBuffer << readFile.rdbuf();
215 std::string fileRaw(streamBuffer.str());
216 readFile.close();
217 return fileRaw;
218 }
219 } // namespace UpdateEngine
220 } // namespace OHOS
221