检查 std::filesystem::path 是否在目录中

Nic*_*iou 5 c++ c++17 std-filesystem

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

例如:

    std::filesystem::path root = "/foo/bar";
    std::filesystem::path userFile = "ham/spam";
    std::filesystem::path finalPath = root / userFile;
Run Code Online (Sandbox Code Playgroud)

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

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

Nic*_*las 8

首先,您需要规范化最终路径。这将删除路径中的所有...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;
}
Run Code Online (Sandbox Code Playgroud)

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