You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

473 lines
13 KiB

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