in reply to Avoiding race conditions

You can use File::Temp to return both the filehandle and filename. When this is done, there is no race condition. When File::Temp opens a file, it does so with O_CREAT|O_EXCL set in the flags and a mode of 600, which ensures that the file will be created and only you will be able to read/write to it. A race condition would be to return only the filename and then open() it because the file could have been generated by someone else in between the time of File::Temp checking to see if it exists and you opening it. So, if you use the File::Temp functions in list format ($filehandle, $filename) = tempfile(...) you should be safe (assuming your temp directory isn't on NFS).

Replies are listed 'Best First'.
Re: Re: Avoiding race conditions
by swiftone (Curate) on Apr 24, 2001 at 22:36 UTC
    That's what I thought, but in the File::Temp documentation:
    WARNING
    For maximum security, endeavour always to avoid ever looking at, touching, or even imputing the existence of the filename. You do not know that that filename is connected to the same file as the handle you have, and attempts to check this can only trigger more race conditions. It's far more secure to use the filehandle alone and dispense with the filename altogether.
      Yes, that is correct, if the file was made in a directory which is world writeable (like most temp directories) and does not have the sticky bit set (unlike most temp directories) then someone can come along and delete the file and make a new one in its place with the same name. While we're on the subject, one practice, which I consider good form in general (but which may not work for you, since you want the file avaiable via www), is to create a ~/tmp with 700 permissions and create all temp files in there, this prevents all of the /tmp race condition security bugs that have cropped up in the past and will surely crop up in the future (it still does not prevent a race condition, two copies of your program could both generate the same filename before either of them opened it, but it prevents someone from symlinking the file to /etc/passwd or creating and opening it first). Anyways, back to your problem: since you are publishing the files via www, I assume that they are being put in a directory which is writeable only by you, if this is the case then you do not need to worry about anyone deleting the file, people will probably be able to read the file but I don't think that is a big problem since you're making it available via the www and someone could just fetch it via the www rather than the local filesystem if they could predict the filename, though a brute force guess would be much slower via www.