1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "path.h"
18 
19 #include <android-base/logging.h>
20 
21 #include <memory>
22 
23 #include <dirent.h>
24 #include <errno.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 
30 using namespace std::literals;
31 
32 namespace android::incfs::path {
33 
34 namespace {
35 
36 class CStrWrapper {
37 public:
CStrWrapper(std::string_view sv)38     CStrWrapper(std::string_view sv) {
39         if (sv[sv.size()] == '\0') {
40             mCstr = sv.data();
41         } else {
42             mCopy.emplace(sv);
43             mCstr = mCopy->c_str();
44         }
45     }
46 
47     CStrWrapper(const CStrWrapper&) = delete;
48     void operator=(const CStrWrapper&) = delete;
49     CStrWrapper(CStrWrapper&&) = delete;
50     void operator=(CStrWrapper&&) = delete;
51 
get() const52     const char* get() const { return mCstr; }
operator const char*() const53     operator const char*() const { return get(); }
54 
55 private:
56     const char* mCstr;
57     std::optional<std::string> mCopy;
58 };
59 
c_str(std::string_view sv)60 inline CStrWrapper c_str(std::string_view sv) {
61     return {sv};
62 }
63 
64 } // namespace
65 
isAbsolute(std::string_view path)66 bool isAbsolute(std::string_view path) {
67     return !path.empty() && path[0] == '/';
68 }
69 
normalize(std::string_view path)70 std::string normalize(std::string_view path) {
71     if (path.empty()) {
72         return {};
73     }
74     if (path.starts_with("../"sv)) {
75         return {};
76     }
77 
78     std::string result;
79     if (isAbsolute(path)) {
80         path.remove_prefix(1);
81     } else {
82         char buffer[PATH_MAX];
83         if (!::getcwd(buffer, sizeof(buffer))) {
84             return {};
85         }
86         result += buffer;
87     }
88 
89     size_t start = 0;
90     size_t end = 0;
91     for (; end != path.npos; start = end + 1) {
92         end = path.find('/', start);
93         // Next component, excluding the separator
94         auto part = path.substr(start, end - start);
95         if (part.empty() || part == "."sv) {
96             continue;
97         }
98         if (part == ".."sv) {
99             if (result.empty()) {
100                 return {};
101             }
102             auto lastPos = result.rfind('/');
103             if (lastPos == result.npos) {
104                 result.clear();
105             } else {
106                 result.resize(lastPos);
107             }
108             continue;
109         }
110         result += '/';
111         result += part;
112     }
113 
114     return result;
115 }
116 
117 static constexpr char fdNameFormat[] = "/proc/self/fd/%d";
118 
procfsForFd(int fd)119 std::string procfsForFd(int fd) {
120     char fdNameBuffer[std::size(fdNameFormat) + 11 + 1]; // max int length + '\0'
121     snprintf(fdNameBuffer, std::size(fdNameBuffer), fdNameFormat, fd);
122     return fdNameBuffer;
123 }
124 
fromFd(int fd)125 std::string fromFd(int fd) {
126     char fdNameBuffer[std::size(fdNameFormat) + 11 + 1]; // max int length + '\0'
127     snprintf(fdNameBuffer, std::size(fdNameBuffer), fdNameFormat, fd);
128 
129     return readlink(fdNameBuffer);
130 }
131 
readlink(std::string_view path)132 std::string readlink(std::string_view path) {
133     static constexpr auto kDeletedSuffix = " (deleted)"sv;
134 
135     auto cPath = c_str(path);
136     std::string res;
137     // We used to call lstat() here to preallocate the buffer to the exact required size; turns out
138     // that call is significantly more expensive than anything else, so doing a couple extra
139     // iterations is worth the savings.
140     auto bufSize = 256;
141     for (;;) {
142         res.resize(bufSize - 1, '\0');
143         auto size = ::readlink(cPath, &res[0], res.size());
144         if (size < 0) {
145             PLOG(ERROR) << "readlink failed for " << path;
146             return {};
147         }
148         if (size >= ssize_t(res.size())) {
149             // can't tell if the name is exactly that long, or got truncated - just repeat the call.
150             bufSize *= 2;
151             continue;
152         }
153         res.resize(size);
154         if (res.ends_with(kDeletedSuffix)) {
155             res.resize(size - kDeletedSuffix.size());
156         }
157         return res;
158     }
159 }
160 
preparePathComponent(std::string_view & path,bool trimAll)161 static void preparePathComponent(std::string_view& path, bool trimAll) {
162     // need to check for double front slash as a single one has a separate meaning in front
163     while (!path.empty() && path.front() == '/' &&
164            (trimAll || (path.size() > 1 && path[1] == '/'))) {
165         path.remove_prefix(1);
166     }
167     // for the back we don't care about double-vs-single slash difference
168     while (path.size() > !trimAll && path.back() == '/') {
169         path.remove_suffix(1);
170     }
171 }
172 
relativize(std::string_view parent,std::string_view nested)173 std::string_view relativize(std::string_view parent, std::string_view nested) {
174     if (!nested.starts_with(parent)) {
175         return nested;
176     }
177     if (nested.size() == parent.size()) {
178         return {};
179     }
180     if (nested[parent.size()] != '/') {
181         return nested;
182     }
183     auto relative = nested.substr(parent.size());
184     while (relative.front() == '/') {
185         relative.remove_prefix(1);
186     }
187     return relative;
188 }
189 
appendNextPath(std::string & res,std::string_view path)190 void details::appendNextPath(std::string& res, std::string_view path) {
191     preparePathComponent(path, !res.empty());
192     if (path.empty()) {
193         return;
194     }
195     if (!res.empty() && !res.ends_with('/')) {
196         res.push_back('/');
197     }
198     res += path;
199 }
200 
splitDirBase(std::string & full)201 std::pair<std::string_view, std::string_view> splitDirBase(std::string& full) {
202     auto res = std::pair(dirName(full), baseName(full));
203     if (res.first.data() == full.data()) {
204         full[res.first.size()] = 0;
205     }
206     return res;
207 }
208 
isEmptyDir(std::string_view dir)209 int isEmptyDir(std::string_view dir) {
210     const auto d = std::unique_ptr<DIR, decltype(&::closedir)>{::opendir(c_str(dir)), ::closedir};
211     if (!d) {
212         return -errno;
213     }
214     while (const auto entry = ::readdir(d.get())) {
215         if (entry->d_type != DT_DIR) {
216             return -ENOTEMPTY;
217         }
218         if (entry->d_name != "."sv && entry->d_name != ".."sv) {
219             return -ENOTEMPTY;
220         }
221     }
222     return 0;
223 }
224 
startsWith(std::string_view path,std::string_view prefix)225 bool startsWith(std::string_view path, std::string_view prefix) {
226     if (!path.starts_with(prefix)) {
227         return false;
228     }
229     return path.size() == prefix.size() || path[prefix.size()] == '/';
230 }
231 
endsWith(std::string_view path,std::string_view suffix)232 bool endsWith(std::string_view path, std::string_view suffix) {
233     if (!path.ends_with(suffix)) {
234         return false;
235     }
236     return path.size() == suffix.size() || path[path.size() - suffix.size() - 1] == '/';
237 }
238 
239 } // namespace android::incfs::path
240