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
fromFd(int fd)117 std::string fromFd(int fd) {
118 static constexpr auto kDeletedSuffix = " (deleted)"sv;
119 static constexpr char fdNameFormat[] = "/proc/self/fd/%d";
120 char fdNameBuffer[std::size(fdNameFormat) + 11 + 1]; // max int length + '\0'
121 snprintf(fdNameBuffer, std::size(fdNameBuffer), fdNameFormat, fd);
122
123 std::string res;
124 // We used to call lstat() here to preallocate the buffer to the exact required size; turns out
125 // that call is significantly more expensive than anything else, so doing a couple extra
126 // iterations is worth the savings.
127 auto bufSize = 256;
128 for (;;) {
129 res.resize(bufSize - 1, '\0');
130 auto size = ::readlink(fdNameBuffer, &res[0], res.size());
131 if (size < 0) {
132 PLOG(ERROR) << "readlink failed for " << fdNameBuffer;
133 return {};
134 }
135 if (size >= ssize_t(res.size())) {
136 // can't tell if the name is exactly that long, or got truncated - just repeat the call.
137 bufSize *= 2;
138 continue;
139 }
140 res.resize(size);
141 if (res.ends_with(kDeletedSuffix)) {
142 res.resize(size - kDeletedSuffix.size());
143 }
144 return res;
145 }
146 }
147
preparePathComponent(std::string_view & path,bool trimAll)148 static void preparePathComponent(std::string_view& path, bool trimAll) {
149 // need to check for double front slash as a single one has a separate meaning in front
150 while (!path.empty() && path.front() == '/' &&
151 (trimAll || (path.size() > 1 && path[1] == '/'))) {
152 path.remove_prefix(1);
153 }
154 // for the back we don't care about double-vs-single slash difference
155 while (path.size() > !trimAll && path.back() == '/') {
156 path.remove_suffix(1);
157 }
158 }
159
relativize(std::string_view parent,std::string_view nested)160 std::string_view relativize(std::string_view parent, std::string_view nested) {
161 if (!nested.starts_with(parent)) {
162 return nested;
163 }
164 if (nested.size() == parent.size()) {
165 return {};
166 }
167 if (nested[parent.size()] != '/') {
168 return nested;
169 }
170 auto relative = nested.substr(parent.size());
171 while (relative.front() == '/') {
172 relative.remove_prefix(1);
173 }
174 return relative;
175 }
176
appendNextPath(std::string & res,std::string_view path)177 void details::appendNextPath(std::string& res, std::string_view path) {
178 preparePathComponent(path, !res.empty());
179 if (path.empty()) {
180 return;
181 }
182 if (!res.empty() && !res.ends_with('/')) {
183 res.push_back('/');
184 }
185 res += path;
186 }
187
splitDirBase(std::string & full)188 std::pair<std::string_view, std::string_view> splitDirBase(std::string& full) {
189 auto res = std::pair(dirName(full), baseName(full));
190 if (res.first.data() == full.data()) {
191 full[res.first.size()] = 0;
192 }
193 return res;
194 }
195
isEmptyDir(std::string_view dir)196 int isEmptyDir(std::string_view dir) {
197 const auto d = std::unique_ptr<DIR, decltype(&::closedir)>{::opendir(c_str(dir)), ::closedir};
198 if (!d) {
199 return -errno;
200 }
201 while (const auto entry = ::readdir(d.get())) {
202 if (entry->d_type != DT_DIR) {
203 return -ENOTEMPTY;
204 }
205 if (entry->d_name != "."sv && entry->d_name != ".."sv) {
206 return -ENOTEMPTY;
207 }
208 }
209 return 0;
210 }
211
startsWith(std::string_view path,std::string_view prefix)212 bool startsWith(std::string_view path, std::string_view prefix) {
213 if (!path.starts_with(prefix)) {
214 return false;
215 }
216 return path.size() == prefix.size() || path[prefix.size()] == '/';
217 }
218
endsWith(std::string_view path,std::string_view suffix)219 bool endsWith(std::string_view path, std::string_view suffix) {
220 if (!path.ends_with(suffix)) {
221 return false;
222 }
223 return path.size() == suffix.size() || path[path.size() - suffix.size() - 1] == '/';
224 }
225
226 } // namespace android::incfs::path
227