Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/Caching/Storages/FileStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -309,13 +309,14 @@ protected function readMetaAndLock(string $file, int $lock): ?array

$size = (int) stream_get_contents($handle, self::MetaHeaderLen);
if ($size) {
$meta = stream_get_contents($handle, $size, self::MetaHeaderLen);
if ($meta !== false) {
$meta = unserialize($meta);
assert(is_array($meta));
$meta[self::File] = $file;
$meta[self::Handle] = $handle;
return $meta;
$raw = stream_get_contents($handle, $size, self::MetaHeaderLen);
if ($raw !== false) {
$meta = @unserialize($raw); // @ - file may not be a valid cache file
if (is_array($meta)) {
$meta[self::File] = $file;
$meta[self::Handle] = $handle;
return $meta;
}
}
}

Expand All @@ -337,7 +338,7 @@ protected function readData(array $meta): mixed
return match (true) {
$data === false => null,
empty($meta[self::MetaSerialized]) => $data,
default => unserialize($data),
default => @unserialize($data), // @ - data may be corrupted by a truncated write
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat corrupted serialized payload as cache miss

When MetaSerialized is set, readData() now returns @unserialize($data) directly, so malformed payloads resolve to false instead of a miss. In Cache::load(), only null is treated as missing ($data === null), so a corrupted file can become a persistent cache hit with value false, skipping regeneration and returning incorrect data to callers. Please map unserialize failure to null (while preserving legitimate serialized false, e.g. b:0;).

Useful? React with 👍 / 👎.

};
}

Expand Down
118 changes: 118 additions & 0 deletions tests/Storages/FileStorage.corrupted.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php declare(strict_types=1);

/**
* Test: Nette\Caching\Storages\FileStorage handles corrupted cache files gracefully.
*
* Verifies that reading a corrupted cache file returns null instead of
* throwing unserialize errors. Covers both corrupted metadata and
* corrupted data payloads.
*/

use Nette\Caching\Cache;
use Nette\Caching\Storages\FileStorage;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


$dir = getTempDir();
$storage = new FileStorage($dir);
$cache = new Cache($storage);


// --- Corrupted metadata ---

$cache->save('meta-test', 'hello');
Assert::same('hello', $cache->load('meta-test'));

// Find the cache file and corrupt its metadata
$files = glob($dir . '/_*');
Assert::truthy($files);

foreach ($files as $file) {
if (is_file($file)) {
// Overwrite with a valid-looking size header but garbage meta.
// "000010" = meta size of 10, followed by non-serialized data.
file_put_contents($file, '000010not-serial');
}
}

// Reading corrupted meta should return null, not crash
Assert::null($cache->load('meta-test'));


// --- Corrupted serialized data ---

// Use a fresh storage to avoid interference
$dir2 = getTempDir() . '/data-test';
@mkdir($dir2, 0777, true);
$storage2 = new FileStorage($dir2);
$cache2 = new Cache($storage2);

$cache2->save('data-test', ['complex' => 'array', 'with' => [1, 2, 3]]);
Assert::type('array', $cache2->load('data-test'));

// Find the cache file
$files2 = glob($dir2 . '/_*');
Assert::truthy($files2);

foreach ($files2 as $file) {
if (is_file($file)) {
$content = file_get_contents($file);
$size = (int) substr($content, 0, 6);
$headerAndMeta = substr($content, 0, 6 + $size);
// Keep valid header+meta but replace data with garbage
file_put_contents($file, $headerAndMeta . 'CORRUPTED-DATA-NOT-SERIALIZABLE');
}
}

// Reading corrupted data should not crash.
// The result may be false (failed unserialize) but must not throw.
Assert::noError(function () use ($cache2) {
$cache2->load('data-test');
});


// --- Truncated file ---

$dir3 = getTempDir() . '/truncated-test';
@mkdir($dir3, 0777, true);
$storage3 = new FileStorage($dir3);
$cache3 = new Cache($storage3);

$cache3->save('trunc-test', str_repeat('x', 10000));
Assert::same(str_repeat('x', 10000), $cache3->load('trunc-test'));

// Truncate the file mid-data
$files3 = glob($dir3 . '/_*');
foreach ($files3 as $file) {
if (is_file($file)) {
$handle = fopen($file, 'r+b');
ftruncate($handle, 50); // keep header + partial meta
fclose($handle);
}
}

// Should return null, not crash
Assert::null($cache3->load('trunc-test'));


// --- File with all zero bytes ---

$dir4 = getTempDir() . '/zeros-test';
@mkdir($dir4, 0777, true);
$storage4 = new FileStorage($dir4);
$cache4 = new Cache($storage4);

$cache4->save('zero-test', 'data');

$files4 = glob($dir4 . '/_*');
foreach ($files4 as $file) {
if (is_file($file)) {
file_put_contents($file, str_repeat("\x00", 100));
}
}

// All-zero header = size 0, should return null
Assert::null($cache4->load('zero-test'));
88 changes: 88 additions & 0 deletions tests/Storages/FileStorage.gc-foreign-files.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php declare(strict_types=1);

/**
* Test: Nette\Caching\Storages\FileStorage clean() skips non-cache files.
*
* Regression test for GH#45: FileStorage GC crashes with "unserialize(): Error at offset"
* when non-cache files (e.g. Latte lock files) matching the _* pattern exist
* in the cache directory.
*/

use Nette\Caching\Cache;
use Nette\Caching\Storages\FileStorage;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


$dir = getTempDir();
$storage = new FileStorage($dir);
$cache = new Cache($storage);


// Write valid cache entries
$cache->save('key1', 'value1');
$cache->save('key2', 'value2');

Assert::same('value1', $cache->load('key1'));
Assert::same('value2', $cache->load('key2'));


// Create foreign files that match the _* pattern used by GC.
// These simulate Latte lock files and other non-cache files that may
// coexist in the same temp directory tree.

// Case 1: Content starting with digits — triggers (int) cast to non-zero size
// in readMetaAndLock(), then garbage gets passed to unserialize().
// This is the exact scenario from GH#45 diagnosis by @martinbohmcz:
// PHP 8 interprets "0942e7" as float 942e7, (int) cast = 9420000.
file_put_contents($dir . '/_includes-template.php.lock', '0942e7deadbeef');

// Case 2: Binary content
file_put_contents($dir . '/_session.lock', "\xff\xfe\x00\x01\x80\x90binary");

// Case 3: Empty file
file_put_contents($dir . '/_empty.lock', '');

// Case 4: File with zero-like header (6 bytes of zeros = size 0, skip path)
file_put_contents($dir . '/_zero-header.tmp', '000000some-data');

// Case 5: File with valid-looking size but garbage meta
file_put_contents($dir . '/_fake-meta.dat', '000010not-a-serialized-array');

// Case 6: File in a subdirectory matching _* pattern
@mkdir($dir . '/_subdir', 0777, true);
file_put_contents($dir . '/_subdir/_nested.lock', 'nested-lock-data');


// GC (collector mode) must not crash on foreign files
Assert::noError(function () use ($storage) {
$storage->clean([]);
});


// Valid cache entries must still be readable
Assert::same('value1', $cache->load('key1'));
Assert::same('value2', $cache->load('key2'));


// Foreign files must be untouched (GC should skip, not delete them)
Assert::true(file_exists($dir . '/_includes-template.php.lock'));
Assert::true(file_exists($dir . '/_session.lock'));
Assert::true(file_exists($dir . '/_empty.lock'));
Assert::true(file_exists($dir . '/_zero-header.tmp'));
Assert::true(file_exists($dir . '/_fake-meta.dat'));
Assert::true(file_exists($dir . '/_subdir/_nested.lock'));


// Cache::All mode deletes all _* files including foreign ones — expected behavior
$storage->clean([Cache::All => true]);

Assert::null($cache->load('key1'));
Assert::null($cache->load('key2'));
Assert::false(file_exists($dir . '/_includes-template.php.lock'));
Assert::false(file_exists($dir . '/_session.lock'));
Assert::false(file_exists($dir . '/_empty.lock'));
Assert::false(file_exists($dir . '/_zero-header.tmp'));
Assert::false(file_exists($dir . '/_fake-meta.dat'));
8 changes: 7 additions & 1 deletion tests/Storages/FileStorage.stress.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,20 @@ function checkStr($s)
define('COUNT_FILES', 3);


$storage = new FileStorage(getTempDir());
$dir = getTempDir();
$storage = new FileStorage($dir);


// clear playground
for ($i = 0; $i <= COUNT_FILES; $i++) {
$storage->write((string) $i, randomStr(), []);
}

// GH#45: place foreign files in the cache directory to verify they don't
// interfere with normal cache operations or cause unserialize errors during GC
file_put_contents($dir . '/_foreign.lock', '0942e7deadbeef');
file_put_contents($dir . '/_session.tmp', "\xff\xfe\x00\x01binary");

// test loop
$hits = ['ok' => 0, 'notfound' => 0, 'error' => 0, 'cantwrite' => 0, 'cantdelete' => 0];
for ($counter = 0; $counter < 1000; $counter++) {
Expand Down