HttpCache.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
  10. *
  11. * For the full copyright and license information, please view the LICENSE
  12. * file that was distributed with this source code.
  13. */
  14. namespace Symfony\Component\HttpKernel\HttpCache;
  15. use Symfony\Component\HttpKernel\HttpKernelInterface;
  16. use Symfony\Component\HttpKernel\TerminableInterface;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. /**
  20. * Cache provides HTTP caching.
  21. *
  22. * @author Fabien Potencier <fabien@symfony.com>
  23. */
  24. class HttpCache implements HttpKernelInterface, TerminableInterface
  25. {
  26. private $kernel;
  27. private $store;
  28. private $request;
  29. private $surrogate;
  30. private $surrogateCacheStrategy;
  31. private $options = array();
  32. private $traces = array();
  33. /**
  34. * Constructor.
  35. *
  36. * The available options are:
  37. *
  38. * * debug: If true, the traces are added as a HTTP header to ease debugging
  39. *
  40. * * default_ttl The number of seconds that a cache entry should be considered
  41. * fresh when no explicit freshness information is provided in
  42. * a response. Explicit Cache-Control or Expires headers
  43. * override this value. (default: 0)
  44. *
  45. * * private_headers Set of request headers that trigger "private" cache-control behavior
  46. * on responses that don't explicitly state whether the response is
  47. * public or private via a Cache-Control directive. (default: Authorization and Cookie)
  48. *
  49. * * allow_reload Specifies whether the client can force a cache reload by including a
  50. * Cache-Control "no-cache" directive in the request. Set it to ``true``
  51. * for compliance with RFC 2616. (default: false)
  52. *
  53. * * allow_revalidate Specifies whether the client can force a cache revalidate by including
  54. * a Cache-Control "max-age=0" directive in the request. Set it to ``true``
  55. * for compliance with RFC 2616. (default: false)
  56. *
  57. * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the
  58. * Response TTL precision is a second) during which the cache can immediately return
  59. * a stale response while it revalidates it in the background (default: 2).
  60. * This setting is overridden by the stale-while-revalidate HTTP Cache-Control
  61. * extension (see RFC 5861).
  62. *
  63. * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which
  64. * the cache can serve a stale response when an error is encountered (default: 60).
  65. * This setting is overridden by the stale-if-error HTTP Cache-Control extension
  66. * (see RFC 5861).
  67. *
  68. * @param HttpKernelInterface $kernel An HttpKernelInterface instance
  69. * @param StoreInterface $store A Store instance
  70. * @param SurrogateInterface $surrogate A SurrogateInterface instance
  71. * @param array $options An array of options
  72. */
  73. public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
  74. {
  75. $this->store = $store;
  76. $this->kernel = $kernel;
  77. $this->surrogate = $surrogate;
  78. // needed in case there is a fatal error because the backend is too slow to respond
  79. register_shutdown_function(array($this->store, 'cleanup'));
  80. $this->options = array_merge(array(
  81. 'debug' => false,
  82. 'default_ttl' => 0,
  83. 'private_headers' => array('Authorization', 'Cookie'),
  84. 'allow_reload' => false,
  85. 'allow_revalidate' => false,
  86. 'stale_while_revalidate' => 2,
  87. 'stale_if_error' => 60,
  88. ), $options);
  89. }
  90. /**
  91. * Gets the current store.
  92. *
  93. * @return StoreInterface $store A StoreInterface instance
  94. */
  95. public function getStore()
  96. {
  97. return $this->store;
  98. }
  99. /**
  100. * Returns an array of events that took place during processing of the last request.
  101. *
  102. * @return array An array of events
  103. */
  104. public function getTraces()
  105. {
  106. return $this->traces;
  107. }
  108. /**
  109. * Returns a log message for the events of the last request processing.
  110. *
  111. * @return string A log message
  112. */
  113. public function getLog()
  114. {
  115. $log = array();
  116. foreach ($this->traces as $request => $traces) {
  117. $log[] = sprintf('%s: %s', $request, implode(', ', $traces));
  118. }
  119. return implode('; ', $log);
  120. }
  121. /**
  122. * Gets the Request instance associated with the master request.
  123. *
  124. * @return Request A Request instance
  125. */
  126. public function getRequest()
  127. {
  128. return $this->request;
  129. }
  130. /**
  131. * Gets the Kernel instance.
  132. *
  133. * @return HttpKernelInterface An HttpKernelInterface instance
  134. */
  135. public function getKernel()
  136. {
  137. return $this->kernel;
  138. }
  139. /**
  140. * Gets the Surrogate instance.
  141. *
  142. * @return SurrogateInterface A Surrogate instance
  143. *
  144. * @throws \LogicException
  145. */
  146. public function getSurrogate()
  147. {
  148. return $this->surrogate;
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  154. {
  155. // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
  156. if (HttpKernelInterface::MASTER_REQUEST === $type) {
  157. $this->traces = array();
  158. $this->request = $request;
  159. if (null !== $this->surrogate) {
  160. $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy();
  161. }
  162. }
  163. $path = $request->getPathInfo();
  164. if ($qs = $request->getQueryString()) {
  165. $path .= '?'.$qs;
  166. }
  167. $this->traces[$request->getMethod().' '.$path] = array();
  168. if (!$request->isMethodSafe()) {
  169. $response = $this->invalidate($request, $catch);
  170. } elseif ($request->headers->has('expect')) {
  171. $response = $this->pass($request, $catch);
  172. } else {
  173. $response = $this->lookup($request, $catch);
  174. }
  175. $this->restoreResponseBody($request, $response);
  176. $response->setDate(\DateTime::createFromFormat('U', time(), new \DateTimeZone('UTC')));
  177. if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
  178. $response->headers->set('X-Symfony-Cache', $this->getLog());
  179. }
  180. if (null !== $this->surrogate) {
  181. if (HttpKernelInterface::MASTER_REQUEST === $type) {
  182. $this->surrogateCacheStrategy->update($response);
  183. } else {
  184. $this->surrogateCacheStrategy->add($response);
  185. }
  186. }
  187. $response->prepare($request);
  188. $response->isNotModified($request);
  189. return $response;
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. public function terminate(Request $request, Response $response)
  195. {
  196. if ($this->getKernel() instanceof TerminableInterface) {
  197. $this->getKernel()->terminate($request, $response);
  198. }
  199. }
  200. /**
  201. * Forwards the Request to the backend without storing the Response in the cache.
  202. *
  203. * @param Request $request A Request instance
  204. * @param bool $catch Whether to process exceptions
  205. *
  206. * @return Response A Response instance
  207. */
  208. protected function pass(Request $request, $catch = false)
  209. {
  210. $this->record($request, 'pass');
  211. return $this->forward($request, $catch);
  212. }
  213. /**
  214. * Invalidates non-safe methods (like POST, PUT, and DELETE).
  215. *
  216. * @param Request $request A Request instance
  217. * @param bool $catch Whether to process exceptions
  218. *
  219. * @return Response A Response instance
  220. *
  221. * @throws \Exception
  222. *
  223. * @see RFC2616 13.10
  224. */
  225. protected function invalidate(Request $request, $catch = false)
  226. {
  227. $response = $this->pass($request, $catch);
  228. // invalidate only when the response is successful
  229. if ($response->isSuccessful() || $response->isRedirect()) {
  230. try {
  231. $this->store->invalidate($request);
  232. // As per the RFC, invalidate Location and Content-Location URLs if present
  233. foreach (array('Location', 'Content-Location') as $header) {
  234. if ($uri = $response->headers->get($header)) {
  235. $subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
  236. $this->store->invalidate($subRequest);
  237. }
  238. }
  239. $this->record($request, 'invalidate');
  240. } catch (\Exception $e) {
  241. $this->record($request, 'invalidate-failed');
  242. if ($this->options['debug']) {
  243. throw $e;
  244. }
  245. }
  246. }
  247. return $response;
  248. }
  249. /**
  250. * Lookups a Response from the cache for the given Request.
  251. *
  252. * When a matching cache entry is found and is fresh, it uses it as the
  253. * response without forwarding any request to the backend. When a matching
  254. * cache entry is found but is stale, it attempts to "validate" the entry with
  255. * the backend using conditional GET. When no matching cache entry is found,
  256. * it triggers "miss" processing.
  257. *
  258. * @param Request $request A Request instance
  259. * @param bool $catch whether to process exceptions
  260. *
  261. * @return Response A Response instance
  262. *
  263. * @throws \Exception
  264. */
  265. protected function lookup(Request $request, $catch = false)
  266. {
  267. // if allow_reload and no-cache Cache-Control, allow a cache reload
  268. if ($this->options['allow_reload'] && $request->isNoCache()) {
  269. $this->record($request, 'reload');
  270. return $this->fetch($request, $catch);
  271. }
  272. try {
  273. $entry = $this->store->lookup($request);
  274. } catch (\Exception $e) {
  275. $this->record($request, 'lookup-failed');
  276. if ($this->options['debug']) {
  277. throw $e;
  278. }
  279. return $this->pass($request, $catch);
  280. }
  281. if (null === $entry) {
  282. $this->record($request, 'miss');
  283. return $this->fetch($request, $catch);
  284. }
  285. if (!$this->isFreshEnough($request, $entry)) {
  286. $this->record($request, 'stale');
  287. return $this->validate($request, $entry, $catch);
  288. }
  289. $this->record($request, 'fresh');
  290. $entry->headers->set('Age', $entry->getAge());
  291. return $entry;
  292. }
  293. /**
  294. * Validates that a cache entry is fresh.
  295. *
  296. * The original request is used as a template for a conditional
  297. * GET request with the backend.
  298. *
  299. * @param Request $request A Request instance
  300. * @param Response $entry A Response instance to validate
  301. * @param bool $catch Whether to process exceptions
  302. *
  303. * @return Response A Response instance
  304. */
  305. protected function validate(Request $request, Response $entry, $catch = false)
  306. {
  307. $subRequest = clone $request;
  308. // send no head requests because we want content
  309. $subRequest->setMethod('GET');
  310. // add our cached last-modified validator
  311. $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
  312. // Add our cached etag validator to the environment.
  313. // We keep the etags from the client to handle the case when the client
  314. // has a different private valid entry which is not cached here.
  315. $cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
  316. $requestEtags = $request->getETags();
  317. if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
  318. $subRequest->headers->set('if_none_match', implode(', ', $etags));
  319. }
  320. $response = $this->forward($subRequest, $catch, $entry);
  321. if (304 == $response->getStatusCode()) {
  322. $this->record($request, 'valid');
  323. // return the response and not the cache entry if the response is valid but not cached
  324. $etag = $response->getEtag();
  325. if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
  326. return $response;
  327. }
  328. $entry = clone $entry;
  329. $entry->headers->remove('Date');
  330. foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
  331. if ($response->headers->has($name)) {
  332. $entry->headers->set($name, $response->headers->get($name));
  333. }
  334. }
  335. $response = $entry;
  336. } else {
  337. $this->record($request, 'invalid');
  338. }
  339. if ($response->isCacheable()) {
  340. $this->store($request, $response);
  341. }
  342. return $response;
  343. }
  344. /**
  345. * Forwards the Request to the backend and determines whether the response should be stored.
  346. *
  347. * This methods is triggered when the cache missed or a reload is required.
  348. *
  349. * @param Request $request A Request instance
  350. * @param bool $catch whether to process exceptions
  351. *
  352. * @return Response A Response instance
  353. */
  354. protected function fetch(Request $request, $catch = false)
  355. {
  356. $subRequest = clone $request;
  357. // send no head requests because we want content
  358. $subRequest->setMethod('GET');
  359. // avoid that the backend sends no content
  360. $subRequest->headers->remove('if_modified_since');
  361. $subRequest->headers->remove('if_none_match');
  362. $response = $this->forward($subRequest, $catch);
  363. if ($response->isCacheable()) {
  364. $this->store($request, $response);
  365. }
  366. return $response;
  367. }
  368. /**
  369. * Forwards the Request to the backend and returns the Response.
  370. *
  371. * @param Request $request A Request instance
  372. * @param bool $catch Whether to catch exceptions or not
  373. * @param Response $entry A Response instance (the stale entry if present, null otherwise)
  374. *
  375. * @return Response A Response instance
  376. */
  377. protected function forward(Request $request, $catch = false, Response $entry = null)
  378. {
  379. if ($this->surrogate) {
  380. $this->surrogate->addSurrogateCapability($request);
  381. }
  382. // modify the X-Forwarded-For header if needed
  383. $forwardedFor = $request->headers->get('X-Forwarded-For');
  384. if ($forwardedFor) {
  385. $request->headers->set('X-Forwarded-For', $forwardedFor.', '.$request->server->get('REMOTE_ADDR'));
  386. } else {
  387. $request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR'));
  388. }
  389. // fix the client IP address by setting it to 127.0.0.1 as HttpCache
  390. // is always called from the same process as the backend.
  391. $request->server->set('REMOTE_ADDR', '127.0.0.1');
  392. // make sure HttpCache is a trusted proxy
  393. if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) {
  394. $trustedProxies[] = '127.0.0.1';
  395. Request::setTrustedProxies($trustedProxies);
  396. }
  397. // always a "master" request (as the real master request can be in cache)
  398. $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
  399. // FIXME: we probably need to also catch exceptions if raw === true
  400. // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
  401. if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
  402. if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
  403. $age = $this->options['stale_if_error'];
  404. }
  405. if (abs($entry->getTtl()) < $age) {
  406. $this->record($request, 'stale-if-error');
  407. return $entry;
  408. }
  409. }
  410. $this->processResponseBody($request, $response);
  411. if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
  412. $response->setPrivate();
  413. } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
  414. $response->setTtl($this->options['default_ttl']);
  415. }
  416. return $response;
  417. }
  418. /**
  419. * Checks whether the cache entry is "fresh enough" to satisfy the Request.
  420. *
  421. * @param Request $request A Request instance
  422. * @param Response $entry A Response instance
  423. *
  424. * @return bool true if the cache entry if fresh enough, false otherwise
  425. */
  426. protected function isFreshEnough(Request $request, Response $entry)
  427. {
  428. if (!$entry->isFresh()) {
  429. return $this->lock($request, $entry);
  430. }
  431. if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
  432. return $maxAge > 0 && $maxAge >= $entry->getAge();
  433. }
  434. return true;
  435. }
  436. /**
  437. * Locks a Request during the call to the backend.
  438. *
  439. * @param Request $request A Request instance
  440. * @param Response $entry A Response instance
  441. *
  442. * @return bool true if the cache entry can be returned even if it is staled, false otherwise
  443. */
  444. protected function lock(Request $request, Response $entry)
  445. {
  446. // try to acquire a lock to call the backend
  447. $lock = $this->store->lock($request);
  448. // there is already another process calling the backend
  449. if (true !== $lock) {
  450. // check if we can serve the stale entry
  451. if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) {
  452. $age = $this->options['stale_while_revalidate'];
  453. }
  454. if (abs($entry->getTtl()) < $age) {
  455. $this->record($request, 'stale-while-revalidate');
  456. // server the stale response while there is a revalidation
  457. return true;
  458. }
  459. // wait for the lock to be released
  460. $wait = 0;
  461. while ($this->store->isLocked($request) && $wait < 5000000) {
  462. usleep(50000);
  463. $wait += 50000;
  464. }
  465. if ($wait < 5000000) {
  466. // replace the current entry with the fresh one
  467. $new = $this->lookup($request);
  468. $entry->headers = $new->headers;
  469. $entry->setContent($new->getContent());
  470. $entry->setStatusCode($new->getStatusCode());
  471. $entry->setProtocolVersion($new->getProtocolVersion());
  472. foreach ($new->headers->getCookies() as $cookie) {
  473. $entry->headers->setCookie($cookie);
  474. }
  475. } else {
  476. // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
  477. $entry->setStatusCode(503);
  478. $entry->setContent('503 Service Unavailable');
  479. $entry->headers->set('Retry-After', 10);
  480. }
  481. return true;
  482. }
  483. // we have the lock, call the backend
  484. return false;
  485. }
  486. /**
  487. * Writes the Response to the cache.
  488. *
  489. * @param Request $request A Request instance
  490. * @param Response $response A Response instance
  491. *
  492. * @throws \Exception
  493. */
  494. protected function store(Request $request, Response $response)
  495. {
  496. if (!$response->headers->has('Date')) {
  497. $response->setDate(\DateTime::createFromFormat('U', time()));
  498. }
  499. try {
  500. $this->store->write($request, $response);
  501. $this->record($request, 'store');
  502. $response->headers->set('Age', $response->getAge());
  503. } catch (\Exception $e) {
  504. $this->record($request, 'store-failed');
  505. if ($this->options['debug']) {
  506. throw $e;
  507. }
  508. }
  509. // now that the response is cached, release the lock
  510. $this->store->unlock($request);
  511. }
  512. /**
  513. * Restores the Response body.
  514. *
  515. * @param Request $request A Request instance
  516. * @param Response $response A Response instance
  517. */
  518. private function restoreResponseBody(Request $request, Response $response)
  519. {
  520. if ($request->isMethod('HEAD') || 304 === $response->getStatusCode()) {
  521. $response->setContent(null);
  522. $response->headers->remove('X-Body-Eval');
  523. $response->headers->remove('X-Body-File');
  524. return;
  525. }
  526. if ($response->headers->has('X-Body-Eval')) {
  527. ob_start();
  528. if ($response->headers->has('X-Body-File')) {
  529. include $response->headers->get('X-Body-File');
  530. } else {
  531. eval('; ?>'.$response->getContent().'<?php ;');
  532. }
  533. $response->setContent(ob_get_clean());
  534. $response->headers->remove('X-Body-Eval');
  535. if (!$response->headers->has('Transfer-Encoding')) {
  536. $response->headers->set('Content-Length', strlen($response->getContent()));
  537. }
  538. } elseif ($response->headers->has('X-Body-File')) {
  539. $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
  540. } else {
  541. return;
  542. }
  543. $response->headers->remove('X-Body-File');
  544. }
  545. protected function processResponseBody(Request $request, Response $response)
  546. {
  547. if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) {
  548. $this->surrogate->process($request, $response);
  549. }
  550. }
  551. /**
  552. * Checks if the Request includes authorization or other sensitive information
  553. * that should cause the Response to be considered private by default.
  554. *
  555. * @param Request $request A Request instance
  556. *
  557. * @return bool true if the Request is private, false otherwise
  558. */
  559. private function isPrivateRequest(Request $request)
  560. {
  561. foreach ($this->options['private_headers'] as $key) {
  562. $key = strtolower(str_replace('HTTP_', '', $key));
  563. if ('cookie' === $key) {
  564. if (count($request->cookies->all())) {
  565. return true;
  566. }
  567. } elseif ($request->headers->has($key)) {
  568. return true;
  569. }
  570. }
  571. return false;
  572. }
  573. /**
  574. * Records that an event took place.
  575. *
  576. * @param Request $request A Request instance
  577. * @param string $event The event name
  578. */
  579. private function record(Request $request, $event)
  580. {
  581. $path = $request->getPathInfo();
  582. if ($qs = $request->getQueryString()) {
  583. $path .= '?'.$qs;
  584. }
  585. $this->traces[$request->getMethod().' '.$path][] = $event;
  586. }
  587. }