Augmentation vers version 3.3.0

This commit is contained in:
Gauvain Boiché
2020-03-31 15:31:03 +02:00
parent d926806907
commit a1864c0414
2618 changed files with 406015 additions and 31377 deletions

View File

@@ -0,0 +1,136 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\HttpCache;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Abstract class implementing Surrogate capabilities to Request and Response instances.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Robin Chalas <robin.chalas@gmail.com>
*/
abstract class AbstractSurrogate implements SurrogateInterface
{
protected $contentTypes;
protected $phpEscapeMap = [
['<?', '<%', '<s', '<S'],
['<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'],
];
/**
* @param array $contentTypes An array of content-type that should be parsed for Surrogate information
* (default: text/html, text/xml, application/xhtml+xml, and application/xml)
*/
public function __construct(array $contentTypes = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'])
{
$this->contentTypes = $contentTypes;
}
/**
* Returns a new cache strategy instance.
*
* @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
*/
public function createCacheStrategy()
{
return new ResponseCacheStrategy();
}
/**
* {@inheritdoc}
*/
public function hasSurrogateCapability(Request $request)
{
if (null === $value = $request->headers->get('Surrogate-Capability')) {
return false;
}
return false !== strpos($value, sprintf('%s/1.0', strtoupper($this->getName())));
}
/**
* {@inheritdoc}
*/
public function addSurrogateCapability(Request $request)
{
$current = $request->headers->get('Surrogate-Capability');
$new = sprintf('symfony="%s/1.0"', strtoupper($this->getName()));
$request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
}
/**
* {@inheritdoc}
*/
public function needsParsing(Response $response)
{
if (!$control = $response->headers->get('Surrogate-Control')) {
return false;
}
$pattern = sprintf('#content="[^"]*%s/1.0[^"]*"#', strtoupper($this->getName()));
return (bool) preg_match($pattern, $control);
}
/**
* {@inheritdoc}
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
{
$subRequest = Request::create($uri, Request::METHOD_GET, [], $cache->getRequest()->cookies->all(), [], $cache->getRequest()->server->all());
try {
$response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
if (!$response->isSuccessful()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
}
return $response->getContent();
} catch (\Exception $e) {
if ($alt) {
return $this->handle($cache, $alt, '', $ignoreErrors);
}
if (!$ignoreErrors) {
throw $e;
}
}
return '';
}
/**
* Remove the Surrogate from the Surrogate-Control header.
*/
protected function removeFromControl(Response $response)
{
if (!$response->headers->has('Surrogate-Control')) {
return;
}
$value = $response->headers->get('Surrogate-Control');
$upperName = strtoupper($this->getName());
if (sprintf('content="%s/1.0"', $upperName) == $value) {
$response->headers->remove('Surrogate-Control');
} elseif (preg_match(sprintf('#,\s*content="%s/1.0"#', $upperName), $value)) {
$response->headers->set('Surrogate-Control', preg_replace(sprintf('#,\s*content="%s/1.0"#', $upperName), '', $value));
} elseif (preg_match(sprintf('#content="%s/1.0",\s*#', $upperName), $value)) {
$response->headers->set('Surrogate-Control', preg_replace(sprintf('#content="%s/1.0",\s*#', $upperName), '', $value));
}
}
}

View File

@@ -13,7 +13,6 @@ namespace Symfony\Component\HttpKernel\HttpCache;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Esi implements the ESI capabilities to Request and Response instances.
@@ -26,97 +25,15 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Esi implements SurrogateInterface
class Esi extends AbstractSurrogate
{
private $contentTypes;
private $phpEscapeMap = array(
array('<?', '<%', '<s', '<S'),
array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
);
/**
* @param array $contentTypes An array of content-type that should be parsed for ESI information
* (default: text/html, text/xml, application/xhtml+xml, and application/xml)
*/
public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
{
$this->contentTypes = $contentTypes;
}
public function getName()
{
return 'esi';
}
/**
* Returns a new cache strategy instance.
*
* @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
*/
public function createCacheStrategy()
{
return new ResponseCacheStrategy();
}
/**
* Checks that at least one surrogate has ESI/1.0 capability.
*
* @return bool true if one surrogate has ESI/1.0 capability, false otherwise
*/
public function hasSurrogateCapability(Request $request)
{
if (null === $value = $request->headers->get('Surrogate-Capability')) {
return false;
}
return false !== strpos($value, 'ESI/1.0');
}
/**
* Checks that at least one surrogate has ESI/1.0 capability.
*
* @param Request $request A Request instance
*
* @return bool true if one surrogate has ESI/1.0 capability, false otherwise
*
* @deprecated since version 2.6, to be removed in 3.0. Use hasSurrogateCapability() instead
*/
public function hasSurrogateEsiCapability(Request $request)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the hasSurrogateCapability() method instead.', E_USER_DEPRECATED);
return $this->hasSurrogateCapability($request);
}
/**
* Adds ESI/1.0 capability to the given Request.
*/
public function addSurrogateCapability(Request $request)
{
$current = $request->headers->get('Surrogate-Capability');
$new = 'symfony2="ESI/1.0"';
$request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
}
/**
* Adds ESI/1.0 capability to the given Request.
*
* @param Request $request A Request instance
*
* @deprecated since version 2.6, to be removed in 3.0. Use addSurrogateCapability() instead
*/
public function addSurrogateEsiCapability(Request $request)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the addSurrogateCapability() method instead.', E_USER_DEPRECATED);
$this->addSurrogateCapability($request);
}
/**
* Adds HTTP headers to specify that the Response needs to be parsed for ESI.
*
* This method only adds an ESI HTTP header if the Response has some ESI tags.
* {@inheritdoc}
*/
public function addSurrogateControl(Response $response)
{
@@ -126,44 +43,7 @@ class Esi implements SurrogateInterface
}
/**
* Checks that the Response needs to be parsed for ESI tags.
*
* @return bool true if the Response needs to be parsed, false otherwise
*/
public function needsParsing(Response $response)
{
if (!$control = $response->headers->get('Surrogate-Control')) {
return false;
}
return (bool) preg_match('#content="[^"]*ESI/1.0[^"]*"#', $control);
}
/**
* Checks that the Response needs to be parsed for ESI tags.
*
* @param Response $response A Response instance
*
* @return bool true if the Response needs to be parsed, false otherwise
*
* @deprecated since version 2.6, to be removed in 3.0. Use needsParsing() instead
*/
public function needsEsiParsing(Response $response)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the needsParsing() method instead.', E_USER_DEPRECATED);
return $this->needsParsing($response);
}
/**
* Renders an ESI tag.
*
* @param string $uri A URI
* @param string $alt An alternate URI
* @param bool $ignoreErrors Whether to ignore errors or not
* @param string $comment A comment to add as an esi:include tag
*
* @return string
* {@inheritdoc}
*/
public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
{
@@ -181,9 +61,7 @@ class Esi implements SurrogateInterface
}
/**
* Replaces a Response ESI tags with the included resource content.
*
* @return Response
* {@inheritdoc}
*/
public function process(Request $request, Response $response)
{
@@ -207,7 +85,7 @@ class Esi implements SurrogateInterface
$i = 1;
while (isset($chunks[$i])) {
$options = array();
$options = [];
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
@@ -232,51 +110,8 @@ class Esi implements SurrogateInterface
$response->headers->set('X-Body-Eval', 'ESI');
// remove ESI/1.0 from the Surrogate-Control header
if ($response->headers->has('Surrogate-Control')) {
$value = $response->headers->get('Surrogate-Control');
if ('content="ESI/1.0"' == $value) {
$response->headers->remove('Surrogate-Control');
} elseif (preg_match('#,\s*content="ESI/1.0"#', $value)) {
$response->headers->set('Surrogate-Control', preg_replace('#,\s*content="ESI/1.0"#', '', $value));
} elseif (preg_match('#content="ESI/1.0",\s*#', $value)) {
$response->headers->set('Surrogate-Control', preg_replace('#content="ESI/1.0",\s*#', '', $value));
}
}
}
$this->removeFromControl($response);
/**
* Handles an ESI from the cache.
*
* @param HttpCache $cache An HttpCache instance
* @param string $uri The main URI
* @param string $alt An alternative URI
* @param bool $ignoreErrors Whether to ignore errors or not
*
* @return string
*
* @throws \RuntimeException
* @throws \Exception
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
{
$subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
try {
$response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
if (!$response->isSuccessful()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
}
return $response->getContent();
} catch (\Exception $e) {
if ($alt) {
return $this->handle($cache, $alt, '', $ignoreErrors);
}
if (!$ignoreErrors) {
throw $e;
}
}
return $response;
}
}

View File

@@ -32,8 +32,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
private $request;
private $surrogate;
private $surrogateCacheStrategy;
private $options = array();
private $traces = array();
private $options = [];
private $traces = [];
/**
* Constructor.
@@ -70,24 +70,24 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* This setting is overridden by the stale-if-error HTTP Cache-Control extension
* (see RFC 5861).
*/
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = [])
{
$this->store = $store;
$this->kernel = $kernel;
$this->surrogate = $surrogate;
// needed in case there is a fatal error because the backend is too slow to respond
register_shutdown_function(array($this->store, 'cleanup'));
register_shutdown_function([$this->store, 'cleanup']);
$this->options = array_merge(array(
$this->options = array_merge([
'debug' => false,
'default_ttl' => 0,
'private_headers' => array('Authorization', 'Cookie'),
'private_headers' => ['Authorization', 'Cookie'],
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
), $options);
], $options);
}
/**
@@ -117,7 +117,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
*/
public function getLog()
{
$log = array();
$log = [];
foreach ($this->traces as $request => $traces) {
$log[] = sprintf('%s: %s', $request, implode(', ', $traces));
}
@@ -154,29 +154,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
*/
public function getSurrogate()
{
if (!$this->surrogate instanceof Esi) {
throw new \LogicException('This instance of HttpCache was not set up to use ESI as surrogate handler. You must overwrite and use createSurrogate');
}
return $this->surrogate;
}
/**
* Gets the Esi instance.
*
* @return Esi An Esi instance
*
* @throws \LogicException
*
* @deprecated since version 2.6, to be removed in 3.0. Use getSurrogate() instead
*/
public function getEsi()
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the getSurrogate() method instead.', E_USER_DEPRECATED);
return $this->getSurrogate();
}
/**
* {@inheritdoc}
*/
@@ -184,7 +164,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
{
// FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->traces = array();
$this->traces = [];
// Keep a clone of the original request for surrogates so they can access it.
// We must clone here to get a separate instance because the application will modify the request during
// the application flow (we know it always does because we do ourselves by setting REMOTE_ADDR to 127.0.0.1
@@ -195,24 +175,25 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
}
$path = $request->getPathInfo();
if ($qs = $request->getQueryString()) {
$path .= '?'.$qs;
}
$this->traces[$request->getMethod().' '.$path] = array();
$this->traces[$this->getTraceKey($request)] = [];
if (!$request->isMethodSafe(false)) {
$response = $this->invalidate($request, $catch);
} elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
$response = $this->pass($request, $catch);
} elseif ($this->options['allow_reload'] && $request->isNoCache()) {
/*
If allow_reload is configured and the client requests "Cache-Control: no-cache",
reload the cache by fetching a fresh response and caching it (if possible).
*/
$this->record($request, 'reload');
$response = $this->fetch($request, $catch);
} else {
$response = $this->lookup($request, $catch);
}
$this->restoreResponseBody($request, $response);
$response->setDate(\DateTime::createFromFormat('U', time(), new \DateTimeZone('UTC')));
if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
$response->headers->set('X-Symfony-Cache', $this->getLog());
}
@@ -279,9 +260,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$this->store->invalidate($request);
// As per the RFC, invalidate Location and Content-Location URLs if present
foreach (array('Location', 'Content-Location') as $header) {
foreach (['Location', 'Content-Location'] as $header) {
if ($uri = $response->headers->get($header)) {
$subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
$subRequest = Request::create($uri, 'get', [], [], [], $request->server->all());
$this->store->invalidate($subRequest);
}
@@ -318,13 +299,6 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
*/
protected function lookup(Request $request, $catch = false)
{
// if allow_reload and no-cache Cache-Control, allow a cache reload
if ($this->options['allow_reload'] && $request->isNoCache()) {
$this->record($request, 'reload');
return $this->fetch($request, $catch);
}
try {
$entry = $this->store->lookup($request);
} catch (\Exception $e) {
@@ -378,12 +352,14 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
// add our cached last-modified validator
$subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
if ($entry->headers->has('Last-Modified')) {
$subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
}
// Add our cached etag validator to the environment.
// We keep the etags from the client to handle the case when the client
// has a different private valid entry which is not cached here.
$cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
$cachedEtags = $entry->getEtag() ? [$entry->getEtag()] : [];
$requestEtags = $request->getETags();
if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
$subRequest->headers->set('if_none_match', implode(', ', $etags));
@@ -403,7 +379,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$entry = clone $entry;
$entry->headers->remove('Date');
foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
foreach (['Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'] as $name) {
if ($response->headers->has($name)) {
$entry->headers->set($name, $response->headers->get($name));
}
@@ -422,9 +398,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
/**
* Forwards the Request to the backend and determines whether the response should be stored.
*
* This methods is triggered when the cache missed or a reload is required.
* Unconditionally fetches a fresh response from the backend and
* stores it in the cache if is cacheable.
*
* @param Request $request A Request instance
* @param bool $catch Whether to process exceptions
@@ -456,9 +431,11 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Forwards the Request to the backend and returns the Response.
*
* @param Request $request A Request instance
* @param bool $catch Whether to catch exceptions or not
* @param Response $entry A Response instance (the stale entry if present, null otherwise)
* All backend requests (cache passes, fetches, cache validations)
* run through this method.
*
* @param bool $catch Whether to catch exceptions or not
* @param Response|null $entry A Response instance (the stale entry if present, null otherwise)
*
* @return Response A Response instance
*/
@@ -472,7 +449,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $catch);
// we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
if (null !== $entry && \in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
if (null !== $entry && \in_array($response->getStatusCode(), [500, 502, 503, 504])) {
if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
$age = $this->options['stale_if_error'];
}
@@ -484,6 +461,17 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
}
/*
RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate
clock MUST NOT send a "Date" header, although it MUST send one in most other cases
except for 1xx or 5xx responses where it MAY do so.
Anyway, a client that received a message without a "Date" header MUST add it.
*/
if (!$response->headers->has('Date')) {
$response->setDate(\DateTime::createFromFormat('U', time()));
}
$this->processResponseBody($request, $response);
if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
@@ -523,49 +511,39 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
// try to acquire a lock to call the backend
$lock = $this->store->lock($request);
if (true === $lock) {
// we have the lock, call the backend
return false;
}
// there is already another process calling the backend
if (true !== $lock) {
// check if we can serve the stale entry
if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) {
$age = $this->options['stale_while_revalidate'];
}
if (abs($entry->getTtl()) < $age) {
$this->record($request, 'stale-while-revalidate');
// server the stale response while there is a revalidation
return true;
}
// wait for the lock to be released
$wait = 0;
while ($this->store->isLocked($request) && $wait < 5000000) {
usleep(50000);
$wait += 50000;
}
if ($wait < 5000000) {
// replace the current entry with the fresh one
$new = $this->lookup($request);
$entry->headers = $new->headers;
$entry->setContent($new->getContent());
$entry->setStatusCode($new->getStatusCode());
$entry->setProtocolVersion($new->getProtocolVersion());
foreach ($new->headers->getCookies() as $cookie) {
$entry->headers->setCookie($cookie);
}
} else {
// backend is slow as hell, send a 503 response (to avoid the dog pile effect)
$entry->setStatusCode(503);
$entry->setContent('503 Service Unavailable');
$entry->headers->set('Retry-After', 10);
}
// May we serve a stale response?
if ($this->mayServeStaleWhileRevalidate($entry)) {
$this->record($request, 'stale-while-revalidate');
return true;
}
// we have the lock, call the backend
return false;
// wait for the lock to be released
if ($this->waitForLock($request)) {
// replace the current entry with the fresh one
$new = $this->lookup($request);
$entry->headers = $new->headers;
$entry->setContent($new->getContent());
$entry->setStatusCode($new->getStatusCode());
$entry->setProtocolVersion($new->getProtocolVersion());
foreach ($new->headers->getCookies() as $cookie) {
$entry->headers->setCookie($cookie);
}
} else {
// backend is slow as hell, send a 503 response (to avoid the dog pile effect)
$entry->setStatusCode(503);
$entry->setContent('503 Service Unavailable');
$entry->headers->set('Retry-After', 10);
}
return true;
}
/**
@@ -575,9 +553,6 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
*/
protected function store(Request $request, Response $response)
{
if (!$response->headers->has('Date')) {
$response->setDate(\DateTime::createFromFormat('U', time()));
}
try {
$this->store->write($request, $response);
@@ -665,11 +640,57 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* @param string $event The event name
*/
private function record(Request $request, $event)
{
$this->traces[$this->getTraceKey($request)][] = $event;
}
/**
* Calculates the key we use in the "trace" array for a given request.
*
* @return string
*/
private function getTraceKey(Request $request)
{
$path = $request->getPathInfo();
if ($qs = $request->getQueryString()) {
$path .= '?'.$qs;
}
$this->traces[$request->getMethod().' '.$path][] = $event;
return $request->getMethod().' '.$path;
}
/**
* Checks whether the given (cached) response may be served as "stale" when a revalidation
* is currently in progress.
*
* @return bool true when the stale response may be served, false otherwise
*/
private function mayServeStaleWhileRevalidate(Response $entry)
{
$timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate');
if (null === $timeout) {
$timeout = $this->options['stale_while_revalidate'];
}
return abs($entry->getTtl()) < $timeout;
}
/**
* Waits for the store to release a locked entry.
*
* @param Request $request The request to wait for
*
* @return bool true if the lock was released before the internal timeout was hit; false if the wait timeout was exceeded
*/
private function waitForLock(Request $request)
{
$wait = 0;
while ($this->store->isLocked($request) && $wait < 100) {
usleep(50000);
++$wait;
}
return $wait < 100;
}
}

View File

@@ -5,10 +5,6 @@
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This code is partially based on the Rack-Cache library by Ryan Tomayko,
* which is released under the MIT license.
* (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@@ -28,30 +24,69 @@ use Symfony\Component\HttpFoundation\Response;
*/
class ResponseCacheStrategy implements ResponseCacheStrategyInterface
{
private $cacheable = true;
/**
* Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
*/
private static $overrideDirectives = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate'];
/**
* Cache-Control headers that are sent to the final response if they appear in ALL of the responses.
*/
private static $inheritDirectives = ['public', 'immutable'];
private $embeddedResponses = 0;
private $ttls = array();
private $maxAges = array();
private $isNotCacheableResponseEmbedded = false;
private $age = 0;
private $flagDirectives = [
'no-cache' => null,
'no-store' => null,
'no-transform' => null,
'must-revalidate' => null,
'proxy-revalidate' => null,
'public' => null,
'private' => null,
'immutable' => null,
];
private $ageDirectives = [
'max-age' => null,
's-maxage' => null,
'expires' => null,
];
/**
* {@inheritdoc}
*/
public function add(Response $response)
{
if (!$response->isFresh() || !$response->isCacheable()) {
$this->cacheable = false;
} else {
$maxAge = $response->getMaxAge();
$this->ttls[] = $response->getTtl();
$this->maxAges[] = $maxAge;
++$this->embeddedResponses;
if (null === $maxAge) {
$this->isNotCacheableResponseEmbedded = true;
foreach (self::$overrideDirectives as $directive) {
if ($response->headers->hasCacheControlDirective($directive)) {
$this->flagDirectives[$directive] = true;
}
}
++$this->embeddedResponses;
foreach (self::$inheritDirectives as $directive) {
if (false !== $this->flagDirectives[$directive]) {
$this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
}
}
$age = $response->getAge();
$this->age = max($this->age, $age);
if ($this->willMakeFinalResponseUncacheable($response)) {
$this->isNotCacheableResponseEmbedded = true;
return;
}
$this->storeRelativeAgeDirective('max-age', $response->headers->getCacheControlDirective('max-age'), $age);
$this->storeRelativeAgeDirective('s-maxage', $response->headers->getCacheControlDirective('s-maxage') ?: $response->headers->getCacheControlDirective('max-age'), $age);
$expires = $response->getExpires();
$expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0);
}
/**
@@ -64,33 +99,123 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
return;
}
// Remove validation related headers in order to avoid browsers using
// their own cache, because some of the response content comes from
// at least one embedded response (which likely has a different caching strategy).
if ($response->isValidateable()) {
$response->setEtag(null);
$response->setLastModified(null);
}
// Remove validation related headers of the master response,
// because some of the response content comes from at least
// one embedded response (which likely has a different caching strategy).
$response->setEtag(null);
$response->setLastModified(null);
if (!$response->isFresh() || !$response->isCacheable()) {
$this->cacheable = false;
}
$this->add($response);
if (!$this->cacheable) {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
$response->headers->set('Age', $this->age);
if ($this->isNotCacheableResponseEmbedded) {
$response->setExpires($response->getDate());
if ($this->flagDirectives['no-store']) {
$response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
} else {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
}
return;
}
$this->ttls[] = $response->getTtl();
$this->maxAges[] = $response->getMaxAge();
$flags = array_filter($this->flagDirectives);
if ($this->isNotCacheableResponseEmbedded) {
$response->headers->removeCacheControlDirective('s-maxage');
} elseif (null !== $maxAge = min($this->maxAges)) {
$response->setSharedMaxAge($maxAge);
$response->headers->set('Age', $maxAge - min($this->ttls));
if (isset($flags['must-revalidate'])) {
$flags['no-cache'] = true;
}
$response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
$maxAge = null;
if (is_numeric($this->ageDirectives['max-age'])) {
$maxAge = $this->ageDirectives['max-age'] + $this->age;
$response->headers->addCacheControlDirective('max-age', $maxAge);
}
if (is_numeric($this->ageDirectives['s-maxage'])) {
$sMaxage = $this->ageDirectives['s-maxage'] + $this->age;
if ($maxAge !== $sMaxage) {
$response->headers->addCacheControlDirective('s-maxage', $sMaxage);
}
}
if (is_numeric($this->ageDirectives['expires'])) {
$date = clone $response->getDate();
$date->modify('+'.($this->ageDirectives['expires'] + $this->age).' seconds');
$response->setExpires($date);
}
}
/**
* RFC2616, Section 13.4.
*
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
*
* @return bool
*/
private function willMakeFinalResponseUncacheable(Response $response)
{
// RFC2616: A response received with a status code of 200, 203, 300, 301 or 410
// MAY be stored by a cache […] unless a cache-control directive prohibits caching.
if ($response->headers->hasCacheControlDirective('no-cache')
|| $response->headers->getCacheControlDirective('no-store')
) {
return true;
}
// Last-Modified and Etag headers cannot be merged, they render the response uncacheable
// by default (except if the response also has max-age etc.).
if (\in_array($response->getStatusCode(), [200, 203, 300, 301, 410])
&& null === $response->getLastModified()
&& null === $response->getEtag()
) {
return false;
}
// RFC2616: A response received with any other status code (e.g. status codes 302 and 307)
// MUST NOT be returned in a reply to a subsequent request unless there are
// cache-control directives or another header(s) that explicitly allow it.
$cacheControl = ['max-age', 's-maxage', 'must-revalidate', 'proxy-revalidate', 'public', 'private'];
foreach ($cacheControl as $key) {
if ($response->headers->hasCacheControlDirective($key)) {
return false;
}
}
if ($response->headers->has('Expires')) {
return false;
}
return true;
}
/**
* Store lowest max-age/s-maxage/expires for the final response.
*
* The response might have been stored in cache a while ago. To keep things comparable,
* we have to subtract the age so that the value is normalized for an age of 0.
*
* If the value is lower than the currently stored value, we update the value, to keep a rolling
* minimal value of each instruction. If the value is NULL, the directive will not be set on the final response.
*
* @param string $directive
* @param int|null $value
* @param int $age
*/
private function storeRelativeAgeDirective($directive, $value, $age)
{
if (null === $value) {
$this->ageDirectives[$directive] = false;
}
if (false !== $this->ageDirectives[$directive]) {
$value -= $age;
$this->ageDirectives[$directive] = null !== $this->ageDirectives[$directive] ? min($this->ageDirectives[$directive], $value) : $value;
}
$response->setMaxAge(0);
}
}

View File

@@ -13,30 +13,14 @@ namespace Symfony\Component\HttpKernel\HttpCache;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Ssi implements the SSI capabilities to Request and Response instances.
*
* @author Sebastian Krebs <krebs.seb@gmail.com>
*/
class Ssi implements SurrogateInterface
class Ssi extends AbstractSurrogate
{
private $contentTypes;
private $phpEscapeMap = array(
array('<?', '<%', '<s', '<S'),
array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
);
/**
* @param array $contentTypes An array of content-type that should be parsed for SSI information
* (default: text/html, text/xml, application/xhtml+xml, and application/xml)
*/
public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
{
$this->contentTypes = $contentTypes;
}
/**
* {@inheritdoc}
*/
@@ -45,37 +29,6 @@ class Ssi implements SurrogateInterface
return 'ssi';
}
/**
* {@inheritdoc}
*/
public function createCacheStrategy()
{
return new ResponseCacheStrategy();
}
/**
* {@inheritdoc}
*/
public function hasSurrogateCapability(Request $request)
{
if (null === $value = $request->headers->get('Surrogate-Capability')) {
return false;
}
return false !== strpos($value, 'SSI/1.0');
}
/**
* {@inheritdoc}
*/
public function addSurrogateCapability(Request $request)
{
$current = $request->headers->get('Surrogate-Capability');
$new = 'symfony2="SSI/1.0"';
$request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
}
/**
* {@inheritdoc}
*/
@@ -86,18 +39,6 @@ class Ssi implements SurrogateInterface
}
}
/**
* {@inheritdoc}
*/
public function needsParsing(Response $response)
{
if (!$control = $response->headers->get('Surrogate-Control')) {
return false;
}
return (bool) preg_match('#content="[^"]*SSI/1.0[^"]*"#', $control);
}
/**
* {@inheritdoc}
*/
@@ -129,7 +70,7 @@ class Ssi implements SurrogateInterface
$i = 1;
while (isset($chunks[$i])) {
$options = array();
$options = [];
preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
@@ -152,41 +93,8 @@ class Ssi implements SurrogateInterface
$response->headers->set('X-Body-Eval', 'SSI');
// remove SSI/1.0 from the Surrogate-Control header
if ($response->headers->has('Surrogate-Control')) {
$value = $response->headers->get('Surrogate-Control');
if ('content="SSI/1.0"' == $value) {
$response->headers->remove('Surrogate-Control');
} elseif (preg_match('#,\s*content="SSI/1.0"#', $value)) {
$response->headers->set('Surrogate-Control', preg_replace('#,\s*content="SSI/1.0"#', '', $value));
} elseif (preg_match('#content="SSI/1.0",\s*#', $value)) {
$response->headers->set('Surrogate-Control', preg_replace('#content="SSI/1.0",\s*#', '', $value));
}
}
}
$this->removeFromControl($response);
/**
* {@inheritdoc}
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
{
$subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
try {
$response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
if (!$response->isSuccessful()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
}
return $response->getContent();
} catch (\Exception $e) {
if ($alt) {
return $this->handle($cache, $alt, '', $ignoreErrors);
}
if (!$ignoreErrors) {
throw $e;
}
}
return $response;
}
}

View File

@@ -40,7 +40,7 @@ class Store implements StoreInterface
throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
}
$this->keyCache = new \SplObjectStorage();
$this->locks = array();
$this->locks = [];
}
/**
@@ -54,7 +54,7 @@ class Store implements StoreInterface
fclose($lock);
}
$this->locks = array();
$this->locks = [];
}
/**
@@ -134,7 +134,7 @@ class Store implements StoreInterface
$key = $this->getCacheKey($request);
if (!$entries = $this->getMetadata($key)) {
return;
return null;
}
// find a cached entry that matches the request.
@@ -148,7 +148,7 @@ class Store implements StoreInterface
}
if (null === $match) {
return;
return null;
}
$headers = $match[1];
@@ -159,6 +159,7 @@ class Store implements StoreInterface
// TODO the metaStore referenced an entity that doesn't exist in
// the entityStore. We definitely want to return nil but we should
// also purge the entry from the meta-store when this is detected.
return null;
}
/**
@@ -180,7 +181,7 @@ class Store implements StoreInterface
if (!$response->headers->has('X-Content-Digest')) {
$digest = $this->generateContentDigest($response);
if (false === $this->save($digest, $response->getContent())) {
if (!$this->save($digest, $response->getContent())) {
throw new \RuntimeException('Unable to store the entity.');
}
@@ -192,11 +193,11 @@ class Store implements StoreInterface
}
// read existing cache entries, remove non-varying, and add this one to the list
$entries = array();
$entries = [];
$vary = $response->headers->get('vary');
foreach ($this->getMetadata($key) as $entry) {
if (!isset($entry[1]['vary'][0])) {
$entry[1]['vary'] = array('');
$entry[1]['vary'] = [''];
}
if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
@@ -207,9 +208,9 @@ class Store implements StoreInterface
$headers = $this->persistResponse($response);
unset($headers['age']);
array_unshift($entries, array($storedEnv, $headers));
array_unshift($entries, [$storedEnv, $headers]);
if (false === $this->save($key, serialize($entries))) {
if (!$this->save($key, serialize($entries))) {
throw new \RuntimeException('Unable to store the metadata.');
}
@@ -236,19 +237,19 @@ class Store implements StoreInterface
$modified = false;
$key = $this->getCacheKey($request);
$entries = array();
$entries = [];
foreach ($this->getMetadata($key) as $entry) {
$response = $this->restoreResponse($entry[1]);
if ($response->isFresh()) {
$response->expire();
$modified = true;
$entries[] = array($entry[0], $this->persistResponse($response));
$entries[] = [$entry[0], $this->persistResponse($response)];
} else {
$entries[] = $entry;
}
}
if ($modified && false === $this->save($key, serialize($entries))) {
if ($modified && !$this->save($key, serialize($entries))) {
throw new \RuntimeException('Unable to store the metadata.');
}
}
@@ -293,7 +294,7 @@ class Store implements StoreInterface
private function getMetadata($key)
{
if (!$entries = $this->load($key)) {
return array();
return [];
}
return unserialize($entries);
@@ -349,13 +350,13 @@ class Store implements StoreInterface
*
* @param string $key The store key
*
* @return string The data associated with the key
* @return string|null The data associated with the key
*/
private function load($key)
{
$path = $this->getPath($key);
return file_exists($path) ? file_get_contents($path) : false;
return file_exists($path) && false !== ($contents = file_get_contents($path)) ? $contents : null;
}
/**
@@ -408,6 +409,8 @@ class Store implements StoreInterface
}
@chmod($path, 0666 & ~umask());
return true;
}
public function getPath($key)
@@ -464,7 +467,7 @@ class Store implements StoreInterface
private function persistResponse(Response $response)
{
$headers = $response->headers->all();
$headers['X-Status'] = array($response->getStatusCode());
$headers['X-Status'] = [$response->getStatusCode()];
return $headers;
}
@@ -483,7 +486,7 @@ class Store implements StoreInterface
unset($headers['X-Status']);
if (null !== $body) {
$headers['X-Body-File'] = array($body);
$headers['X-Body-File'] = [$body];
}
return new Response($body, $status, $headers);

View File

@@ -30,26 +30,41 @@ class SubRequestHandler
{
// save global state related to trusted headers and proxies
$trustedProxies = Request::getTrustedProxies();
$trustedHeaders = array(
Request::HEADER_FORWARDED => Request::getTrustedHeaderName(Request::HEADER_FORWARDED),
Request::HEADER_CLIENT_IP => Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP),
Request::HEADER_CLIENT_HOST => Request::getTrustedHeaderName(Request::HEADER_CLIENT_HOST),
Request::HEADER_CLIENT_PROTO => Request::getTrustedHeaderName(Request::HEADER_CLIENT_PROTO),
Request::HEADER_CLIENT_PORT => Request::getTrustedHeaderName(Request::HEADER_CLIENT_PORT),
);
$trustedHeaderSet = Request::getTrustedHeaderSet();
if (method_exists(Request::class, 'getTrustedHeaderName')) {
Request::setTrustedProxies($trustedProxies, -1);
$trustedHeaders = [
Request::HEADER_FORWARDED => Request::getTrustedHeaderName(Request::HEADER_FORWARDED, false),
Request::HEADER_X_FORWARDED_FOR => Request::getTrustedHeaderName(Request::HEADER_X_FORWARDED_FOR, false),
Request::HEADER_X_FORWARDED_HOST => Request::getTrustedHeaderName(Request::HEADER_X_FORWARDED_HOST, false),
Request::HEADER_X_FORWARDED_PROTO => Request::getTrustedHeaderName(Request::HEADER_X_FORWARDED_PROTO, false),
Request::HEADER_X_FORWARDED_PORT => Request::getTrustedHeaderName(Request::HEADER_X_FORWARDED_PORT, false),
];
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet);
} else {
$trustedHeaders = [
Request::HEADER_FORWARDED => 'FORWARDED',
Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
];
}
// remove untrusted values
$remoteAddr = $request->server->get('REMOTE_ADDR');
if (!IpUtils::checkIp($remoteAddr, $trustedProxies)) {
foreach (array_filter($trustedHeaders) as $name) {
$request->headers->remove($name);
$request->server->remove('HTTP_'.strtoupper(str_replace('-', '_', $name)));
foreach ($trustedHeaders as $key => $name) {
if ($trustedHeaderSet & $key) {
$request->headers->remove($name);
$request->server->remove('HTTP_'.strtoupper(str_replace('-', '_', $name)));
}
}
}
// compute trusted values, taking any trusted proxies into account
$trustedIps = array();
$trustedValues = array();
$trustedIps = [];
$trustedValues = [];
foreach (array_reverse($request->getClientIps()) as $ip) {
$trustedIps[] = $ip;
$trustedValues[] = sprintf('for="%s"', $ip);
@@ -60,19 +75,18 @@ class SubRequestHandler
}
// set trusted values, reusing as much as possible the global trusted settings
if ($name = $trustedHeaders[Request::HEADER_FORWARDED]) {
if (Request::HEADER_FORWARDED & $trustedHeaderSet) {
$trustedValues[0] .= sprintf(';host="%s";proto=%s', $request->getHttpHost(), $request->getScheme());
$request->headers->set($name, $v = implode(', ', $trustedValues));
$request->headers->set($name = $trustedHeaders[Request::HEADER_FORWARDED], $v = implode(', ', $trustedValues));
$request->server->set('HTTP_'.strtoupper(str_replace('-', '_', $name)), $v);
}
if ($name = $trustedHeaders[Request::HEADER_CLIENT_IP]) {
$request->headers->set($name, $v = implode(', ', $trustedIps));
if (Request::HEADER_X_FORWARDED_FOR & $trustedHeaderSet) {
$request->headers->set($name = $trustedHeaders[Request::HEADER_X_FORWARDED_FOR], $v = implode(', ', $trustedIps));
$request->server->set('HTTP_'.strtoupper(str_replace('-', '_', $name)), $v);
} elseif (!(Request::HEADER_FORWARDED & $trustedHeaderSet)) {
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet | Request::HEADER_X_FORWARDED_FOR);
$request->headers->set($name = $trustedHeaders[Request::HEADER_X_FORWARDED_FOR], $v = implode(', ', $trustedIps));
$request->server->set('HTTP_'.strtoupper(str_replace('-', '_', $name)), $v);
}
if (!$name && !$trustedHeaders[Request::HEADER_FORWARDED]) {
$request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps));
$request->server->set('HTTP_X_FORWARDED_FOR', $v);
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_FORWARDED_FOR');
}
// fix the client IP address by setting it to 127.0.0.1,
@@ -81,24 +95,14 @@ class SubRequestHandler
// ensure 127.0.0.1 is set as trusted proxy
if (!IpUtils::checkIp('127.0.0.1', $trustedProxies)) {
Request::setTrustedProxies(array_merge($trustedProxies, array('127.0.0.1')));
Request::setTrustedProxies(array_merge($trustedProxies, ['127.0.0.1']), Request::getTrustedHeaderSet());
}
try {
$e = null;
$response = $kernel->handle($request, $type, $catch);
} catch (\Throwable $e) {
} catch (\Exception $e) {
return $kernel->handle($request, $type, $catch);
} finally {
// restore global state
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet);
}
// restore global state
Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $trustedHeaders[Request::HEADER_CLIENT_IP]);
Request::setTrustedProxies($trustedProxies);
if (null !== $e) {
throw $e;
}
return $response;
}
}