Skip to content

Commit 117d83b

Browse files
committed
minor #18085 [Cache] Hash using B64+MD5 in FilesystemAdapter (nicolas-grekas)
This PR was merged into the 3.1-dev branch. Discussion ---------- [Cache] Hash using B64+MD5 in FilesystemAdapter | Q | A | ------------- | --- | Branch | master | Bug fix? | no | New feature? | no | BC breaks? | no | Deprecations? | no | Tests pass? | no | Fixed tickets | - | License | MIT | Doc PR | - Using MD5+B64 is good enough to avoid any hash collision, even on case-insensitive filesystems. On Windows where the total path length is limited, this saves 44 chars worth. Even if collisions are extremely unlikely, they are detected by adding then comparing the raw key to saved payloads. This also has the added benefit of easing debugging/grepping the cached items on the filesystem. Commits ------- e96bb10 [Cache] Hash using B64+MD5 in FilesystemAdapter
2 parents 681a349 + e96bb10 commit 117d83b

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/Symfony/Component/Cache/Adapter/FilesystemAdapter.php

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public function __construct($directory, $defaultLifetime = 0, $namespace = '')
4040
throw new InvalidArgumentException(sprintf('Cache directory is not writable (%s)', $directory));
4141
}
4242
// On Windows the whole path is limited to 258 chars
43-
if ('\\' === DIRECTORY_SEPARATOR && strlen($dir) > 190) {
43+
if ('\\' === DIRECTORY_SEPARATOR && strlen($dir) > 234) {
4444
throw new InvalidArgumentException(sprintf('Cache directory too long (%s)', $directory));
4545
}
4646

@@ -68,10 +68,13 @@ protected function doFetch(array $ids)
6868
@unlink($file);
6969
}
7070
} else {
71+
$i = rawurldecode(rtrim(fgets($h)));
7172
$value = stream_get_contents($h);
7273
flock($h, LOCK_UN);
7374
fclose($h);
74-
$values[$id] = unserialize($value);
75+
if ($i === $id) {
76+
$values[$id] = unserialize($value);
77+
}
7578
}
7679
}
7780

@@ -131,7 +134,7 @@ protected function doSave(array $values, $lifetime)
131134
if (!file_exists($dir)) {
132135
@mkdir($dir, 0777, true);
133136
}
134-
$value = $expiresAt."\n".serialize($value);
137+
$value = $expiresAt."\n".rawurlencode($id)."\n".serialize($value);
135138
if (false !== @file_put_contents($file, $value, LOCK_EX)) {
136139
@touch($file, $expiresAt);
137140
} else {
@@ -144,8 +147,8 @@ protected function doSave(array $values, $lifetime)
144147

145148
private function getFile($id)
146149
{
147-
$hash = hash('sha256', $id);
150+
$hash = str_replace('/', '-', base64_encode(md5($id, true)));
148151

149-
return $this->directory.$hash[0].DIRECTORY_SEPARATOR.$hash[1].DIRECTORY_SEPARATOR.$hash;
152+
return $this->directory.$hash[0].DIRECTORY_SEPARATOR.$hash[1].DIRECTORY_SEPARATOR.substr($hash, 2, -2);
150153
}
151154
}

0 commit comments

Comments
 (0)