Store.php 13 KB

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