« Jellyfish | Main | Tape Heads »

File exists? perldoc -f -X

A common question on #perl runs: “how do I check if a file exists?” There are two answers. First: perldoc -f -X details all the file test flags in Perl. Second: checking whether a file exists is quite often a needless race condition.

# Example code. Totally flawed. Do not use. if ( -e $file ) { append_data($file); } else { create_new($file); }

In the above example, the developer wished to append data if the file already existed, otherwise create the file. The race condition comes into effect just after the -e $file test, and lasts until the open call—somewhere under the hypothetical append_data call—opens the file. That is, during the race condition, another process could create the file, or a dangling symbolic link, or, if the file had existed, delete it. At best the code would then throw an exception, at worst, create a security problem. One possible security problem is arbitrary file overwrite, where a malicious attacker would point the $file (or all the possible filenames) towards a critical system file, hoping that the code above heedlessly overwrites or corrupts the data:

$ ln -s /etc/passwd the_file

The developer incorrectly assumed that the system state would remain constant between the ill-advised file test and the subsequent operation on that file. This is at best woeful ignorance, at worst professional negligence. The code should simply open the file in append mode, as this will create the file, or append to it, without the needless file test:

open(my $fh, '>>', $file) or die "error: cannot append: file=$file, errstr=$!\n";

In most cases, instead of the needless initial test, the subsequent operation following that test—opening the file, or creating a directory—should be performed instead, and any errors—the file already existing, or a permissions problem—handled as necessary afterwards.

Finally, if the code involves /tmp or a similar shared directory, peruse Perl and Temporary Files for methods to properly handle files in shared locations. Not understanding how to properly manage files under /tmp often results in egregious security holes.

Technorati Tags: