Chris@0: Chris@0: * Chris@0: * This code is partially based on the Rack-Cache library by Ryan Tomayko, Chris@0: * which is released under the MIT license. Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\HttpKernel\HttpCache; Chris@0: Chris@0: use Symfony\Component\HttpFoundation\Request; Chris@0: use Symfony\Component\HttpFoundation\Response; Chris@0: Chris@0: /** Chris@0: * Store implements all the logic for storing cache metadata (Request and Response headers). Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: */ Chris@0: class Store implements StoreInterface Chris@0: { Chris@0: protected $root; Chris@0: private $keyCache; Chris@0: private $locks; Chris@0: Chris@0: /** Chris@0: * @param string $root The path to the cache directory Chris@0: * Chris@0: * @throws \RuntimeException Chris@0: */ Chris@0: public function __construct($root) Chris@0: { Chris@0: $this->root = $root; Chris@0: if (!file_exists($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) { Chris@0: throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root)); Chris@0: } Chris@0: $this->keyCache = new \SplObjectStorage(); Chris@17: $this->locks = []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Cleanups storage. Chris@0: */ Chris@0: public function cleanup() Chris@0: { Chris@0: // unlock everything Chris@0: foreach ($this->locks as $lock) { Chris@0: flock($lock, LOCK_UN); Chris@0: fclose($lock); Chris@0: } Chris@0: Chris@17: $this->locks = []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Tries to lock the cache for a given Request, without blocking. Chris@0: * Chris@0: * @return bool|string true if the lock is acquired, the path to the current lock otherwise Chris@0: */ Chris@0: public function lock(Request $request) Chris@0: { Chris@0: $key = $this->getCacheKey($request); Chris@0: Chris@0: if (!isset($this->locks[$key])) { Chris@0: $path = $this->getPath($key); Chris@17: if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) { Chris@0: return $path; Chris@0: } Chris@0: $h = fopen($path, 'cb'); Chris@0: if (!flock($h, LOCK_EX | LOCK_NB)) { Chris@0: fclose($h); Chris@0: Chris@0: return $path; Chris@0: } Chris@0: Chris@0: $this->locks[$key] = $h; Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Releases the lock for the given Request. Chris@0: * Chris@0: * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise Chris@0: */ Chris@0: public function unlock(Request $request) Chris@0: { Chris@0: $key = $this->getCacheKey($request); Chris@0: Chris@0: if (isset($this->locks[$key])) { Chris@0: flock($this->locks[$key], LOCK_UN); Chris@0: fclose($this->locks[$key]); Chris@0: unset($this->locks[$key]); Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@0: public function isLocked(Request $request) Chris@0: { Chris@0: $key = $this->getCacheKey($request); Chris@0: Chris@0: if (isset($this->locks[$key])) { Chris@0: return true; // shortcut if lock held by this process Chris@0: } Chris@0: Chris@0: if (!file_exists($path = $this->getPath($key))) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $h = fopen($path, 'rb'); Chris@0: flock($h, LOCK_EX | LOCK_NB, $wouldBlock); Chris@0: flock($h, LOCK_UN); // release the lock we just acquired Chris@0: fclose($h); Chris@0: Chris@0: return (bool) $wouldBlock; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Locates a cached Response for the Request provided. Chris@0: * Chris@0: * @return Response|null A Response instance, or null if no cache entry was found Chris@0: */ Chris@0: public function lookup(Request $request) Chris@0: { Chris@0: $key = $this->getCacheKey($request); Chris@0: Chris@0: if (!$entries = $this->getMetadata($key)) { Chris@0: return; Chris@0: } Chris@0: Chris@0: // find a cached entry that matches the request. Chris@0: $match = null; Chris@0: foreach ($entries as $entry) { Chris@0: if ($this->requestsMatch(isset($entry[1]['vary'][0]) ? implode(', ', $entry[1]['vary']) : '', $request->headers->all(), $entry[0])) { Chris@0: $match = $entry; Chris@0: Chris@0: break; Chris@0: } Chris@0: } Chris@0: Chris@0: if (null === $match) { Chris@0: return; Chris@0: } Chris@0: Chris@14: $headers = $match[1]; Chris@0: if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) { Chris@0: return $this->restoreResponse($headers, $body); Chris@0: } Chris@0: Chris@0: // TODO the metaStore referenced an entity that doesn't exist in Chris@0: // the entityStore. We definitely want to return nil but we should Chris@0: // also purge the entry from the meta-store when this is detected. Chris@0: } Chris@0: Chris@0: /** Chris@0: * Writes a cache entry to the store for the given Request and Response. Chris@0: * Chris@0: * Existing entries are read and any that match the response are removed. This Chris@0: * method calls write with the new list of cache entries. Chris@0: * Chris@0: * @return string The key under which the response is stored Chris@0: * Chris@0: * @throws \RuntimeException Chris@0: */ Chris@0: public function write(Request $request, Response $response) Chris@0: { Chris@0: $key = $this->getCacheKey($request); Chris@0: $storedEnv = $this->persistRequest($request); Chris@0: Chris@0: // write the response body to the entity store if this is the original response Chris@0: if (!$response->headers->has('X-Content-Digest')) { Chris@0: $digest = $this->generateContentDigest($response); Chris@0: Chris@0: if (false === $this->save($digest, $response->getContent())) { Chris@0: throw new \RuntimeException('Unable to store the entity.'); Chris@0: } Chris@0: Chris@0: $response->headers->set('X-Content-Digest', $digest); Chris@0: Chris@0: if (!$response->headers->has('Transfer-Encoding')) { Chris@17: $response->headers->set('Content-Length', \strlen($response->getContent())); Chris@0: } Chris@0: } Chris@0: Chris@0: // read existing cache entries, remove non-varying, and add this one to the list Chris@17: $entries = []; Chris@0: $vary = $response->headers->get('vary'); Chris@0: foreach ($this->getMetadata($key) as $entry) { Chris@0: if (!isset($entry[1]['vary'][0])) { Chris@17: $entry[1]['vary'] = ['']; Chris@0: } Chris@0: Chris@14: if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary, $entry[0], $storedEnv)) { Chris@0: $entries[] = $entry; Chris@0: } Chris@0: } Chris@0: Chris@0: $headers = $this->persistResponse($response); Chris@0: unset($headers['age']); Chris@0: Chris@17: array_unshift($entries, [$storedEnv, $headers]); Chris@0: Chris@0: if (false === $this->save($key, serialize($entries))) { Chris@0: throw new \RuntimeException('Unable to store the metadata.'); Chris@0: } Chris@0: Chris@0: return $key; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns content digest for $response. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: protected function generateContentDigest(Response $response) Chris@0: { Chris@0: return 'en'.hash('sha256', $response->getContent()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Invalidates all cache entries that match the request. Chris@0: * Chris@0: * @throws \RuntimeException Chris@0: */ Chris@0: public function invalidate(Request $request) Chris@0: { Chris@0: $modified = false; Chris@0: $key = $this->getCacheKey($request); Chris@0: Chris@17: $entries = []; Chris@0: foreach ($this->getMetadata($key) as $entry) { Chris@0: $response = $this->restoreResponse($entry[1]); Chris@0: if ($response->isFresh()) { Chris@0: $response->expire(); Chris@0: $modified = true; Chris@17: $entries[] = [$entry[0], $this->persistResponse($response)]; Chris@0: } else { Chris@0: $entries[] = $entry; Chris@0: } Chris@0: } Chris@0: Chris@0: if ($modified && false === $this->save($key, serialize($entries))) { Chris@0: throw new \RuntimeException('Unable to store the metadata.'); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Determines whether two Request HTTP header sets are non-varying based on Chris@0: * the vary response header value provided. Chris@0: * Chris@0: * @param string $vary A Response vary header Chris@0: * @param array $env1 A Request HTTP header array Chris@0: * @param array $env2 A Request HTTP header array Chris@0: * Chris@0: * @return bool true if the two environments match, false otherwise Chris@0: */ Chris@0: private function requestsMatch($vary, $env1, $env2) Chris@0: { Chris@0: if (empty($vary)) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: foreach (preg_split('/[\s,]+/', $vary) as $header) { Chris@0: $key = str_replace('_', '-', strtolower($header)); Chris@0: $v1 = isset($env1[$key]) ? $env1[$key] : null; Chris@0: $v2 = isset($env2[$key]) ? $env2[$key] : null; Chris@0: if ($v1 !== $v2) { Chris@0: return false; Chris@0: } Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets all data associated with the given key. Chris@0: * Chris@0: * Use this method only if you know what you are doing. Chris@0: * Chris@0: * @param string $key The store key Chris@0: * Chris@0: * @return array An array of data associated with the key Chris@0: */ Chris@0: private function getMetadata($key) Chris@0: { Chris@0: if (!$entries = $this->load($key)) { Chris@17: return []; Chris@0: } Chris@0: Chris@0: return unserialize($entries); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Purges data for the given URL. Chris@0: * Chris@0: * This method purges both the HTTP and the HTTPS version of the cache entry. Chris@0: * Chris@0: * @param string $url A URL Chris@0: * Chris@0: * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise Chris@0: */ Chris@0: public function purge($url) Chris@0: { Chris@0: $http = preg_replace('#^https:#', 'http:', $url); Chris@0: $https = preg_replace('#^http:#', 'https:', $url); Chris@0: Chris@0: $purgedHttp = $this->doPurge($http); Chris@0: $purgedHttps = $this->doPurge($https); Chris@0: Chris@0: return $purgedHttp || $purgedHttps; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Purges data for the given URL. Chris@0: * Chris@0: * @param string $url A URL Chris@0: * Chris@0: * @return bool true if the URL exists and has been purged, false otherwise Chris@0: */ Chris@0: private function doPurge($url) Chris@0: { Chris@0: $key = $this->getCacheKey(Request::create($url)); Chris@0: if (isset($this->locks[$key])) { Chris@0: flock($this->locks[$key], LOCK_UN); Chris@0: fclose($this->locks[$key]); Chris@0: unset($this->locks[$key]); Chris@0: } Chris@0: Chris@0: if (file_exists($path = $this->getPath($key))) { Chris@0: unlink($path); Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Loads data for the given key. Chris@0: * Chris@0: * @param string $key The store key Chris@0: * Chris@0: * @return string The data associated with the key Chris@0: */ Chris@0: private function load($key) Chris@0: { Chris@0: $path = $this->getPath($key); Chris@0: Chris@0: return file_exists($path) ? file_get_contents($path) : false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Save data for the given key. Chris@0: * Chris@0: * @param string $key The store key Chris@0: * @param string $data The data to store Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function save($key, $data) Chris@0: { Chris@0: $path = $this->getPath($key); Chris@0: Chris@0: if (isset($this->locks[$key])) { Chris@0: $fp = $this->locks[$key]; Chris@0: @ftruncate($fp, 0); Chris@0: @fseek($fp, 0); Chris@0: $len = @fwrite($fp, $data); Chris@17: if (\strlen($data) !== $len) { Chris@0: @ftruncate($fp, 0); Chris@0: Chris@0: return false; Chris@0: } Chris@0: } else { Chris@17: if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) { Chris@0: return false; Chris@0: } Chris@0: Chris@17: $tmpFile = tempnam(\dirname($path), basename($path)); Chris@0: if (false === $fp = @fopen($tmpFile, 'wb')) { Chris@14: @unlink($tmpFile); Chris@14: Chris@0: return false; Chris@0: } Chris@0: @fwrite($fp, $data); Chris@0: @fclose($fp); Chris@0: Chris@0: if ($data != file_get_contents($tmpFile)) { Chris@14: @unlink($tmpFile); Chris@14: Chris@0: return false; Chris@0: } Chris@0: Chris@0: if (false === @rename($tmpFile, $path)) { Chris@14: @unlink($tmpFile); Chris@14: Chris@0: return false; Chris@0: } Chris@0: } Chris@0: Chris@0: @chmod($path, 0666 & ~umask()); Chris@0: } Chris@0: Chris@0: public function getPath($key) Chris@0: { Chris@17: return $this->root.\DIRECTORY_SEPARATOR.substr($key, 0, 2).\DIRECTORY_SEPARATOR.substr($key, 2, 2).\DIRECTORY_SEPARATOR.substr($key, 4, 2).\DIRECTORY_SEPARATOR.substr($key, 6); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates a cache key for the given Request. Chris@0: * Chris@0: * This method should return a key that must only depend on a Chris@0: * normalized version of the request URI. Chris@0: * Chris@0: * If the same URI can have more than one representation, based on some Chris@0: * headers, use a Vary header to indicate them, and each representation will Chris@0: * be stored independently under the same cache key. Chris@0: * Chris@0: * @return string A key for the given Request Chris@0: */ Chris@0: protected function generateCacheKey(Request $request) Chris@0: { Chris@0: return 'md'.hash('sha256', $request->getUri()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a cache key for the given Request. Chris@0: * Chris@0: * @return string A key for the given Request Chris@0: */ Chris@0: private function getCacheKey(Request $request) Chris@0: { Chris@0: if (isset($this->keyCache[$request])) { Chris@0: return $this->keyCache[$request]; Chris@0: } Chris@0: Chris@0: return $this->keyCache[$request] = $this->generateCacheKey($request); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Persists the Request HTTP headers. Chris@0: * Chris@0: * @return array An array of HTTP headers Chris@0: */ Chris@0: private function persistRequest(Request $request) Chris@0: { Chris@0: return $request->headers->all(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Persists the Response HTTP headers. Chris@0: * Chris@0: * @return array An array of HTTP headers Chris@0: */ Chris@0: private function persistResponse(Response $response) Chris@0: { Chris@0: $headers = $response->headers->all(); Chris@17: $headers['X-Status'] = [$response->getStatusCode()]; Chris@0: Chris@0: return $headers; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Restores a Response from the HTTP headers and body. Chris@0: * Chris@0: * @param array $headers An array of HTTP headers for the Response Chris@0: * @param string $body The Response body Chris@0: * Chris@0: * @return Response Chris@0: */ Chris@0: private function restoreResponse($headers, $body = null) Chris@0: { Chris@0: $status = $headers['X-Status'][0]; Chris@0: unset($headers['X-Status']); Chris@0: Chris@0: if (null !== $body) { Chris@17: $headers['X-Body-File'] = [$body]; Chris@0: } Chris@0: Chris@0: return new Response($body, $status, $headers); Chris@0: } Chris@0: }