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 
16 #include "file_entry.h"
17 #include <cstring>
18 #include <fstream>
19 #include <iostream>
20 #include "dirent.h"
21 #include "sys/stat.h"
22 #include "unistd.h"
23 #ifdef _WIN32
24 #include "shlwapi.h"
25 #include "windows.h"
26 #endif
27 #include "resource_data.h"
28 
29 namespace OHOS {
30 namespace Global {
31 namespace Restool {
32 #ifdef _WIN32
33 const std::string FileEntry::SEPARATE = "\\";
34 #else
35 const std::string FileEntry::SEPARATE = "/";
36 #endif
37 
38 using namespace std;
FileEntry(const string &path)39 FileEntry::FileEntry(const string &path)
40     : filePath_(path), isFile_(false)
41 {
42 }
43 
~FileEntry()44 FileEntry::~FileEntry()
45 {
46 }
47 
Init()48 bool FileEntry::Init()
49 {
50     string filePath = filePath_.GetPath();
51     if (!Exist(filePath)) {
52         cerr << "Error: '" << filePath << "' not exists." << endl;
53         return false;
54     }
55 
56     isFile_ = !IsDirectory(filePath);
57     return true;
58 }
59 
GetChilds() const60 const vector<unique_ptr<FileEntry>> FileEntry::GetChilds() const
61 {
62     vector<unique_ptr<FileEntry>> children;
63     string filePath = filePath_.GetPath();
64 #ifdef _WIN32
65     WIN32_FIND_DATA findData;
66     string temp(filePath + "\\*.*");
67     HANDLE handle = FindFirstFile(AdaptLongPath(temp).c_str(), &findData);
68     if (handle == INVALID_HANDLE_VALUE) {
69         return children;
70     }
71 
72     do {
73         string filename(findData.cFileName);
74         if (IsIgnore(filename)) {
75             continue;
76         }
77 
78         filePath = filePath_.GetPath() + SEPARATE + filename;
79         unique_ptr<FileEntry> f = make_unique<FileEntry>(filePath);
80         f->Init();
81         children.push_back(move(f));
82     } while (FindNextFile(handle, &findData));
83     FindClose(handle);
84 #else
85     DIR *handle = opendir(filePath.c_str());
86     struct dirent *entry;
87     while ((entry = readdir(handle)) != nullptr) {
88         string filename(entry->d_name);
89         if (IsIgnore(filename)) {
90             continue;
91         }
92 
93         filePath = filePath_.GetPath() + SEPARATE + filename;
94         unique_ptr<FileEntry> f = make_unique<FileEntry>(filePath);
95         f->Init();
96         children.push_back(move(f));
97     }
98     closedir(handle);
99 #endif
100     return children;
101 }
102 
IsFile() const103 bool FileEntry::IsFile() const
104 {
105     return isFile_;
106 }
107 
GetFilePath() const108 const FileEntry::FilePath &FileEntry::GetFilePath() const
109 {
110     return filePath_;
111 }
112 
Exist(const string &path)113 bool FileEntry::Exist(const string &path)
114 {
115 #ifdef _WIN32
116     return PathFileExists(AdaptLongPath(path).c_str());
117 #else
118     struct stat s;
119     if (stat(path.c_str(), &s) != 0) {
120         return false;
121     }
122 #endif
123     return true;
124 }
125 
RemoveAllDir(const string &path)126 bool FileEntry::RemoveAllDir(const string &path)
127 {
128     FileEntry f(path);
129     if (!f.Init()) {
130         return false;
131     }
132 
133     if (f.IsFile()) {
134         cerr << "Error: RemoveAllDir '" << path << "' not directory." << endl;
135         return false;
136     }
137     return RemoveAllDirInner(f);
138 }
139 
RemoveFile(const string &path)140 bool FileEntry::RemoveFile(const string &path)
141 {
142     FileEntry f(path);
143     if (!f.Init()) {
144         return false;
145     }
146     return RemoveAllDirInner(f);
147 }
148 
CreateDirs(const string &path)149 bool FileEntry::CreateDirs(const string &path)
150 {
151     return CreateDirsInner(path, 0);
152 }
153 
CopyFileInner(const string &src, const string &dst)154 bool FileEntry::CopyFileInner(const string &src, const string &dst)
155 {
156 #ifdef _WIN32
157     if (!CopyFile(AdaptLongPath(src).c_str(), AdaptLongPath(dst).c_str(), false)) {
158         cerr << "Error: copy file fail from '" << src << "' to '" << dst << "'. reason:" << strerror(errno) << endl;
159         return false;
160     }
161 #else
162     ifstream in(src, ios::binary);
163     ofstream out(dst, ios::binary);
164     if (!in || !out) {
165         cerr << "Error: open failed '" << src << "' or '" << dst << "'. reason:" << strerror(errno) << endl;
166         return false;
167     }
168     out << in.rdbuf();
169 #endif
170     return true;
171 }
172 
IsDirectory(const string &path)173 bool FileEntry::IsDirectory(const string &path)
174 {
175 #ifdef _WIN32
176     if (!PathIsDirectory(AdaptLongPath(path).c_str())) {
177         return false;
178     }
179     return true;
180 #else
181     struct stat s;
182     stat(path.c_str(), &s);
183     return S_ISDIR(s.st_mode);
184 #endif
185 }
186 
RealPath(const string &path)187 string FileEntry::RealPath(const string &path)
188 {
189 #ifdef _WIN32
190     char buffer[MAX_PATH];
191     if (!PathCanonicalize(buffer, path.c_str())) {
192         return "";
193     }
194 
195     if (PathIsRelative(buffer)) {
196         char current[MAX_PATH];
197         if (!GetCurrentDirectory(MAX_PATH, current)) {
198             return "";
199         }
200 
201         char temp[MAX_PATH];
202         if (!PathCombine(temp, current, buffer)) {
203             return "";
204         }
205         if (!Exist(string(temp))) {
206             return "";
207         }
208         return string(temp);
209     }
210 #else
211     char buffer[PATH_MAX];
212     if (!realpath(path.c_str(), buffer)) {
213         return "";
214     }
215 #endif
216     if (!Exist(string(buffer))) {
217         return "";
218     }
219     return string(buffer);
220 }
221 
FilePath(const string &path)222 FileEntry::FilePath::FilePath(const string &path) : filePath_(path)
223 {
224     Format();
225     Init();
226 }
227 
~FilePath()228 FileEntry::FilePath::~FilePath()
229 {
230 }
231 
Append(const string &path)232 FileEntry::FilePath FileEntry::FilePath::Append(const string &path)
233 {
234     Format();
235     string filePath = filePath_ + SEPARATE + path;
236     return FilePath(filePath);
237 }
238 
ReplaceExtension(const string &extension)239 FileEntry::FilePath FileEntry::FilePath::ReplaceExtension(const string &extension)
240 {
241     string filePath;
242     if (!parent_.empty()) {
243         filePath += parent_ + SEPARATE;
244     }
245 
246     filePath += filename_.substr(0, filename_.length() - extension_.length()) + extension;
247     return FilePath(filePath);
248 }
249 
GetParent()250 FileEntry::FilePath FileEntry::FilePath::GetParent()
251 {
252     return FilePath(parent_);
253 }
254 
GetPath() const255 const string &FileEntry::FilePath::GetPath() const
256 {
257     return filePath_;
258 }
259 
GetFilename() const260 const string &FileEntry::FilePath::GetFilename() const
261 {
262     return filename_;
263 }
264 
GetExtension() const265 const string &FileEntry::FilePath::GetExtension() const
266 {
267     return extension_;
268 }
269 
GetSegments() const270 const vector<string> FileEntry::FilePath::GetSegments() const
271 {
272     vector<string> segments;
273     string::size_type offset = 0;
274     string::size_type pos = filePath_.find_first_of(SEPARATE.front(), offset);
275     while (pos != string::npos) {
276         segments.push_back(filePath_.substr(offset, pos - offset));
277         offset = pos + 1;
278         pos = filePath_.find_first_of(SEPARATE.front(), offset);
279     }
280 
281     if (offset < filePath_.length()) {
282         segments.push_back(filePath_.substr(offset));
283     }
284     return segments;
285 }
286 
287 // below private
IsIgnore(const string &filename) const288 bool FileEntry::IsIgnore(const string &filename) const
289 {
290     if (filename == "." || filename == "..") {
291         return true;
292     }
293     return false;
294 }
295 
RemoveAllDirInner(const FileEntry &entry)296 bool FileEntry::RemoveAllDirInner(const FileEntry &entry)
297 {
298     string path = entry.GetFilePath().GetPath();
299     if (entry.IsFile()) {
300 #ifdef _WIN32
301         bool result = remove(AdaptLongPath(path).c_str()) == 0;
302 #else
303         bool result = remove(path.c_str()) == 0;
304 #endif
305         if (!result) {
306             cerr << "Error: remove file '" << path << "' failed, reason: " << strerror(errno) << endl;
307             return false;
308         }
309         return true;
310     }
311 
312     for (const auto &iter : entry.GetChilds()) {
313         if (!RemoveAllDirInner(*iter)) {
314             return false;
315         }
316     }
317 #ifdef _WIN32
318     bool result = rmdir(AdaptLongPath(path).c_str()) == 0;
319 #else
320     bool result = rmdir(path.c_str()) == 0;
321 #endif
322     if (!result) {
323         cerr << "Error: remove directory '" << path << "' failed, reason: " << strerror(errno) << endl;
324         return false;
325     }
326     return true;
327 }
328 
CreateDirsInner(const string &path, string::size_type offset)329 bool FileEntry::CreateDirsInner(const string &path, string::size_type offset)
330 {
331     string::size_type pos = path.find_first_of(SEPARATE.front(), offset);
332     if (pos == string::npos) {
333 #ifdef _WIN32
334         return CreateDirectory(AdaptLongPath(path).c_str(), nullptr) != 0;
335 #else
336         return mkdir(path.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0;
337 #endif
338     }
339 
340     string subPath = path.substr(0, pos + 1);
341     if (!Exist(subPath)) {
342 #ifdef _WIN32
343         if (!CreateDirectory(AdaptLongPath(subPath).c_str(), nullptr)) {
344 #else
345         if (mkdir(subPath.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
346 #endif
347             return false;
348         }
349     }
350     return CreateDirsInner(path, pos + 1);
351 }
352 
353 void FileEntry::FilePath::Format()
354 {
355     if (filePath_.back() != SEPARATE.front()) {
356         return;
357     }
358     filePath_.pop_back();
359 }
360 
361 void FileEntry::FilePath::Init()
362 {
363     filename_ = filePath_;
364     string::size_type pos = filePath_.find_last_of(SEPARATE.front());
365     if (pos != string::npos) {
366         parent_ = filePath_.substr(0, pos);
367         if (pos + 1 < filePath_.length()) {
368             filename_ = filePath_.substr(pos + 1);
369         }
370     }
371 
372     pos = filename_.find_last_of('.');
373     if (pos != string::npos && pos + 1 < filename_.length()) {
374         extension_ = filename_.substr(pos);
375     }
376 }
377 
378 string FileEntry::AdaptLongPath(const string &path)
379 {
380 #ifdef _WIN32
381     if (path.size() >= MAX_PATH -12) { //the max file path can not exceed 260 - 12
382         return LONG_PATH_HEAD + path;
383     }
384 #endif
385     return path;
386 }
387 }
388 }
389 }
390