在我的应用程序中,我试图检查路径是否在特定目录中。/x/y/z例如,我希望我的应用程序的某些部分不能访问路径中的文件。我不能使用传统的文件权限,因为应用程序的其他部分应该能够访问这些文件。
一些 Internet 资源建议使用realpathto 首先规范化路径,即解析所有符号链接和..(例如1、2 ) 的实例。但是,似乎不可能在open没有竞争条件 (TOCTOU) 之后执行路径解析。
char *resolved = realpath("/my/potentially/dangerous/path.txt", NULL);
// someone changes any part of the path to a symlink to something else <--- race condition
if (check_path(resolved)) {
// <--- race condition
int fd = open(resolved, O_RDONLY);
}
我是否忽略了某些东西,或者 POSIX(和 Linux)没有提供任何方法来做这样的事情而没有竞争条件?