Store.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. * @param string $root The path to the cache directory
  28. *
  29. * @throws \RuntimeException
  30. */
  31. public function __construct($root)
  32. {
  33. $this->root = $root;
  34. if (!file_exists($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
  35. throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
  36. }
  37. $this->keyCache = new \SplObjectStorage();
  38. $this->locks = array();
  39. }
  40. /**
  41. * Cleanups storage.
  42. */
  43. public function cleanup()
  44. {
  45. // unlock everything
  46. foreach ($this->locks as $lock) {
  47. flock($lock, LOCK_UN);
  48. fclose($lock);
  49. }
  50. $this->locks = array();
  51. }
  52. /**
  53. * Tries to lock the cache for a given Request, without blocking.
  54. *
  55. * @return bool|string true if the lock is acquired, the path to the current lock otherwise
  56. */
  57. public function lock(Request $request)
  58. {
  59. $key = $this->getCacheKey($request);
  60. if (!isset($this->locks[$key])) {
  61. $path = $this->getPath($key);
  62. if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
  63. return $path;
  64. }
  65. $h = fopen($path, 'cb');
  66. if (!flock($h, LOCK_EX | LOCK_NB)) {
  67. fclose($h);
  68. return $path;
  69. }
  70. $this->locks[$key] = $h;
  71. }
  72. return true;
  73. }
  74. /**
  75. * Releases the lock for the given Request.
  76. *
  77. * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
  78. */
  79. public function unlock(Request $request)
  80. {
  81. $key = $this->getCacheKey($request);
  82. if (isset($this->locks[$key])) {
  83. flock($this->locks[$key], LOCK_UN);
  84. fclose($this->locks[$key]);
  85. unset($this->locks[$key]);
  86. return true;
  87. }
  88. return false;
  89. }
  90. public function isLocked(Request $request)
  91. {
  92. $key = $this->getCacheKey($request);
  93. if (isset($this->locks[$key])) {
  94. return true; // shortcut if lock held by this process
  95. }
  96. if (!file_exists($path = $this->getPath($key))) {
  97. return false;
  98. }
  99. $h = fopen($path, 'rb');
  100. flock($h, LOCK_EX | LOCK_NB, $wouldBlock);
  101. flock($h, LOCK_UN); // release the lock we just acquired
  102. fclose($h);
  103. return (bool) $wouldBlock;
  104. }
  105. /**
  106. * Locates a cached Response for the Request provided.
  107. *
  108. * @return Response|null A Response instance, or null if no cache entry was found
  109. */
  110. public function lookup(Request $request)
  111. {
  112. $key = $this->getCacheKey($request);
  113. if (!$entries = $this->getMetadata($key)) {
  114. return;
  115. }
  116. // find a cached entry that matches the request.
  117. $match = null;
  118. foreach ($entries as $entry) {
  119. if ($this->requestsMatch(isset($entry[1]['vary'][0]) ? implode(', ', $entry[1]['vary']) : '', $request->headers->all(), $entry[0])) {
  120. $match = $entry;
  121. break;
  122. }
  123. }
  124. if (null === $match) {
  125. return;
  126. }
  127. $headers = $match[1];
  128. if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
  129. return $this->restoreResponse($headers, $body);
  130. }
  131. // TODO the metaStore referenced an entity that doesn't exist in
  132. // the entityStore. We definitely want to return nil but we should
  133. // also purge the entry from the meta-store when this is detected.
  134. }
  135. /**
  136. * Writes a cache entry to the store for the given Request and Response.
  137. *
  138. * Existing entries are read and any that match the response are removed. This
  139. * method calls write with the new list of cache entries.
  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 ($entry[1]['vary'][0] != $vary || !$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. * @return string
  183. */
  184. protected function generateContentDigest(Response $response)
  185. {
  186. return 'en'.hash('sha256', $response->getContent());
  187. }
  188. /**
  189. * Invalidates all cache entries that match the request.
  190. *
  191. * @throws \RuntimeException
  192. */
  193. public function invalidate(Request $request)
  194. {
  195. $modified = false;
  196. $key = $this->getCacheKey($request);
  197. $entries = array();
  198. foreach ($this->getMetadata($key) as $entry) {
  199. $response = $this->restoreResponse($entry[1]);
  200. if ($response->isFresh()) {
  201. $response->expire();
  202. $modified = true;
  203. $entries[] = array($entry[0], $this->persistResponse($response));
  204. } else {
  205. $entries[] = $entry;
  206. }
  207. }
  208. if ($modified && false === $this->save($key, serialize($entries))) {
  209. throw new \RuntimeException('Unable to store the metadata.');
  210. }
  211. }
  212. /**
  213. * Determines whether two Request HTTP header sets are non-varying based on
  214. * the vary response header value provided.
  215. *
  216. * @param string $vary A Response vary header
  217. * @param array $env1 A Request HTTP header array
  218. * @param array $env2 A Request HTTP header array
  219. *
  220. * @return bool true if the two environments match, false otherwise
  221. */
  222. private function requestsMatch($vary, $env1, $env2)
  223. {
  224. if (empty($vary)) {
  225. return true;
  226. }
  227. foreach (preg_split('/[\s,]+/', $vary) as $header) {
  228. $key = str_replace('_', '-', strtolower($header));
  229. $v1 = isset($env1[$key]) ? $env1[$key] : null;
  230. $v2 = isset($env2[$key]) ? $env2[$key] : null;
  231. if ($v1 !== $v2) {
  232. return false;
  233. }
  234. }
  235. return true;
  236. }
  237. /**
  238. * Gets all data associated with the given key.
  239. *
  240. * Use this method only if you know what you are doing.
  241. *
  242. * @param string $key The store key
  243. *
  244. * @return array An array of data associated with the key
  245. */
  246. private function getMetadata($key)
  247. {
  248. if (!$entries = $this->load($key)) {
  249. return array();
  250. }
  251. return unserialize($entries);
  252. }
  253. /**
  254. * Purges data for the given URL.
  255. *
  256. * This method purges both the HTTP and the HTTPS version of the cache entry.
  257. *
  258. * @param string $url A URL
  259. *
  260. * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise
  261. */
  262. public function purge($url)
  263. {
  264. $http = preg_replace('#^https:#', 'http:', $url);
  265. $https = preg_replace('#^http:#', 'https:', $url);
  266. $purgedHttp = $this->doPurge($http);
  267. $purgedHttps = $this->doPurge($https);
  268. return $purgedHttp || $purgedHttps;
  269. }
  270. /**
  271. * Purges data for the given URL.
  272. *
  273. * @param string $url A URL
  274. *
  275. * @return bool true if the URL exists and has been purged, false otherwise
  276. */
  277. private function doPurge($url)
  278. {
  279. $key = $this->getCacheKey(Request::create($url));
  280. if (isset($this->locks[$key])) {
  281. flock($this->locks[$key], LOCK_UN);
  282. fclose($this->locks[$key]);
  283. unset($this->locks[$key]);
  284. }
  285. if (file_exists($path = $this->getPath($key))) {
  286. unlink($path);
  287. return true;
  288. }
  289. return false;
  290. }
  291. /**
  292. * Loads data for the given key.
  293. *
  294. * @param string $key The store key
  295. *
  296. * @return string The data associated with the key
  297. */
  298. private function load($key)
  299. {
  300. $path = $this->getPath($key);
  301. return file_exists($path) ? file_get_contents($path) : false;
  302. }
  303. /**
  304. * Save data for the given key.
  305. *
  306. * @param string $key The store key
  307. * @param string $data The data to store
  308. *
  309. * @return bool
  310. */
  311. private function save($key, $data)
  312. {
  313. $path = $this->getPath($key);
  314. if (isset($this->locks[$key])) {
  315. $fp = $this->locks[$key];
  316. @ftruncate($fp, 0);
  317. @fseek($fp, 0);
  318. $len = @fwrite($fp, $data);
  319. if (\strlen($data) !== $len) {
  320. @ftruncate($fp, 0);
  321. return false;
  322. }
  323. } else {
  324. if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
  325. return false;
  326. }
  327. $tmpFile = tempnam(\dirname($path), basename($path));
  328. if (false === $fp = @fopen($tmpFile, 'wb')) {
  329. @unlink($tmpFile);
  330. return false;
  331. }
  332. @fwrite($fp, $data);
  333. @fclose($fp);
  334. if ($data != file_get_contents($tmpFile)) {
  335. @unlink($tmpFile);
  336. return false;
  337. }
  338. if (false === @rename($tmpFile, $path)) {
  339. @unlink($tmpFile);
  340. return false;
  341. }
  342. }
  343. @chmod($path, 0666 & ~umask());
  344. }
  345. public function getPath($key)
  346. {
  347. 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);
  348. }
  349. /**
  350. * Generates a cache key for the given Request.
  351. *
  352. * This method should return a key that must only depend on a
  353. * normalized version of the request URI.
  354. *
  355. * If the same URI can have more than one representation, based on some
  356. * headers, use a Vary header to indicate them, and each representation will
  357. * be stored independently under the same cache key.
  358. *
  359. * @return string A key for the given Request
  360. */
  361. protected function generateCacheKey(Request $request)
  362. {
  363. return 'md'.hash('sha256', $request->getUri());
  364. }
  365. /**
  366. * Returns a cache key for the given Request.
  367. *
  368. * @return string A key for the given Request
  369. */
  370. private function getCacheKey(Request $request)
  371. {
  372. if (isset($this->keyCache[$request])) {
  373. return $this->keyCache[$request];
  374. }
  375. return $this->keyCache[$request] = $this->generateCacheKey($request);
  376. }
  377. /**
  378. * Persists the Request HTTP headers.
  379. *
  380. * @return array An array of HTTP headers
  381. */
  382. private function persistRequest(Request $request)
  383. {
  384. return $request->headers->all();
  385. }
  386. /**
  387. * Persists the Response HTTP headers.
  388. *
  389. * @return array An array of HTTP headers
  390. */
  391. private function persistResponse(Response $response)
  392. {
  393. $headers = $response->headers->all();
  394. $headers['X-Status'] = array($response->getStatusCode());
  395. return $headers;
  396. }
  397. /**
  398. * Restores a Response from the HTTP headers and body.
  399. *
  400. * @param array $headers An array of HTTP headers for the Response
  401. * @param string $body The Response body
  402. *
  403. * @return Response
  404. */
  405. private function restoreResponse($headers, $body = null)
  406. {
  407. $status = $headers['X-Status'][0];
  408. unset($headers['X-Status']);
  409. if (null !== $body) {
  410. $headers['X-Body-File'] = array($body);
  411. }
  412. return new Response($body, $status, $headers);
  413. }
  414. }