Store.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 \SplObjectStorage $keyCache;
  26. /** @var array<string, resource> */
  27. private array $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): bool|string
  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): bool
  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): bool
  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. public function lookup(Request $request): ?Response
  108. {
  109. $key = $this->getCacheKey($request);
  110. if (!$entries = $this->getMetadata($key)) {
  111. return null;
  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 null;
  123. }
  124. $headers = $match[1];
  125. if (file_exists($path = $this->getPath($headers['x-content-digest'][0]))) {
  126. return $this->restoreResponse($headers, $path);
  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. return null;
  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. * @throws \RuntimeException
  140. */
  141. public function write(Request $request, Response $response): string
  142. {
  143. $key = $this->getCacheKey($request);
  144. $storedEnv = $this->persistRequest($request);
  145. if ($response->headers->has('X-Body-File')) {
  146. // Assume the response came from disk, but at least perform some safeguard checks
  147. if (!$response->headers->has('X-Content-Digest')) {
  148. throw new \RuntimeException('A restored response must have the X-Content-Digest header.');
  149. }
  150. $digest = $response->headers->get('X-Content-Digest');
  151. if ($this->getPath($digest) !== $response->headers->get('X-Body-File')) {
  152. throw new \RuntimeException('X-Body-File and X-Content-Digest do not match.');
  153. }
  154. // Everything seems ok, omit writing content to disk
  155. } else {
  156. $digest = $this->generateContentDigest($response);
  157. $response->headers->set('X-Content-Digest', $digest);
  158. if (!$this->save($digest, $response->getContent(), false)) {
  159. throw new \RuntimeException('Unable to store the entity.');
  160. }
  161. if (!$response->headers->has('Transfer-Encoding')) {
  162. $response->headers->set('Content-Length', \strlen($response->getContent()));
  163. }
  164. }
  165. // read existing cache entries, remove non-varying, and add this one to the list
  166. $entries = [];
  167. $vary = $response->headers->get('vary');
  168. foreach ($this->getMetadata($key) as $entry) {
  169. if (!isset($entry[1]['vary'][0])) {
  170. $entry[1]['vary'] = [''];
  171. }
  172. if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary ?? '', $entry[0], $storedEnv)) {
  173. $entries[] = $entry;
  174. }
  175. }
  176. $headers = $this->persistResponse($response);
  177. unset($headers['age']);
  178. array_unshift($entries, [$storedEnv, $headers]);
  179. if (!$this->save($key, serialize($entries))) {
  180. throw new \RuntimeException('Unable to store the metadata.');
  181. }
  182. return $key;
  183. }
  184. /**
  185. * Returns content digest for $response.
  186. */
  187. protected function generateContentDigest(Response $response): string
  188. {
  189. return 'en'.hash('sha256', $response->getContent());
  190. }
  191. /**
  192. * Invalidates all cache entries that match the request.
  193. *
  194. * @throws \RuntimeException
  195. */
  196. public function invalidate(Request $request)
  197. {
  198. $modified = false;
  199. $key = $this->getCacheKey($request);
  200. $entries = [];
  201. foreach ($this->getMetadata($key) as $entry) {
  202. $response = $this->restoreResponse($entry[1]);
  203. if ($response->isFresh()) {
  204. $response->expire();
  205. $modified = true;
  206. $entries[] = [$entry[0], $this->persistResponse($response)];
  207. } else {
  208. $entries[] = $entry;
  209. }
  210. }
  211. if ($modified && !$this->save($key, serialize($entries))) {
  212. throw new \RuntimeException('Unable to store the metadata.');
  213. }
  214. }
  215. /**
  216. * Determines whether two Request HTTP header sets are non-varying based on
  217. * the vary response header value provided.
  218. *
  219. * @param string|null $vary A Response vary header
  220. * @param array $env1 A Request HTTP header array
  221. * @param array $env2 A Request HTTP header array
  222. */
  223. private function requestsMatch(?string $vary, array $env1, array $env2): bool
  224. {
  225. if (empty($vary)) {
  226. return true;
  227. }
  228. foreach (preg_split('/[\s,]+/', $vary) as $header) {
  229. $key = str_replace('_', '-', strtolower($header));
  230. $v1 = $env1[$key] ?? null;
  231. $v2 = $env2[$key] ?? null;
  232. if ($v1 !== $v2) {
  233. return false;
  234. }
  235. }
  236. return true;
  237. }
  238. /**
  239. * Gets all data associated with the given key.
  240. *
  241. * Use this method only if you know what you are doing.
  242. */
  243. private function getMetadata(string $key): array
  244. {
  245. if (!$entries = $this->load($key)) {
  246. return [];
  247. }
  248. return unserialize($entries) ?: [];
  249. }
  250. /**
  251. * Purges data for the given URL.
  252. *
  253. * This method purges both the HTTP and the HTTPS version of the cache entry.
  254. *
  255. * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise
  256. */
  257. public function purge(string $url): bool
  258. {
  259. $http = preg_replace('#^https:#', 'http:', $url);
  260. $https = preg_replace('#^http:#', 'https:', $url);
  261. $purgedHttp = $this->doPurge($http);
  262. $purgedHttps = $this->doPurge($https);
  263. return $purgedHttp || $purgedHttps;
  264. }
  265. /**
  266. * Purges data for the given URL.
  267. */
  268. private function doPurge(string $url): bool
  269. {
  270. $key = $this->getCacheKey(Request::create($url));
  271. if (isset($this->locks[$key])) {
  272. flock($this->locks[$key], \LOCK_UN);
  273. fclose($this->locks[$key]);
  274. unset($this->locks[$key]);
  275. }
  276. if (is_file($path = $this->getPath($key))) {
  277. unlink($path);
  278. return true;
  279. }
  280. return false;
  281. }
  282. /**
  283. * Loads data for the given key.
  284. */
  285. private function load(string $key): ?string
  286. {
  287. $path = $this->getPath($key);
  288. return is_file($path) && false !== ($contents = @file_get_contents($path)) ? $contents : null;
  289. }
  290. /**
  291. * Save data for the given key.
  292. */
  293. private function save(string $key, string $data, bool $overwrite = true): bool
  294. {
  295. $path = $this->getPath($key);
  296. if (!$overwrite && file_exists($path)) {
  297. return true;
  298. }
  299. if (isset($this->locks[$key])) {
  300. $fp = $this->locks[$key];
  301. @ftruncate($fp, 0);
  302. @fseek($fp, 0);
  303. $len = @fwrite($fp, $data);
  304. if (\strlen($data) !== $len) {
  305. @ftruncate($fp, 0);
  306. return false;
  307. }
  308. } else {
  309. if (!is_dir(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
  310. return false;
  311. }
  312. $tmpFile = tempnam(\dirname($path), basename($path));
  313. if (false === $fp = @fopen($tmpFile, 'w')) {
  314. @unlink($tmpFile);
  315. return false;
  316. }
  317. @fwrite($fp, $data);
  318. @fclose($fp);
  319. if ($data != file_get_contents($tmpFile)) {
  320. @unlink($tmpFile);
  321. return false;
  322. }
  323. if (false === @rename($tmpFile, $path)) {
  324. @unlink($tmpFile);
  325. return false;
  326. }
  327. }
  328. @chmod($path, 0666 & ~umask());
  329. return true;
  330. }
  331. public function getPath(string $key)
  332. {
  333. 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);
  334. }
  335. /**
  336. * Generates a cache key for the given Request.
  337. *
  338. * This method should return a key that must only depend on a
  339. * normalized version of the request URI.
  340. *
  341. * If the same URI can have more than one representation, based on some
  342. * headers, use a Vary header to indicate them, and each representation will
  343. * be stored independently under the same cache key.
  344. */
  345. protected function generateCacheKey(Request $request): string
  346. {
  347. return 'md'.hash('sha256', $request->getUri());
  348. }
  349. /**
  350. * Returns a cache key for the given Request.
  351. */
  352. private function getCacheKey(Request $request): string
  353. {
  354. if (isset($this->keyCache[$request])) {
  355. return $this->keyCache[$request];
  356. }
  357. return $this->keyCache[$request] = $this->generateCacheKey($request);
  358. }
  359. /**
  360. * Persists the Request HTTP headers.
  361. */
  362. private function persistRequest(Request $request): array
  363. {
  364. return $request->headers->all();
  365. }
  366. /**
  367. * Persists the Response HTTP headers.
  368. */
  369. private function persistResponse(Response $response): array
  370. {
  371. $headers = $response->headers->all();
  372. $headers['X-Status'] = [$response->getStatusCode()];
  373. return $headers;
  374. }
  375. /**
  376. * Restores a Response from the HTTP headers and body.
  377. */
  378. private function restoreResponse(array $headers, string $path = null): Response
  379. {
  380. $status = $headers['X-Status'][0];
  381. unset($headers['X-Status']);
  382. if (null !== $path) {
  383. $headers['X-Body-File'] = [$path];
  384. }
  385. return new Response($path, $status, $headers);
  386. }
  387. }