首页 > 解决方案 > 检查 std::filesystem::path 是否在目录中

问题描述

我有一个由std::filesystem::path. 我想向该路径添加一些用户提供的文件名,并确保生成的路径不在根目录之外。

例如:

    std::filesystem::path root = "/foo/bar";
    std::filesystem::path userFile = "ham/spam";
    std::filesystem::path finalPath = root / userFile;

最后的路径没问题,在里面/foo/bar。但是如果我给../ham/spam变量userFile,这将导致定义之外的文件rootPath

如何检查生成的文件是否保持在其允许的边界内?

标签: c++c++17std-filesystem

解决方案


首先,您需要标准化最终路径。这将删除路径中的所有...s。然后,您需要检查它是否在其目录迭代器范围内(相对于root. 并且有一个标准库算法

总的来说,代码如下所示:

std::optional<fs::path> MakeAbsolute(const fs::path &root, const fs::path &userPath)
{
    auto finalPath = (root / userPath).lexically_normal();

    auto[rootEnd, nothing] = std::mismatch(root.begin(), root.end(), finalPath.begin());

    if(rootEnd != root.end())
        return std::nullopt;

    return finalPath;
}

请注意,这仅在理论上有效;用户可能在根目录中使用了符号链接恶作剧来突破您的根目录。您需要使用canonical而不是lexically_normal确保不会发生这种情况。但是,canonical 要求该路径存在,因此如果这是需要创建的文件/目录的路径,它将不起作用。


推荐阅读