No Description

Store.php 12KB

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