Store.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * This code is partially based on the Rack-Cache library by Ryan Tomayko,
  8. * which is released under the MIT license.
  9. *
  10. * For the full copyright and license information, please view the LICENSE
  11. * file that was distributed with this source code.
  12. */
  13. namespace Symfony\Component\HttpKernel\HttpCache;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. /**
  17. * Store implements all the logic for storing cache metadata (Request and Response headers).
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class Store implements StoreInterface
  22. {
  23. protected $root;
  24. private $keyCache;
  25. private $locks;
  26. /**
  27. * Constructor.
  28. *
  29. * @param string $root The path to the cache directory
  30. *
  31. * @throws \RuntimeException
  32. */
  33. public function __construct($root)
  34. {
  35. $this->root = $root;
  36. if (!is_dir($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
  37. throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
  38. }
  39. $this->keyCache = new \SplObjectStorage();
  40. $this->locks = array();
  41. }
  42. /**
  43. * Cleanups storage.
  44. */
  45. public function cleanup()
  46. {
  47. // unlock everything
  48. foreach ($this->locks as $lock) {
  49. if (file_exists($lock)) {
  50. @unlink($lock);
  51. }
  52. }
  53. $error = error_get_last();
  54. if (1 === $error['type'] && false === headers_sent()) {
  55. // send a 503
  56. header('HTTP/1.0 503 Service Unavailable');
  57. header('Retry-After: 10');
  58. echo '503 Service Unavailable';
  59. }
  60. }
  61. /**
  62. * Locks the cache for a given Request.
  63. *
  64. * @param Request $request A Request instance
  65. *
  66. * @return bool|string true if the lock is acquired, the path to the current lock otherwise
  67. */
  68. public function lock(Request $request)
  69. {
  70. $path = $this->getPath($this->getCacheKey($request).'.lck');
  71. if (!is_dir(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
  72. return false;
  73. }
  74. $lock = @fopen($path, 'x');
  75. if (false !== $lock) {
  76. fclose($lock);
  77. $this->locks[] = $path;
  78. return true;
  79. }
  80. return !file_exists($path) ?: $path;
  81. }
  82. /**
  83. * Releases the lock for the given Request.
  84. *
  85. * @param Request $request A Request instance
  86. *
  87. * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
  88. */
  89. public function unlock(Request $request)
  90. {
  91. $file = $this->getPath($this->getCacheKey($request).'.lck');
  92. return is_file($file) ? @unlink($file) : false;
  93. }
  94. public function isLocked(Request $request)
  95. {
  96. $path = $this->getPath($this->getCacheKey($request).'.lck');
  97. clearstatcache(true, $path);
  98. return is_file($path);
  99. }
  100. /**
  101. * Locates a cached Response for the Request provided.
  102. *
  103. * @param Request $request A Request instance
  104. *
  105. * @return Response|null A Response instance, or null if no cache entry was found
  106. */
  107. public function lookup(Request $request)
  108. {
  109. $key = $this->getCacheKey($request);
  110. if (!$entries = $this->getMetadata($key)) {
  111. return;
  112. }
  113. // find a cached entry that matches the request.
  114. $match = null;
  115. foreach ($entries as $entry) {
  116. if ($this->requestsMatch(isset($entry[1]['vary'][0]) ? implode(', ', $entry[1]['vary']) : '', $request->headers->all(), $entry[0])) {
  117. $match = $entry;
  118. break;
  119. }
  120. }
  121. if (null === $match) {
  122. return;
  123. }
  124. list($req, $headers) = $match;
  125. if (is_file($body = $this->getPath($headers['x-content-digest'][0]))) {
  126. return $this->restoreResponse($headers, $body);
  127. }
  128. // TODO the metaStore referenced an entity that doesn't exist in
  129. // the entityStore. We definitely want to return nil but we should
  130. // also purge the entry from the meta-store when this is detected.
  131. }
  132. /**
  133. * Writes a cache entry to the store for the given Request and Response.
  134. *
  135. * Existing entries are read and any that match the response are removed. This
  136. * method calls write with the new list of cache entries.
  137. *
  138. * @param Request $request A Request instance
  139. * @param Response $response A Response instance
  140. *
  141. * @return string The key under which the response is stored
  142. *
  143. * @throws \RuntimeException
  144. */
  145. public function write(Request $request, Response $response)
  146. {
  147. $key = $this->getCacheKey($request);
  148. $storedEnv = $this->persistRequest($request);
  149. // write the response body to the entity store if this is the original response
  150. if (!$response->headers->has('X-Content-Digest')) {
  151. $digest = $this->generateContentDigest($response);
  152. if (false === $this->save($digest, $response->getContent())) {
  153. throw new \RuntimeException('Unable to store the entity.');
  154. }
  155. $response->headers->set('X-Content-Digest', $digest);
  156. if (!$response->headers->has('Transfer-Encoding')) {
  157. $response->headers->set('Content-Length', strlen($response->getContent()));
  158. }
  159. }
  160. // read existing cache entries, remove non-varying, and add this one to the list
  161. $entries = array();
  162. $vary = $response->headers->get('vary');
  163. foreach ($this->getMetadata($key) as $entry) {
  164. if (!isset($entry[1]['vary'][0])) {
  165. $entry[1]['vary'] = array('');
  166. }
  167. if ($vary != $entry[1]['vary'][0] || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
  168. $entries[] = $entry;
  169. }
  170. }
  171. $headers = $this->persistResponse($response);
  172. unset($headers['age']);
  173. array_unshift($entries, array($storedEnv, $headers));
  174. if (false === $this->save($key, serialize($entries))) {
  175. throw new \RuntimeException('Unable to store the metadata.');
  176. }
  177. return $key;
  178. }
  179. /**
  180. * Returns content digest for $response.
  181. *
  182. * @param Response $response
  183. *
  184. * @return string
  185. */
  186. protected function generateContentDigest(Response $response)
  187. {
  188. return 'en'.hash('sha256', $response->getContent());
  189. }
  190. /**
  191. * Invalidates all cache entries that match the request.
  192. *
  193. * @param Request $request A Request instance
  194. *
  195. * @throws \RuntimeException
  196. */
  197. public function invalidate(Request $request)
  198. {
  199. $modified = false;
  200. $key = $this->getCacheKey($request);
  201. $entries = array();
  202. foreach ($this->getMetadata($key) as $entry) {
  203. $response = $this->restoreResponse($entry[1]);
  204. if ($response->isFresh()) {
  205. $response->expire();
  206. $modified = true;
  207. $entries[] = array($entry[0], $this->persistResponse($response));
  208. } else {
  209. $entries[] = $entry;
  210. }
  211. }
  212. if ($modified && false === $this->save($key, serialize($entries))) {
  213. throw new \RuntimeException('Unable to store the metadata.');
  214. }
  215. }
  216. /**
  217. * Determines whether two Request HTTP header sets are non-varying based on
  218. * the vary response header value provided.
  219. *
  220. * @param string $vary A Response vary header
  221. * @param array $env1 A Request HTTP header array
  222. * @param array $env2 A Request HTTP header array
  223. *
  224. * @return bool true if the two environments match, false otherwise
  225. */
  226. private function requestsMatch($vary, $env1, $env2)
  227. {
  228. if (empty($vary)) {
  229. return true;
  230. }
  231. foreach (preg_split('/[\s,]+/', $vary) as $header) {
  232. $key = str_replace('_', '-', strtolower($header));
  233. $v1 = isset($env1[$key]) ? $env1[$key] : null;
  234. $v2 = isset($env2[$key]) ? $env2[$key] : null;
  235. if ($v1 !== $v2) {
  236. return false;
  237. }
  238. }
  239. return true;
  240. }
  241. /**
  242. * Gets all data associated with the given key.
  243. *
  244. * Use this method only if you know what you are doing.
  245. *
  246. * @param string $key The store key
  247. *
  248. * @return array An array of data associated with the key
  249. */
  250. private function getMetadata($key)
  251. {
  252. if (false === $entries = $this->load($key)) {
  253. return array();
  254. }
  255. return unserialize($entries);
  256. }
  257. /**
  258. * Purges data for the given URL.
  259. *
  260. * @param string $url A URL
  261. *
  262. * @return bool true if the URL exists and has been purged, false otherwise
  263. */
  264. public function purge($url)
  265. {
  266. if (is_file($path = $this->getPath($this->getCacheKey(Request::create($url))))) {
  267. unlink($path);
  268. return true;
  269. }
  270. return false;
  271. }
  272. /**
  273. * Loads data for the given key.
  274. *
  275. * @param string $key The store key
  276. *
  277. * @return string The data associated with the key
  278. */
  279. private function load($key)
  280. {
  281. $path = $this->getPath($key);
  282. return is_file($path) ? file_get_contents($path) : false;
  283. }
  284. /**
  285. * Save data for the given key.
  286. *
  287. * @param string $key The store key
  288. * @param string $data The data to store
  289. *
  290. * @return bool
  291. */
  292. private function save($key, $data)
  293. {
  294. $path = $this->getPath($key);
  295. if (!is_dir(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
  296. return false;
  297. }
  298. $tmpFile = tempnam(dirname($path), basename($path));
  299. if (false === $fp = @fopen($tmpFile, 'wb')) {
  300. return false;
  301. }
  302. @fwrite($fp, $data);
  303. @fclose($fp);
  304. if ($data != file_get_contents($tmpFile)) {
  305. return false;
  306. }
  307. if (false === @rename($tmpFile, $path)) {
  308. return false;
  309. }
  310. @chmod($path, 0666 & ~umask());
  311. }
  312. public function getPath($key)
  313. {
  314. 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);
  315. }
  316. /**
  317. * Generates a cache key for the given Request.
  318. *
  319. * This method should return a key that must only depend on a
  320. * normalized version of the request URI.
  321. *
  322. * If the same URI can have more than one representation, based on some
  323. * headers, use a Vary header to indicate them, and each representation will
  324. * be stored independently under the same cache key.
  325. *
  326. * @param Request $request A Request instance
  327. *
  328. * @return string A key for the given Request
  329. */
  330. protected function generateCacheKey(Request $request)
  331. {
  332. return 'md'.hash('sha256', $request->getUri());
  333. }
  334. /**
  335. * Returns a cache key for the given Request.
  336. *
  337. * @param Request $request A Request instance
  338. *
  339. * @return string A key for the given Request
  340. */
  341. private function getCacheKey(Request $request)
  342. {
  343. if (isset($this->keyCache[$request])) {
  344. return $this->keyCache[$request];
  345. }
  346. return $this->keyCache[$request] = $this->generateCacheKey($request);
  347. }
  348. /**
  349. * Persists the Request HTTP headers.
  350. *
  351. * @param Request $request A Request instance
  352. *
  353. * @return array An array of HTTP headers
  354. */
  355. private function persistRequest(Request $request)
  356. {
  357. return $request->headers->all();
  358. }
  359. /**
  360. * Persists the Response HTTP headers.
  361. *
  362. * @param Response $response A Response instance
  363. *
  364. * @return array An array of HTTP headers
  365. */
  366. private function persistResponse(Response $response)
  367. {
  368. $headers = $response->headers->all();
  369. $headers['X-Status'] = array($response->getStatusCode());
  370. return $headers;
  371. }
  372. /**
  373. * Restores a Response from the HTTP headers and body.
  374. *
  375. * @param array $headers An array of HTTP headers for the Response
  376. * @param string $body The Response body
  377. *
  378. * @return Response
  379. */
  380. private function restoreResponse($headers, $body = null)
  381. {
  382. $status = $headers['X-Status'][0];
  383. unset($headers['X-Status']);
  384. if (null !== $body) {
  385. $headers['X-Body-File'] = array($body);
  386. }
  387. return new Response($body, $status, $headers);
  388. }
  389. }