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