• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define LOG_TAG "incfs-mounts"
18 
19 #include "MountRegistry.h"
20 
21 #include <android-base/logging.h>
22 #include <poll.h>
23 #include <stdlib.h>
24 
25 #include <charconv>
26 #include <set>
27 #include <unordered_map>
28 
29 #include "incfs.h"
30 #include "path.h"
31 #include "split.h"
32 
33 using namespace std::literals;
34 
35 namespace android::incfs {
36 
37 // /proc/self/mountinfo may have some special characters in paths replaced with their
38 // octal codes in the following pattern: '\xxx', e.g. \040 for space character.
39 // This function translates those patterns back into corresponding characters.
fixProcPath(std::string & path)40 static void fixProcPath(std::string& path) {
41     static const auto kPrefix = "\\"sv;
42     static const auto kPatternLength = 4;
43     auto pos = std::search(path.begin(), path.end(), kPrefix.begin(), kPrefix.end());
44     if (pos == path.end()) {
45         return;
46     }
47     auto dest = pos;
48     do {
49         if (path.end() - pos < kPatternLength || !std::equal(kPrefix.begin(), kPrefix.end(), pos)) {
50             *dest++ = *pos++;
51         } else {
52             int charCode;
53             auto res = std::from_chars(&*(pos + kPrefix.size()), &*(pos + kPatternLength), charCode,
54                                        8);
55             if (res.ec == std::errc{}) {
56                 *dest++ = char(charCode);
57             } else {
58                 // Didn't convert, let's keep it as is.
59                 dest = std::copy(pos, pos + kPatternLength, dest);
60                 pos += kPatternLength;
61             }
62         }
63     } while (pos != path.end());
64     path.erase(dest, path.end());
65 }
66 
binds() const67 std::vector<std::pair<std::string_view, std::string_view>> MountRegistry::Mounts::Mount::binds()
68         const {
69     std::vector<std::pair<std::string_view, std::string_view>> result;
70     result.reserve(mBase->binds.size());
71     for (auto it : mBase->binds) {
72         result.emplace_back(it->second.subdir, it->first);
73     }
74     return result;
75 }
76 
swap(MountRegistry::Mounts & other)77 void MountRegistry::Mounts::swap(MountRegistry::Mounts& other) {
78     roots.swap(other.roots);
79     rootByBindPoint.swap(other.rootByBindPoint);
80 }
81 
clear()82 void MountRegistry::Mounts::clear() {
83     roots.clear();
84     rootByBindPoint.clear();
85 }
86 
rootIndex(std::string_view path) const87 std::pair<int, MountRegistry::BindMap::const_iterator> MountRegistry::Mounts::rootIndex(
88         std::string_view path) const {
89     auto it = rootByBindPoint.lower_bound(path);
90     if (it != rootByBindPoint.end() && it->first == path) {
91         return {it->second.rootIndex, it};
92     }
93     if (it != rootByBindPoint.begin()) {
94         --it;
95         if (path::startsWith(path, it->first) && path.size() > it->first.size()) {
96             const auto index = it->second.rootIndex;
97             if (index >= int(roots.size()) || roots[index].empty()) {
98                 LOG(ERROR) << "[incfs] Root for path '" << path << "' #" << index
99                            << " is not valid";
100                 return {-1, {}};
101             }
102             return {index, it};
103         }
104     }
105     return {-1, {}};
106 }
107 
rootFor(std::string_view path) const108 std::string_view MountRegistry::Mounts::rootFor(std::string_view path) const {
109     auto [index, _] = rootIndex(path::normalize(path));
110     if (index < 0) {
111         return {};
112     }
113     return roots[index].path;
114 }
115 
rootAndSubpathFor(std::string_view path) const116 auto MountRegistry::Mounts::rootAndSubpathFor(std::string_view path) const
117         -> std::pair<const Root*, std::string> {
118     auto normalPath = path::normalize(path);
119     auto [index, bindIt] = rootIndex(normalPath);
120     if (index < 0) {
121         return {};
122     }
123 
124     const auto& bindSubdir = bindIt->second.subdir;
125     const auto pastBindSubdir = path::relativize(bindIt->first, normalPath);
126     const auto& root = roots[index];
127     return {&root, path::join(bindSubdir, pastBindSubdir)};
128 }
129 
addRoot(std::string_view root,std::string_view backingDir)130 void MountRegistry::Mounts::addRoot(std::string_view root, std::string_view backingDir) {
131     const auto index = roots.size();
132     auto absolute = path::normalize(root);
133     auto it = rootByBindPoint.insert_or_assign(absolute, Bind{std::string(), int(index)}).first;
134     roots.push_back({std::move(absolute), path::normalize(backingDir), {it}});
135 }
136 
removeRoot(std::string_view root)137 void MountRegistry::Mounts::removeRoot(std::string_view root) {
138     auto absolute = path::normalize(root);
139     auto it = rootByBindPoint.find(absolute);
140     if (it == rootByBindPoint.end()) {
141         LOG(WARNING) << "[incfs] Trying to remove non-existent root '" << root << '\'';
142         return;
143     }
144     const auto index = it->second.rootIndex;
145     if (index >= int(roots.size())) {
146         LOG(ERROR) << "[incfs] Root '" << root << "' has index " << index
147                    << " out of bounds (total roots count is " << roots.size();
148         return;
149     }
150 
151     for (auto bindIt : roots[index].binds) {
152         rootByBindPoint.erase(bindIt);
153     }
154 
155     if (index + 1 == int(roots.size())) {
156         roots.pop_back();
157         // Run a small GC job here as we may be able to remove some obsolete
158         // entries.
159         while (roots.back().empty()) {
160             roots.pop_back();
161         }
162     } else {
163         roots[index].clear();
164     }
165 }
166 
addBind(std::string_view what,std::string_view where)167 void MountRegistry::Mounts::addBind(std::string_view what, std::string_view where) {
168     auto whatAbsolute = path::normalize(what);
169     auto [root, rootIt] = rootIndex(whatAbsolute);
170     if (root < 0) {
171         LOG(ERROR) << "[incfs] No root found for bind from " << what << " to " << where;
172         return;
173     }
174 
175     const auto& currentBind = rootIt->first;
176     auto whatSubpath = path::relativize(currentBind, whatAbsolute);
177     const auto& subdir = rootIt->second.subdir;
178     auto realSubdir = path::join(subdir, whatSubpath);
179     auto it = rootByBindPoint
180                       .insert_or_assign(path::normalize(where), Bind{std::move(realSubdir), root})
181                       .first;
182     roots[root].binds.push_back(it);
183 }
184 
removeBind(std::string_view what)185 void MountRegistry::Mounts::removeBind(std::string_view what) {
186     auto absolute = path::normalize(what);
187     auto [root, rootIt] = rootIndex(absolute);
188     if (root < 0) {
189         LOG(WARNING) << "[incfs] Trying to remove non-existent bind point '" << what << '\'';
190         return;
191     }
192     if (roots[root].path == absolute) {
193         removeRoot(absolute);
194         return;
195     }
196 
197     rootByBindPoint.erase(rootIt);
198     auto& binds = roots[root].binds;
199     auto itBind = std::find(binds.begin(), binds.end(), rootIt);
200     std::swap(binds.back(), *itBind);
201     binds.pop_back();
202 }
203 
MountRegistry(std::string_view filesystem)204 MountRegistry::MountRegistry(std::string_view filesystem)
205       : mFilesystem(filesystem.empty() ? INCFS_NAME : filesystem),
206         mMountInfo(::open("/proc/self/mountinfo", O_RDONLY | O_CLOEXEC)) {
207     if (!mMountInfo.ok()) {
208         PLOG(FATAL) << "Failed to open the /proc/mounts file";
209     }
210     mMounts.loadFrom(mMountInfo, mFilesystem);
211 }
212 
213 MountRegistry::~MountRegistry() = default;
214 
rootFor(std::string_view path)215 std::string MountRegistry::rootFor(std::string_view path) {
216     auto lock = ensureUpToDate();
217     return std::string(mMounts.rootFor(path));
218 }
219 
detailsFor(std::string_view path)220 auto MountRegistry::detailsFor(std::string_view path) -> Details {
221     auto lock = ensureUpToDate();
222     auto [root, subpath] = mMounts.rootAndSubpathFor(path);
223     if (!root) {
224         return {};
225     }
226     return {root->path, root->backing, subpath};
227 }
228 
rootAndSubpathFor(std::string_view path)229 std::pair<std::string, std::string> MountRegistry::rootAndSubpathFor(std::string_view path) {
230     auto lock = ensureUpToDate();
231     auto [root, subpath] = mMounts.rootAndSubpathFor(path);
232     if (!root) {
233         return {};
234     }
235     return {std::string(root->path), std::move(subpath)};
236 }
237 
copyMounts()238 MountRegistry::Mounts MountRegistry::copyMounts() {
239     auto lock = ensureUpToDate();
240     return mMounts;
241 }
242 
reload()243 void MountRegistry::reload() {
244     (void)ensureUpToDate();
245 }
246 
ensureUpToDate()247 std::unique_lock<std::mutex> MountRegistry::ensureUpToDate() {
248     pollfd pfd = {.fd = mMountInfo.get(), .events = POLLERR | POLLPRI};
249     const auto res = TEMP_FAILURE_RETRY(poll(&pfd, 1, 0));
250     if (res == 0) {
251         // timeout - nothing to do, up to date
252         return std::unique_lock{mDataMutex};
253     }
254 
255     // reload even if poll() fails: (1) it usually doesn't and (2) it's better to be safe.
256     std::unique_lock lock(mDataMutex);
257     mMounts.loadFrom(mMountInfo, mFilesystem);
258     return lock;
259 }
260 
261 template <class Callback>
forEachLine(base::borrowed_fd fd,Callback && cb)262 static bool forEachLine(base::borrowed_fd fd, Callback&& cb) {
263     static constexpr auto kBufSize = 128 * 1024;
264     char buffer[kBufSize];
265     const char* nextLine = buffer;
266     char* nextRead = buffer;
267     int64_t pos = 0;
268     for (;;) {
269         const auto read = pread(fd.get(), nextRead, std::end(buffer) - nextRead, pos);
270         if (read == 0) {
271             break;
272         }
273         if (read < 0) {
274             if (errno == EINTR) {
275                 continue;
276             }
277             return false;
278         }
279 
280         pos += read;
281         const auto readEnd = nextRead + read;
282         auto chunk = std::string_view{nextLine, size_t(readEnd - nextLine)};
283         do {
284             auto lineEnd = chunk.find('\n');
285             if (lineEnd == chunk.npos) {
286                 break;
287             }
288             cb(chunk.substr(0, lineEnd));
289             chunk.remove_prefix(lineEnd + 1);
290         } while (!chunk.empty());
291 
292         const auto remainingSize = readEnd - chunk.end();
293         memmove(buffer, chunk.end(), remainingSize);
294         nextLine = buffer;
295         nextRead = buffer + remainingSize;
296     }
297 
298     if (nextLine < nextRead) {
299         cb({nextLine, size_t(nextRead - nextLine)});
300     }
301 
302     return true;
303 }
304 
loadFrom(base::borrowed_fd fd,std::string_view filesystem)305 bool MountRegistry::Mounts::loadFrom(base::borrowed_fd fd, std::string_view filesystem) {
306     struct MountInfo {
307         std::string backing;
308         std::set<std::string, std::less<>> roots;
309         std::vector<std::pair<std::string, std::string>> bindPoints;
310     };
311     std::unordered_map<std::string, MountInfo> mountsByGroup(16);
312     std::vector<std::string_view> items(12);
313     const auto parsed = forEachLine(fd, [&](std::string_view line) {
314         if (line.empty()) {
315             return;
316         }
317         Split(line, ' ', &items);
318         if (items.size() < 10) {
319             LOG(WARNING) << "[incfs] bad line in mountinfo: '" << line << '\'';
320             return;
321         }
322         // Note: there are optional fields in the line, starting at [6]. Anything after that should
323         // be indexed from the end.
324         const auto name = items.rbegin()[2];
325         if (!name.starts_with(filesystem)) {
326             return;
327         }
328         const auto groupId = items[2];
329         auto subdir = items[3];
330         auto backingDir = items.rbegin()[1];
331         auto mountPoint = std::string(items[4]);
332         fixProcPath(mountPoint);
333         mountPoint = path::normalize(mountPoint);
334         auto& mount = mountsByGroup[std::string(groupId)];
335         if (mount.backing.empty()) {
336             mount.backing.assign(backingDir);
337         } else if (mount.backing != backingDir) {
338             LOG(WARNING) << "[incfs] root '" << *mount.roots.begin()
339                          << "' mounted in multiple places with different backing dirs, '"
340                          << mount.backing << "' vs new '" << backingDir
341                          << "'; updating to the new one";
342             mount.backing.assign(backingDir);
343         }
344         if (subdir == "/"sv) {
345             mount.roots.emplace(mountPoint);
346             subdir = ""sv;
347         }
348         mount.bindPoints.emplace_back(std::string(subdir), std::move(mountPoint));
349     });
350 
351     if (!parsed) {
352         return false;
353     }
354 
355     rootByBindPoint.clear();
356     // preserve the allocated capacity, but clear existing data
357     roots.resize(mountsByGroup.size());
358     for (auto& root : roots) {
359         root.binds.clear();
360     }
361 
362     int index = 0;
363     for (auto& [_, mount] : mountsByGroup) {
364         if (mount.roots.empty()) {
365             // the mount has no root, and without root we have no good way of accessing the
366             // control files - so the only valid reaction here is to ignore it
367             LOG(WARNING) << "[incfs] mount '" << mount.backing << "' has no root, but "
368                          << mount.bindPoints.size() << " bind(s), ignoring";
369             continue;
370         }
371 
372         Root& root = roots[index];
373         auto& binds = root.binds;
374         binds.reserve(mount.bindPoints.size());
375         for (auto& [subdir, bind] : mount.bindPoints) {
376             auto it = rootByBindPoint
377                               .insert_or_assign(std::move(bind), Bind{std::move(subdir), index})
378                               .first;
379             binds.push_back(it);
380         }
381         root.backing = std::move(mount.backing);
382         fixProcPath(root.backing);
383 
384         // a trick here: given that as of now we either have exactly one root, or the preferred one
385         // is always at the front, let's pick that one here.
386         root.path = std::move(mount.roots.extract(mount.roots.begin()).value());
387         ++index;
388     }
389     roots.resize(index);
390 
391     LOG(INFO) << "[incfs] Loaded " << filesystem << " mount info: " << roots.size()
392               << " instances, " << rootByBindPoint.size() << " mount points";
393     if (base::VERBOSE >= base::GetMinimumLogSeverity()) {
394         for (auto&& [root, backing, binds] : roots) {
395             LOG(INFO) << "[incfs]  '" << root << '\'';
396             LOG(INFO) << "[incfs]    backing: '" << backing << '\'';
397             for (auto&& bind : binds) {
398                 LOG(INFO) << "[incfs]      bind : '" << bind->second.subdir << "'->'" << bind->first
399                           << '\'';
400             }
401         }
402     }
403     return true;
404 }
405 
load(base::borrowed_fd mountInfo,std::string_view filesystem)406 auto MountRegistry::Mounts::load(base::borrowed_fd mountInfo, std::string_view filesystem)
407         -> Mounts {
408     Mounts res;
409     res.loadFrom(mountInfo, filesystem);
410     return res;
411 }
412 
413 } // namespace android::incfs
414