Store.php 14KB

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