• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 "utils/file_utils.h"
17 
18 #include <cerrno>
19 #include <cstdlib>
20 #include <cstring>
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <fstream>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28 #include "securec.h"
29 #include "storage_service_errno.h"
30 #include "storage_service_log.h"
31 #include "string_ex.h"
32 #ifdef USE_LIBRESTORECON
33 #include "policycoreutils.h"
34 #endif
35 namespace OHOS {
36 namespace StorageDaemon {
37 constexpr uint32_t ALL_PERMS = (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
38 const int BUF_LEN = 1024;
39 
ChMod(const std::string & path,mode_t mode)40 int32_t ChMod(const std::string &path, mode_t mode)
41 {
42     return TEMP_FAILURE_RETRY(chmod(path.c_str(), mode));
43 }
44 
ChOwn(const std::string & path,uid_t uid,gid_t gid)45 int32_t ChOwn(const std::string &path, uid_t uid, gid_t gid)
46 {
47     return TEMP_FAILURE_RETRY(chown(path.c_str(), uid, gid));
48 }
49 
MkDir(const std::string & path,mode_t mode)50 int32_t MkDir(const std::string &path, mode_t mode)
51 {
52     return TEMP_FAILURE_RETRY(mkdir(path.c_str(), mode));
53 }
54 
RmDir(const std::string & path)55 int32_t RmDir(const std::string &path)
56 {
57     return TEMP_FAILURE_RETRY(rmdir(path.c_str()));
58 }
59 
Mount(const std::string & source,const std::string & target,const char * type,unsigned long flags,const void * data)60 int32_t Mount(const std::string &source, const std::string &target, const char *type,
61               unsigned long flags, const void *data)
62 {
63     return TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), type, flags, data));
64 }
65 
UMount(const std::string & path)66 int32_t UMount(const std::string &path)
67 {
68     return TEMP_FAILURE_RETRY(umount(path.c_str()));
69 }
70 
UMount2(const std::string & path,int flag)71 int32_t UMount2(const std::string &path, int flag)
72 {
73     return TEMP_FAILURE_RETRY(umount2(path.c_str(), flag));
74 }
75 
IsDir(const std::string & path)76 bool IsDir(const std::string &path)
77 {
78     // check whether the path exists
79     struct stat st;
80     int ret = TEMP_FAILURE_RETRY(lstat(path.c_str(), &st));
81     if (ret) {
82         return false;
83     }
84 
85     return S_ISDIR(st.st_mode);
86 }
87 
MkDirRecurse(const std::string & path,mode_t mode)88 bool MkDirRecurse(const std::string& path, mode_t mode)
89 {
90     std::string::size_type index = 0;
91     do {
92         std::string subPath = path;
93         index = path.find('/', index + 1);
94         if (index != std::string::npos) {
95             subPath = path.substr(0, index);
96         }
97 
98         if (TEMP_FAILURE_RETRY(access(subPath.c_str(), F_OK)) != 0) {
99             if (MkDir(subPath, mode) != 0 && errno != EEXIST) {
100                 return false;
101             }
102         }
103     } while (index != std::string::npos);
104 
105     return TEMP_FAILURE_RETRY(access(path.c_str(), F_OK)) == 0;
106 }
107 
108 // On success, true is returned.  On error, false is returned, and errno is set appropriately.
PrepareDir(const std::string & path,mode_t mode,uid_t uid,gid_t gid)109 bool PrepareDir(const std::string &path, mode_t mode, uid_t uid, gid_t gid)
110 {
111     LOGI("prepare for %{public}s", path.c_str());
112 
113     // check whether the path exists
114     struct stat st;
115     if (TEMP_FAILURE_RETRY(lstat(path.c_str(), &st)) == E_ERR) {
116         if (errno != ENOENT) {
117             LOGE("failed to lstat, errno %{public}d", errno);
118             return false;
119         }
120     } else {
121         if (!S_ISDIR(st.st_mode)) {
122             LOGE("%{public}s exists and is not a directory", path.c_str());
123             return false;
124         }
125 
126         if (((st.st_mode & ALL_PERMS) != mode) && ChMod(path, mode)) {
127             LOGE("dir exists and failed to chmod, errno %{public}d", errno);
128             return false;
129         }
130 
131         if (((st.st_uid != uid) || (st.st_gid != gid)) && ChOwn(path, uid, gid)) {
132             LOGE("dir exists and failed to chown, errno %{public}d", errno);
133             return false;
134         }
135 
136         return true;
137     }
138 
139     mode_t mask = umask(0);
140     if (MkDir(path, mode)) {
141         LOGE("failed to mkdir, errno %{public}d", errno);
142         umask(mask);
143         return false;
144     }
145     umask(mask);
146 
147     if (ChMod(path, mode)) {
148         LOGE("failed to chmod, errno %{public}d", errno);
149         return false;
150     }
151 
152     if (ChOwn(path, uid, gid)) {
153         LOGE("failed to chown, errno %{public}d", errno);
154         return false;
155     }
156 
157 #ifdef USE_LIBRESTORECON
158     int err = Restorecon(path.c_str());
159     if (err) {
160         LOGE("failed to restorecon, err:%{public}d", err);
161         return false;
162     }
163 #endif
164 
165     return true;
166 }
167 
RmDirRecurse(const std::string & path)168 bool RmDirRecurse(const std::string &path)
169 {
170     LOGI("rm dir %{public}s", path.c_str());
171 
172     DIR *dir = opendir(path.c_str());
173     if (!dir) {
174         if (errno == ENOENT) {
175             return true;
176         }
177 
178         LOGE("failed to open dir %{public}s, errno %{public}d", path.c_str(), errno);
179         return false;
180     }
181 
182     for (struct dirent *ent = readdir(dir); ent != nullptr; ent = readdir(dir)) {
183         if (ent->d_type == DT_DIR) {
184             if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {
185                 continue;
186             }
187 
188             if (!RmDirRecurse(path + "/" + ent->d_name)) {
189                 (void)closedir(dir);
190                 return false;
191             }
192         } else {
193             if (unlink((path + "/" + ent->d_name).c_str())) {
194                 LOGE("failed to unlink file %{public}s, errno %{public}d", ent->d_name, errno);
195                 (void)closedir(dir);
196                 return false;
197             }
198         }
199     }
200 
201     (void)closedir(dir);
202     if (rmdir(path.c_str())) {
203         LOGE("failed to rm dir %{public}s, errno %{public}d", path.c_str(), errno);
204         return false;
205     }
206 
207     return true;
208 }
209 
TravelChmod(std::string path,mode_t mode)210 void TravelChmod(std::string path, mode_t mode)
211 {
212     struct stat st;
213     DIR *d = NULL;
214     struct dirent *dp = NULL;
215     const char *skip1 = ".";
216     const char *skip2 = "..";
217 
218     if (stat(path.c_str(), &st) < 0 || !S_ISDIR(st.st_mode)) {
219         LOGE("invalid path");
220         return;
221     }
222 
223     (void)ChMod(path, mode);
224     if (!(d = opendir(path.c_str()))) {
225         LOGE("opendir failed");
226         return;
227     }
228 
229     while ((dp = readdir(d)) != NULL) {
230         if ((!strncmp(dp->d_name, skip1, strlen(skip1))) || (!strncmp(dp->d_name, skip2, strlen(skip2))))
231             continue;
232 
233         std::string subpath = path + "/" + dp->d_name;
234         stat(subpath.c_str(), &st);
235         (void)ChMod(subpath, mode);
236         if (S_ISDIR(st.st_mode))
237             TravelChmod(subpath, mode);
238     }
239     (void)closedir(d);
240 }
241 
StringToUint32(const std::string & str,uint32_t & num)242 bool StringToUint32(const std::string &str, uint32_t &num)
243 {
244     if (str.empty()) {
245         return false;
246     }
247     if (!IsNumericStr(str)) {
248         LOGE("Not numeric entry");
249         return false;
250     }
251 
252     int value;
253     if (!StrToInt(str, value)) {
254         LOGE("String to int convert failed");
255         return false;
256     }
257     num = static_cast<uint32_t>(value);
258 
259     return true;
260 }
261 
GetSubDirs(const std::string & path,std::vector<std::string> & dirList)262 void GetSubDirs(const std::string &path, std::vector<std::string> &dirList)
263 {
264     dirList.clear();
265 
266     struct stat st;
267     int ret = TEMP_FAILURE_RETRY(lstat(path.c_str(), &st));
268     if (ret != 0 || ((st.st_mode & S_IFDIR) != S_IFDIR)) {
269         LOGE("path is not dir");
270         return;
271     }
272 
273     DIR *dir = opendir(path.c_str());
274     if (!dir) {
275         LOGE("failed to open dir %{public}s, errno %{public}d", path.c_str(), errno);
276         return;
277     }
278 
279     for (struct dirent *ent = readdir(dir); ent != nullptr; ent = readdir(dir)) {
280         if ((ent->d_type != DT_DIR) ||
281             (strcmp(ent->d_name, ".") == 0) ||
282             (strcmp(ent->d_name, "..") == 0)) {
283             continue;
284         }
285         dirList.push_back(ent->d_name);
286     }
287 
288     (void)closedir(dir);
289 }
290 
ReadDigitDir(const std::string & path,std::vector<FileList> & dirInfo)291 void ReadDigitDir(const std::string &path, std::vector<FileList> &dirInfo)
292 {
293     struct stat st;
294     int ret = TEMP_FAILURE_RETRY(lstat(path.c_str(), &st));
295     if (ret != 0 || ((st.st_mode & S_IFDIR) != S_IFDIR)) {
296         LOGE("path is not dir");
297         return;
298     }
299 
300     DIR *dir = opendir(path.c_str());
301     if (!dir) {
302         LOGE("failed to open dir %{public}s, errno %{public}d", path.c_str(), errno);
303         return;
304     }
305 
306     for (struct dirent *ent = readdir(dir); ent != nullptr; ent = readdir(dir)) {
307         if ((ent->d_type != DT_DIR) ||
308             (strcmp(ent->d_name, ".") == 0) ||
309             (strcmp(ent->d_name, "..") == 0)) {
310             continue;
311         }
312 
313         uint32_t userId;
314         std::string name(ent->d_name);
315         if (!StringToUint32(name, userId)) {
316             continue;
317         }
318         FileList entry = {
319             .userId = userId,
320             .path = path + "/" + name
321         };
322         dirInfo.push_back(entry);
323     }
324 
325     (void)closedir(dir);
326 }
327 
ReadFile(std::string path,std::string * str)328 bool ReadFile(std::string path, std::string *str)
329 {
330     std::ifstream infile;
331     int cnt = 0;
332 
333     std::string rpath(PATH_MAX + 1, '\0');
334     if ((path.length() > PATH_MAX) || (realpath(path.c_str(), rpath.data()) == nullptr)) {
335         LOGE("realpath failed");
336         return false;
337     }
338 
339     infile.open(rpath.c_str());
340     if (!infile) {
341         LOGE("Cannot open file");
342         return false;
343     }
344 
345     while (1) {
346         std::string subStr;
347         infile >> subStr;
348         if (subStr == "") {
349             break;
350         }
351         cnt++;
352         *str = *str + subStr + '\n';
353     }
354 
355     infile.close();
356     return cnt == 0 ? false : true;
357 }
358 
FromatCmd(std::vector<std::string> & cmd)359 static std::vector<char*> FromatCmd(std::vector<std::string> &cmd)
360 {
361     std::vector<char*>res;
362     res.reserve(cmd.size() + 1);
363 
364     for (auto& line : cmd) {
365         LOGI("cmd %{public}s", line.c_str());
366         res.emplace_back(const_cast<char*>(line.c_str()));
367     }
368     res.emplace_back(nullptr);
369 
370     return res;
371 }
372 
ForkExec(std::vector<std::string> & cmd,std::vector<std::string> * output)373 int ForkExec(std::vector<std::string> &cmd, std::vector<std::string> *output)
374 {
375     int pipe_fd[2];
376     pid_t pid;
377     int status;
378     auto args = FromatCmd(cmd);
379 
380     if (pipe(pipe_fd) < 0) {
381         LOGE("creat pipe failed");
382         return E_ERR;
383     }
384 
385     pid = fork();
386     if (pid == -1) {
387         LOGE("fork failed");
388         return E_ERR;
389     } else if (pid == 0) {
390         (void)close(pipe_fd[0]);
391         if (dup2(pipe_fd[1], STDOUT_FILENO) == -1) {
392             LOGE("dup2 failed");
393             exit(1);
394         }
395         (void)close(pipe_fd[1]);
396         execvp(args[0], const_cast<char **>(args.data()));
397         exit(0);
398     } else {
399         (void)close(pipe_fd[1]);
400         if (output) {
401             char buf[BUF_LEN] = { 0 };
402             (void)memset_s(buf, sizeof(buf), 0, sizeof(buf));
403             output->clear();
404             while (read(pipe_fd[0], buf, BUF_LEN - 1) > 0) {
405                 LOGI("get result %{public}s", buf);
406                 output->push_back(buf);
407             }
408             return E_OK;
409         }
410 
411         waitpid(pid, &status, 0);
412         if (errno == ECHILD) {
413             return E_NO_CHILD;
414         }
415         if (!WIFEXITED(status)) {
416             LOGE("Process exits abnormally");
417             return E_ERR;
418         }
419     }
420     return E_OK;
421 }
422 
TraverseDirUevent(const std::string & path,bool flag)423 void TraverseDirUevent(const std::string &path, bool flag)
424 {
425     DIR *dir = opendir(path.c_str());
426     if (dir == nullptr) {
427         return;
428     }
429 
430     int dirFd = dirfd(dir);
431     int fd = openat(dirFd, "uevent", O_WRONLY | O_CLOEXEC);
432     if (fd >= 0) {
433         std::string writeStr = "add\n";
434         write(fd, writeStr.c_str(), writeStr.length());
435         (void)close(fd);
436     }
437 
438     for (struct dirent *ent = readdir(dir); ent != nullptr; ent = readdir(dir)) {
439         if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {
440             continue;
441         }
442 
443         if (ent->d_type != DT_DIR && !flag) {
444             continue;
445         }
446 
447         TraverseDirUevent(path + "/" + ent->d_name, false);
448     }
449 
450     (void)closedir(dir);
451 }
452 } // STORAGE_DAEMON
453 } // OHOS
454