Using temporary files safely
You have a lot of suggestions already, but another option that I don't think has been mentioned is using named pipes. It will depend on the library in question as to whether it works or not, but it might be worth a try. You can create a named pipe in your application using the CreateNamedPipe
function, and pass the name of the pipe to the library to operate on (the filename you would pass would be \\.\pipe\PipeName). Whether the library accepts a filename like that or not is something you would have to try, but if it works the advantage is your file never has to actually be written to disk.
This can be achieved using the CreateFile
and GetTempFileName
functions (if you don't know if you can write to the current working directory, you may also want to use , GetTempPath
).
- Determine a directory to store your temporary file in; the current directory (".") or the result of
GetTempPath
would be good candidates. - Use
GetTempFileName
to create a temporary file name. - Finally, call
CreateFile
to create the temporary file.
For the last step, there are a few things to consider:
- The
dwFlagsAndAttributes
parameter ofCreateFile
should probably includeFILE_ATTRIBUTE_TEMPORARY
. - The
dwFlagsAndAttributes
parameter should probably also includeFILE_FLAG_DELETE_ON_CLOSE
to make sure that the file gets deleted no matter what (this probably also works if your process crashes, in which case the system closes all handles for you). - The
dwShareMode
parameter ofCreateFile
should probably beFILE_SHARE_READ
so that other attempts to open the file will succeed, but only for reading. This means that your library code will be able to read the file, but nobody will be able to write to it.
This article should give you some good guidelines on the issue.
The gist of the matter is this:
- The POSIX mkstemp() function is the secure and preferred solution where available. Unfortunately, it is not available in Windows, so you would need to find a wrapper that properly implements this functionality using Windows API calls.
- On Windows, the tmpfile_s() function is the only one that actually opens the temporary file atomically (instead of simply generating a filename), protecting you from a race condition. Unfortunately, this function does not allow you to specify which directory the file will be created in, which is a potential security issue.