顺序使用stat和mkdir的竞赛条件 [英] Race condition with stat and mkdir in sequence

查看:256
本文介绍了顺序使用stat和mkdir的竞赛条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Coverage抱怨. toctou:调用检查函数后使用DIR的函数mkdir.这可能会导致检查时间,使用时间竞争状况

Coverity complains of . toctou: Calling function mkdir that uses DIR after a check function. This can cause a time-of-check, time-of-use race condition

if (stat(DIR, &st) != 0)
{
    if (mkdir(DIR, 0755) < 0)
    {
        return ERROR;
    }
}

将代码更改为是否足够好,我仅将stat用于文件是否存在检查

Is it good enough to change the code to ,I was using stat only for file exist check

if (mkdir(NDUID_DIR, 0755) < 0)
{
    if(errno != EEXIST)
    {
        return ERROR;
    }
}

是否有更好的方法来修复代码?

Is there a better way to fix the code?

推荐答案

您的两个摘录似乎都不正确和/或不完整.

Both of your snippets appear to be incorrect and/or incomplete.

在OpenBSD上, sys_mkdir return ,然后将errno设置为 EEXIST 存在.但是,这不能保证目标文件是目录-现有的常规文件仍会导致 mkdir(2) 返回完全相同的EEXIST.

On OpenBSD, sys_mkdir would return -1, and set errno to EEXIST when the target file is present. However, that doesn't guarantee that the target file is a directory -- an existing regular file would still result in mkdir(2) returning the exact same EEXIST.

要获得广泛接受的方法的指导,请查看 mkdir(1) -p选项如何在BSD上实现( bin/mkdir/mkdir.c#mkpath在OpenBSD中 NetBSD ),所有这些都位于 S_ISDIR 宏,以确保现有文件是目录,而不仅仅是其他任何类型的文件.

For guidance of the widely accepted approach, take a look at how mkdir(1) -p option is implemented across the BSDs (bin/mkdir/mkdir.c#mkpath in OpenBSD and NetBSD), all of which, on mkdir(2)'s error, appear to immediately call stat(2) to subsequently run the S_ISDIR macro to ensure that the existing file is a directory, and not just any other type of a file.

这篇关于顺序使用stat和mkdir的竞赛条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆