From 19 Deadly Sins of Software Security;
The following code is the poster child for the file-access race condition defect. In between the call to access(2) and open(2), the operating system could switch away from your running process and give another process a time slice. In the interveneing time, the file /tmp/splat could be deleted, and then the application crashes.
…
const char *filename="/tmp/splat";
if (access(filename, R_OK)==0) {
int fd=open(filename, O_RDONLY);
handle_file_contents(fd);
close(fd);
}
and
Again, this code is accessing the file using a filename. The code determines if the file is readable by the effective user of the Perl script and if it is, reads it. This sinful code is similar to the C/C++ code: between the file check and the read, the file may have disappeared.
#!/user/bin/perl
my $file="$ENV{HOME}/.config";
read_config($file) if -r $file;
and finally,
Use a file handle, not the filename, to verify the file exists and then open it.
$!/ur/bin/perl
my $file="$ENV{HOME}/.config";
if (open(FILE, "< $file")) {
read_config(*FILE) if is_accessible(*FILE);
}
The point is that if you use a filename for each call to a file-related function, the file could be changed, deleted, etc. between calls, particularly on a remote server. It’s better to use a file handle or file descriptor. Unfortunately, the PHP manual seems to indicate that most file functions only work on a string representing the filename and don’t have overloads that can take a handle instead,
filesize
in particular:
$fn = "somefile.txt"
$fh = fopen($fn);
if ($fh !== FALSE) {
$data = fread($fh, filesize($fn));
}
That’s not good; between the call to fopen
and filesize
, the file could have been altered. Worse, the file could have been altered between the call to filesize
and the meat of fread
!
Does 开发者_运维知识库anyone know of a way to use PHP file functions, especially filesize
with handles instead of filenames?
A lot of the data you're looking for can be accessed with fstat().
The following can be derived from an fstat() call. See stat() for more about the information fstat() returns. From the PHP manual:
Array
(
[dev] => 771
[ino] => 488704
[mode] => 33188
[nlink] => 1
[uid] => 0
[gid] => 0
[rdev] => 0
[size] => 1114
[atime] => 1061067181
[mtime] => 1056136526
[ctime] => 1056136526
[blksize] => 4096
[blocks] => 8
)
精彩评论