Skip to content

Commit 7dec5ff

Browse files
author
arcfieldOSS
committed
changes to locking to attempt to prevent races on read that might result in incomplete reads.
1 parent cafc8b4 commit 7dec5ff

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

phpfastcache/3.0.0/abstract.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,10 +280,14 @@ protected function readfile($file) {
280280
throw new Exception("Can't Read File",96);
281281

282282
}
283+
if (flock($file_handle, LOCK_SH | LOCK_NB)) {
283284
while (!feof($file_handle)) {
284285
$line = fgets($file_handle);
285286
$string .= $line;
286287
}
288+
} else {
289+
throw new Exception("Can't Read File",96);
290+
}
287291
fclose($file_handle);
288292

289293
return $string;

phpfastcache/3.0.0/drivers/files.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ private function getFilePath($keyword, $skip = false) {
7070

7171
function driver_set($keyword, $value = "", $time = 300, $option = array() ) {
7272
$file_path = $this->getFilePath($keyword);
73+
$tmp_path = $file_path . ".tmp";
7374
// echo "<br>DEBUG SET: ".$keyword." - ".$value." - ".$time."<br>";
7475
$data = $this->encode($value);
7576

@@ -86,11 +87,23 @@ function driver_set($keyword, $value = "", $time = 300, $option = array() ) {
8687
}
8788
}
8889

89-
if($toWrite == true) {
90+
/*
91+
* write to intent file to prevent race during read; race during write is ok
92+
* because first-to-lock wins and the file will exist before the writer attempts
93+
* to write.
94+
*/
95+
if($toWrite == true && !@file_exists($tmp_path && !@file_exists($file_path))) {
9096
try {
91-
$f = @fopen($file_path, "w+");
97+
$f = @fopen($tmp_path, "c");
98+
if (flock($f,LOCK_EX| LOCK_NB)) {
9299
fwrite($f, $data);
100+
fflush($f);
101+
flock($f,LOCK_UN);
102+
} else {
103+
//arguably the file is being written to so the job is done
104+
}
93105
fclose($f);
106+
@rename($tmp_path,$file_path);
94107
} catch (Exception $e) {
95108
// miss cache
96109
return false;

0 commit comments

Comments
 (0)