c++file-handlingcoveritytocttou

TOCTTOU - Using access before handling file


I have this function that copies files to a mirror directory and then deletes the old one. It works well however, in Coverity, my code shows up as a TOCTTOU warning.

void function(){
    const char *original_key = "path/to/file/filename";
    const char *mirror_key = "path/to/another/file/filename";

    if((access(original_key, F_OK) == 0) && (access(mirror_key, F_OK) == 0)){
        copy_file("/bin/cp %s %s", original_key, mirror_key); /*copy function in another cpp file*/
        unlink(original_key);
    }
}

/* in another cpp file */
int copy_file(const char*command, ...){
    int rc = -1;
    va_list args;
    char *buffer = NULL;
    va_start(args, command);
    vasprintf(&buffer, command, args);
    va_end(args);
    if (buffer)
    {
        char *wrd;
        char *ptr = buffer;
        std::vector<const char *> list;
        while ((wrd = strsep(&ptr, " ")) != NULL)
        {
            if (strlen(wrd))
            {
                list.push_back(wrd);
            }
        }
        if (list.size() > 0)
        {
            char *argv[list.size() + 1];
            for (size_t idx = 0; idx < list.size(); idx++)
            {
                argv[idx] = (char *)list[idx];
            }
            argv[list.size()] = NULL;
            rc = system_spawn_args(argv);
        }
        free(buffer);
    }
    return(rc);
}

Is there a way to prevent TOCTTOU in this situation?

note: move did not work - Cross Device Error.

Thanks


Solution

  • Since my main function was basically to move one file to another. I just used rename() this did the job and also did not warn me as a TOCTTOU in Coverity