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 <cinttypes>
19 #include <climits>
20 #include <fstream>
21 #include <iostream>
22 #include <sstream>
23 #include <stack>
24 #include <string>
25 #include <sys/stat.h>
26 #include <sys/statfs.h>
27 #include <unistd.h>
28 #include <vector>
29
30 #include "constant.h"
31 #include "update_log.h"
32
33 namespace OHOS {
34 namespace UpdateEngine {
35 std::map<std::string, int32_t> FileUtils::baseDirMap_;
36
GetFileSize(const std::string & fileName)37 int64_t FileUtils::GetFileSize(const std::string &fileName)
38 {
39 std::error_code errorCode;
40 int64_t fileSize = static_cast<int64_t>(std::filesystem::file_size(fileName, errorCode));
41 if (errorCode.operator bool()) {
42 ENGINE_LOGE("get file size error, file = %{public}s", fileName.c_str());
43 return 0;
44 }
45 return fileSize;
46 }
47
IsFileExist(const std::string & fileName)48 bool FileUtils::IsFileExist(const std::string &fileName)
49 {
50 std::ifstream f(fileName.c_str());
51 return f.good();
52 }
53
IsSpaceEnough(const std::string & filePath,const int64_t requiredSpace)54 bool FileUtils::IsSpaceEnough(const std::string &filePath, const int64_t requiredSpace)
55 {
56 uint64_t freeSpace = 0;
57 struct statfs diskStatfs;
58 int ret = statfs(filePath.c_str(), &diskStatfs);
59 if (ret >= 0) {
60 freeSpace = (uint64_t)diskStatfs.f_bsize * (uint64_t)diskStatfs.f_bavail;
61 } else {
62 ENGINE_LOGE("statfs fail, error code = %{public}d", ret);
63 }
64 ENGINE_LOGI("free space=%{public}" PRIu64 ", required space=%{public}" PRIu64 "", freeSpace,
65 static_cast<uint64_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.length() > 0 && fileDir.back() == '/') {
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 char dealPath[PATH_MAX] = {};
208 if (realpath(filePath.c_str(), dealPath) == nullptr) {
209 ENGINE_LOGE("filePath %{private}s is not exist or invalid", filePath.c_str());
210 return "";
211 }
212 std::ifstream readFile;
213 readFile.open(dealPath);
214 if (readFile.fail()) {
215 ENGINE_LOGI("open file from %{public}s err", filePath.c_str());
216 return "";
217 }
218 std::stringstream streamBuffer;
219 streamBuffer << readFile.rdbuf();
220 std::string fileRaw(streamBuffer.str());
221 readFile.close();
222 return fileRaw;
223 }
224 } // namespace UpdateEngine
225 } // namespace OHOS
226