blob: f56f243de58ef0c13d0b02a25ad0996b199f8ca4 [file] [log] [blame]
Ethan Yonker00028b42014-04-09 14:29:02 -05001/*
2 Copyright 2014 TeamWin
3 This file is part of TWRP/TeamWin Recovery Project.
4
5 TWRP is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 TWRP is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with TWRP. If not, see <http://www.gnu.org/licenses/>.
17*/
18
19#include <string>
20#include <vector>
21#include <dirent.h>
22#include "find_file.hpp"
23#include "twrp-functions.hpp"
24#include "twcommon.h"
25
26using namespace std;
27
28string Find_File::Find(const string& file_name, const string& start_path) {
29 return Find_File().Find_Internal(file_name, start_path);
30}
31
32Find_File::Find_File() {
33}
34
35string Find_File::Find_Internal(const string& filename, const string& starting_path) {
36 DIR *d = opendir(starting_path.c_str());
37 string new_path, return_path;
38 vector<string> dirs;
39 vector<string> symlinks;
40 unsigned index;
41
42 // Check to see if we have already searched this directory to prevent infinite loops
43 if (std::find(searched_dirs.begin(), searched_dirs.end(), starting_path) != searched_dirs.end()) {
44 return "";
45 }
46 searched_dirs.push_back(starting_path);
47
48 if (d == NULL) {
49 LOGERR("Find_File: Error opening '%s'\n", starting_path.c_str());
50 return "";
51 }
52
53 struct dirent *p;
54 while ((p = readdir(d))) {
55 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
56 continue;
57 new_path = starting_path + "/";
58 new_path.append(p->d_name);
59 if (p->d_type == DT_DIR) {
60 // Add dir to search list for later
61 dirs.push_back(new_path);
62 } else if (p->d_type == DT_LNK) {
63 // Add symlink to search list for later
64 symlinks.push_back(new_path);
65 } else if (p->d_type == DT_REG && filename == p->d_name) {
66 // We found a match!
67 closedir(d);
68 return new_path;
69 }
70 }
71 closedir(d);
72
73 // Scan real directories first if no match found in this path
74 for (index = 0; index < dirs.size(); index++) {
75 return_path = Find_Internal(filename, dirs.at(index));
76 if (!return_path.empty()) return return_path;
77 }
78 // Scan symlinks after scanning real directories
79 for (index = 0; index < symlinks.size(); index++) {
80 char buf[PATH_MAX];
81 // Resolve symlink to a real path
82 char* ret = realpath(symlinks.at(index).c_str(), buf);
83 if (ret) {
84 return_path = Find_Internal(filename, buf);
85 if (!return_path.empty()) return return_path;
86 }
87 }
88 return "";
89}