Store.php 12 KB

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