HttpCache.php 23KB

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