C++检查路径是否在给定目录之外



检查给定路径a是否在另一路径B之外的最简单方法是什么?即:判断foo/../../bar/是否在foo/之外。

这样的东西应该可以工作。还要注意,这两条路径都应该存在。

#include <filesystem>
#include <algorithm>
#include <iterator>
#include <cassert>
bool isSafePath(const std::filesystem::path &root, const std::filesystem::path &child) {
auto const normRoot = std::filesystem::canonical(root);
auto const normChild = std::filesystem::canonical(child);

auto itr = std::search(normChild.begin(), normChild.end(), 
normRoot.begin(), normRoot.end());

return itr == normChild.begin();
}
int main(int argc, char **argv)
{
assert(isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/nvevg/index.html"));
assert(isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/nvevg"));
assert(isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../apps/CMakeLists.txt"));

assert(not isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../../../../../etc/shadow"));
assert(not isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../CMakeLists.txt"));
assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/"));
assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/"));
assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../../../../../../../etc/fstab"));

return 0;
}

有一个函数返回传递的两者之间的相对路径,称为relative。您可以检查结果路径是否以..开始

bool isSubPath(const std::string& base, const std::string& destination)
{
std::string relative = std::filesystem::relative(destination, base);
// Size check for a "." result.
// If the path starts with "..", it's not a subdirectory.
return relative.size() == 1 || relative[0] != '.' && relative[1] != '.';
}

相关内容

  • 没有找到相关文章

最新更新