Skip to content

Commit

Permalink
minor #18085 [Cache] Hash using B64+MD5 in FilesystemAdapter (nicolas…
Browse files Browse the repository at this point in the history
…-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
  • Loading branch information
fabpot committed Mar 10, 2016
2 parents 681a349 + e96bb10 commit 117d83b
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/Symfony/Component/Cache/Adapter/FilesystemAdapter.php
Expand Up @@ -40,7 +40,7 @@ public function __construct($directory, $defaultLifetime = 0, $namespace = '')
throw new InvalidArgumentException(sprintf('Cache directory is not writable (%s)', $directory));
}
// On Windows the whole path is limited to 258 chars
if ('\\' === DIRECTORY_SEPARATOR && strlen($dir) > 190) {
if ('\\' === DIRECTORY_SEPARATOR && strlen($dir) > 234) {
throw new InvalidArgumentException(sprintf('Cache directory too long (%s)', $directory));
}

Expand Down Expand Up @@ -68,10 +68,13 @@ protected function doFetch(array $ids)
@unlink($file);
}
} else {
$i = rawurldecode(rtrim(fgets($h)));
$value = stream_get_contents($h);
flock($h, LOCK_UN);
fclose($h);
$values[$id] = unserialize($value);
if ($i === $id) {
$values[$id] = unserialize($value);
}
}
}

Expand Down Expand Up @@ -131,7 +134,7 @@ protected function doSave(array $values, $lifetime)
if (!file_exists($dir)) {
@mkdir($dir, 0777, true);
}
$value = $expiresAt."\n".serialize($value);
$value = $expiresAt."\n".rawurlencode($id)."\n".serialize($value);
if (false !== @file_put_contents($file, $value, LOCK_EX)) {
@touch($file, $expiresAt);
} else {
Expand All @@ -144,8 +147,8 @@ protected function doSave(array $values, $lifetime)

private function getFile($id)
{
$hash = hash('sha256', $id);
$hash = str_replace('/', '-', base64_encode(md5($id, true)));

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

0 comments on commit 117d83b

Please sign in to comment.