Upgrade framework

This commit is contained in:
2023-11-14 16:54:35 +01:00
parent 1648a5cd42
commit 4fcf6fffcc
10548 changed files with 693138 additions and 466698 deletions

View File

@@ -24,28 +24,24 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
abstract class AbstractSurrogate implements SurrogateInterface
{
protected $contentTypes;
protected $phpEscapeMap = array(
array('<?', '<%', '<s', '<S'),
array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
);
protected $phpEscapeMap = [
['<?', '<%', '<s', '<S'],
['<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'],
];
/**
* Constructor.
*
* @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 = array('text/html', 'text/xml', 'application/xhtml+xml', '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()
public function createCacheStrategy(): ResponseCacheStrategyInterface
{
return new ResponseCacheStrategy();
}
@@ -53,13 +49,13 @@ abstract class AbstractSurrogate implements SurrogateInterface
/**
* {@inheritdoc}
*/
public function hasSurrogateCapability(Request $request)
public function hasSurrogateCapability(Request $request): bool
{
if (null === $value = $request->headers->get('Surrogate-Capability')) {
return false;
}
return false !== strpos($value, sprintf('%s/1.0', strtoupper($this->getName())));
return str_contains($value, sprintf('%s/1.0', strtoupper($this->getName())));
}
/**
@@ -76,7 +72,7 @@ abstract class AbstractSurrogate implements SurrogateInterface
/**
* {@inheritdoc}
*/
public function needsParsing(Response $response)
public function needsParsing(Response $response): bool
{
if (!$control = $response->headers->get('Surrogate-Control')) {
return false;
@@ -90,15 +86,15 @@ abstract class AbstractSurrogate implements SurrogateInterface
/**
* {@inheritdoc}
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
public function handle(HttpCache $cache, string $uri, string $alt, bool $ignoreErrors): string
{
$subRequest = Request::create($uri, Request::METHOD_GET, array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
$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()));
if (!$response->isSuccessful() && Response::HTTP_NOT_MODIFIED !== $response->getStatusCode()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %d).', $subRequest->getUri(), $response->getStatusCode()));
}
return $response->getContent();
@@ -111,12 +107,12 @@ abstract class AbstractSurrogate implements SurrogateInterface
throw $e;
}
}
return '';
}
/**
* Remove the Surrogate from the Surrogate-Control header.
*
* @param Response $response
*/
protected function removeFromControl(Response $response)
{

View File

@@ -27,7 +27,7 @@ use Symfony\Component\HttpFoundation\Response;
*/
class Esi extends AbstractSurrogate
{
public function getName()
public function getName(): string
{
return 'esi';
}
@@ -37,7 +37,7 @@ class Esi extends AbstractSurrogate
*/
public function addSurrogateControl(Response $response)
{
if (false !== strpos($response->getContent(), '<esi:include')) {
if (str_contains($response->getContent(), '<esi:include')) {
$response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
}
}
@@ -45,7 +45,7 @@ class Esi extends AbstractSurrogate
/**
* {@inheritdoc}
*/
public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
public function renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = ''): string
{
$html = sprintf('<esi:include src="%s"%s%s />',
$uri,
@@ -63,7 +63,7 @@ class Esi extends AbstractSurrogate
/**
* {@inheritdoc}
*/
public function process(Request $request, Response $response)
public function process(Request $request, Response $response): Response
{
$type = $response->headers->get('Content-Type');
if (empty($type)) {
@@ -71,7 +71,7 @@ class Esi extends AbstractSurrogate
}
$parts = explode(';', $type);
if (!in_array($parts[0], $this->contentTypes)) {
if (!\in_array($parts[0], $this->contentTypes)) {
return $response;
}
@@ -80,13 +80,13 @@ class Esi extends AbstractSurrogate
$content = preg_replace('#<esi\:remove>.*?</esi\:remove>#s', '', $content);
$content = preg_replace('#<esi\:comment[^>]+>#s', '', $content);
$chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
$chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
$chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
$i = 1;
while (isset($chunks[$i])) {
$options = array();
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
$options = [];
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
}
@@ -97,7 +97,7 @@ class Esi extends AbstractSurrogate
$chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
var_export($options['src'], true),
var_export(isset($options['alt']) ? $options['alt'] : '', true),
var_export($options['alt'] ?? '', true),
isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false'
);
++$i;
@@ -111,5 +111,7 @@ class Esi extends AbstractSurrogate
// remove ESI/1.0 from the Surrogate-Control header
$this->removeFromControl($response);
return $response;
}
}

View File

@@ -5,20 +5,22 @@
*
* (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.
*/
/*
* This code is partially based on the Rack-Cache library by Ryan Tomayko,
* which is released under the MIT license.
* (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
*/
namespace Symfony\Component\HttpKernel\HttpCache;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
/**
* Cache provides HTTP caching.
@@ -31,16 +33,23 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
private $store;
private $request;
private $surrogate;
private $surrogateCacheStrategy;
private $options = array();
private $traces = array();
private $surrogateCacheStrategy = null;
private array $options = [];
private array $traces = [];
/**
* Constructor.
*
* The available options are:
*
* * debug: If true, the traces are added as a HTTP header to ease debugging
* * debug If true, exceptions are thrown when things go wrong. Otherwise, the cache
* will try to carry on and deliver a meaningful response.
*
* * trace_level May be one of 'none', 'short' and 'full'. For 'short', a concise trace of the
* main request will be added as an HTTP header. 'full' will add traces for all
* requests (including ESI subrequests). (default: 'full' if in debug; 'none' otherwise)
*
* * trace_header Header name to use for traces. (default: X-Symfony-Cache)
*
* * default_ttl The number of seconds that a cache entry should be considered
* fresh when no explicit freshness information is provided in
@@ -69,60 +78,72 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* the cache can serve a stale response when an error is encountered (default: 60).
* This setting is overridden by the stale-if-error HTTP Cache-Control extension
* (see RFC 5861).
*
* @param HttpKernelInterface $kernel An HttpKernelInterface instance
* @param StoreInterface $store A Store instance
* @param SurrogateInterface $surrogate A SurrogateInterface instance
* @param array $options An array of options
*/
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);
'trace_level' => 'none',
'trace_header' => 'X-Symfony-Cache',
], $options);
if (!isset($options['trace_level'])) {
$this->options['trace_level'] = $this->options['debug'] ? 'full' : 'none';
}
}
/**
* Gets the current store.
*
* @return StoreInterface $store A StoreInterface instance
*/
public function getStore()
public function getStore(): StoreInterface
{
return $this->store;
}
/**
* Returns an array of events that took place during processing of the last request.
*
* @return array An array of events
*/
public function getTraces()
public function getTraces(): array
{
return $this->traces;
}
private function addTraces(Response $response)
{
$traceString = null;
if ('full' === $this->options['trace_level']) {
$traceString = $this->getLog();
}
if ('short' === $this->options['trace_level'] && $masterId = array_key_first($this->traces)) {
$traceString = implode('/', $this->traces[$masterId]);
}
if (null !== $traceString) {
$response->headers->add([$this->options['trace_header'] => $traceString]);
}
}
/**
* Returns a log message for the events of the last request processing.
*
* @return string A log message
*/
public function getLog()
public function getLog(): string
{
$log = array();
$log = [];
foreach ($this->traces as $request => $traces) {
$log[] = sprintf('%s: %s', $request, implode(', ', $traces));
}
@@ -131,21 +152,17 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
/**
* Gets the Request instance associated with the master request.
*
* @return Request A Request instance
* Gets the Request instance associated with the main request.
*/
public function getRequest()
public function getRequest(): Request
{
return $this->request;
}
/**
* Gets the Kernel instance.
*
* @return HttpKernelInterface An HttpKernelInterface instance
*/
public function getKernel()
public function getKernel(): HttpKernelInterface
{
return $this->kernel;
}
@@ -153,11 +170,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Gets the Surrogate instance.
*
* @return SurrogateInterface A Surrogate instance
*
* @throws \LogicException
*/
public function getSurrogate()
public function getSurrogate(): SurrogateInterface
{
return $this->surrogate;
}
@@ -165,20 +180,24 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* {@inheritdoc}
*/
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
{
// 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->request = $request;
if (HttpKernelInterface::MAIN_REQUEST === $type) {
$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
// and adding the X-Forwarded-For header, see HttpCache::forward()).
$this->request = clone $request;
if (null !== $this->surrogate) {
$this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy();
}
}
$this->traces[$this->getTraceKey($request)] = array();
$this->traces[$this->getTraceKey($request)] = [];
if (!$request->isMethodSafe(false)) {
if (!$request->isMethodSafe()) {
$response = $this->invalidate($request, $catch);
} elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
$response = $this->pass($request, $catch);
@@ -195,12 +214,12 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$this->restoreResponseBody($request, $response);
if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
$response->headers->set('X-Symfony-Cache', $this->getLog());
if (HttpKernelInterface::MAIN_REQUEST === $type) {
$this->addTraces($response);
}
if (null !== $this->surrogate) {
if (HttpKernelInterface::MASTER_REQUEST === $type) {
if (HttpKernelInterface::MAIN_REQUEST === $type) {
$this->surrogateCacheStrategy->update($response);
} else {
$this->surrogateCacheStrategy->add($response);
@@ -227,12 +246,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Forwards the Request to the backend without storing the Response in the cache.
*
* @param Request $request A Request instance
* @param bool $catch Whether to process exceptions
*
* @return Response A Response instance
* @param bool $catch Whether to process exceptions
*/
protected function pass(Request $request, $catch = false)
protected function pass(Request $request, bool $catch = false): Response
{
$this->record($request, 'pass');
@@ -242,16 +258,13 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Invalidates non-safe methods (like POST, PUT, and DELETE).
*
* @param Request $request A Request instance
* @param bool $catch Whether to process exceptions
*
* @return Response A Response instance
* @param bool $catch Whether to process exceptions
*
* @throws \Exception
*
* @see RFC2616 13.10
*/
protected function invalidate(Request $request, $catch = false)
protected function invalidate(Request $request, bool $catch = false): Response
{
$response = $this->pass($request, $catch);
@@ -261,9 +274,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);
}
@@ -291,14 +304,11 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* the backend using conditional GET. When no matching cache entry is found,
* it triggers "miss" processing.
*
* @param Request $request A Request instance
* @param bool $catch whether to process exceptions
*
* @return Response A Response instance
* @param bool $catch Whether to process exceptions
*
* @throws \Exception
*/
protected function lookup(Request $request, $catch = false)
protected function lookup(Request $request, bool $catch = false): Response
{
try {
$entry = $this->store->lookup($request);
@@ -324,6 +334,10 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
return $this->validate($request, $entry, $catch);
}
if ($entry->headers->hasCacheControlDirective('no-cache')) {
return $this->validate($request, $entry, $catch);
}
$this->record($request, 'fresh');
$entry->headers->set('Age', $entry->getAge());
@@ -337,13 +351,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* The original request is used as a template for a conditional
* GET request with the backend.
*
* @param Request $request A Request instance
* @param Response $entry A Response instance to validate
* @param bool $catch Whether to process exceptions
*
* @return Response A Response instance
* @param bool $catch Whether to process exceptions
*/
protected function validate(Request $request, Response $entry, $catch = false)
protected function validate(Request $request, Response $entry, bool $catch = false): Response
{
$subRequest = clone $request;
@@ -353,15 +363,17 @@ 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));
$subRequest->headers->set('If-None-Match', implode(', ', $etags));
}
$response = $this->forward($subRequest, $catch, $entry);
@@ -371,14 +383,14 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
// return the response and not the cache entry if the response is valid but not cached
$etag = $response->getEtag();
if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
if ($etag && \in_array($etag, $requestEtags) && !\in_array($etag, $cachedEtags)) {
return $response;
}
$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));
}
@@ -400,12 +412,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* 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
*
* @return Response A Response instance
* @param bool $catch Whether to process exceptions
*/
protected function fetch(Request $request, $catch = false)
protected function fetch(Request $request, bool $catch = false): Response
{
$subRequest = clone $request;
@@ -415,8 +424,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
// avoid that the backend sends no content
$subRequest->headers->remove('if_modified_since');
$subRequest->headers->remove('if_none_match');
$subRequest->headers->remove('If-Modified-Since');
$subRequest->headers->remove('If-None-Match');
$response = $this->forward($subRequest, $catch);
@@ -433,47 +442,51 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* All backend requests (cache passes, fetches, cache validations)
* run through this method.
*
* @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)
* @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
* @return Response
*/
protected function forward(Request $request, $catch = false, Response $entry = null)
protected function forward(Request $request, bool $catch = false, Response $entry = null)
{
if ($this->surrogate) {
$this->surrogate->addSurrogateCapability($request);
}
// modify the X-Forwarded-For header if needed
$forwardedFor = $request->headers->get('X-Forwarded-For');
if ($forwardedFor) {
$request->headers->set('X-Forwarded-For', $forwardedFor.', '.$request->server->get('REMOTE_ADDR'));
} else {
$request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR'));
}
// fix the client IP address by setting it to 127.0.0.1 as HttpCache
// is always called from the same process as the backend.
$request->server->set('REMOTE_ADDR', '127.0.0.1');
// make sure HttpCache is a trusted proxy
if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) {
$trustedProxies[] = '127.0.0.1';
Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_ALL);
}
// always a "master" request (as the real master request can be in cache)
$response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
// FIXME: we probably need to also catch exceptions if raw === true
$response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MAIN_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))) {
/*
* Support stale-if-error given on Responses or as a config option.
* RFC 7234 summarizes in Section 4.2.4 (but also mentions with the individual
* Cache-Control directives) that
*
* A cache MUST NOT generate a stale response if it is prohibited by an
* explicit in-protocol directive (e.g., by a "no-store" or "no-cache"
* cache directive, a "must-revalidate" cache-response-directive, or an
* applicable "s-maxage" or "proxy-revalidate" cache-response-directive;
* see Section 5.2.2).
*
* https://tools.ietf.org/html/rfc7234#section-4.2.4
*
* We deviate from this in one detail, namely that we *do* serve entries in the
* stale-if-error case even if they have a `s-maxage` Cache-Control directive.
*/
if (null !== $entry
&& \in_array($response->getStatusCode(), [500, 502, 503, 504])
&& !$entry->headers->hasCacheControlDirective('no-cache')
&& !$entry->mustRevalidate()
) {
if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
$age = $this->options['stale_if_error'];
}
if (abs($entry->getTtl()) < $age) {
/*
* stale-if-error gives the (extra) time that the Response may be used *after* it has become stale.
* So we compare the time the $entry has been sitting in the cache already with the
* time it was fresh plus the allowed grace period.
*/
if ($entry->getAge() <= $entry->getMaxAge() + $age) {
$this->record($request, 'stale-if-error');
return $entry;
@@ -504,13 +517,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Checks whether the cache entry is "fresh enough" to satisfy the Request.
*
* @param Request $request A Request instance
* @param Response $entry A Response instance
*
* @return bool true if the cache entry if fresh enough, false otherwise
*/
protected function isFreshEnough(Request $request, Response $entry)
protected function isFreshEnough(Request $request, Response $entry): bool
{
if (!$entry->isFresh()) {
return $this->lock($request, $entry);
@@ -526,12 +534,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Locks a Request during the call to the backend.
*
* @param Request $request A Request instance
* @param Response $entry A Response instance
*
* @return bool true if the cache entry can be returned even if it is staled, false otherwise
*/
protected function lock(Request $request, Response $entry)
protected function lock(Request $request, Response $entry): bool
{
// try to acquire a lock to call the backend
$lock = $this->store->lock($request);
@@ -574,9 +579,6 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Writes the Response to the cache.
*
* @param Request $request A Request instance
* @param Response $response A Response instance
*
* @throws \Exception
*/
protected function store(Request $request, Response $response)
@@ -601,20 +603,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Restores the Response body.
*
* @param Request $request A Request instance
* @param Response $response A Response instance
*/
private function restoreResponseBody(Request $request, Response $response)
{
if ($request->isMethod('HEAD') || 304 === $response->getStatusCode()) {
$response->setContent(null);
$response->headers->remove('X-Body-Eval');
$response->headers->remove('X-Body-File');
return;
}
if ($response->headers->has('X-Body-Eval')) {
ob_start();
@@ -627,10 +618,14 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$response->setContent(ob_get_clean());
$response->headers->remove('X-Body-Eval');
if (!$response->headers->has('Transfer-Encoding')) {
$response->headers->set('Content-Length', strlen($response->getContent()));
$response->headers->set('Content-Length', \strlen($response->getContent()));
}
} elseif ($response->headers->has('X-Body-File')) {
$response->setContent(file_get_contents($response->headers->get('X-Body-File')));
// Response does not include possibly dynamic content (ESI, SSI), so we need
// not handle the content for HEAD requests
if (!$request->isMethod('HEAD')) {
$response->setContent(file_get_contents($response->headers->get('X-Body-File')));
}
} else {
return;
}
@@ -648,18 +643,14 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Checks if the Request includes authorization or other sensitive information
* that should cause the Response to be considered private by default.
*
* @param Request $request A Request instance
*
* @return bool true if the Request is private, false otherwise
*/
private function isPrivateRequest(Request $request)
private function isPrivateRequest(Request $request): bool
{
foreach ($this->options['private_headers'] as $key) {
$key = strtolower(str_replace('HTTP_', '', $key));
if ('cookie' === $key) {
if (count($request->cookies->all())) {
if (\count($request->cookies->all())) {
return true;
}
} elseif ($request->headers->has($key)) {
@@ -672,23 +663,16 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Records that an event took place.
*
* @param Request $request A Request instance
* @param string $event The event name
*/
private function record(Request $request, $event)
private function record(Request $request, string $event)
{
$this->traces[$this->getTraceKey($request)][] = $event;
}
/**
* Calculates the key we use in the "trace" array for a given request.
*
* @param Request $request
*
* @return string
*/
private function getTraceKey(Request $request)
private function getTraceKey(Request $request): string
{
$path = $request->getPathInfo();
if ($qs = $request->getQueryString()) {
@@ -701,12 +685,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Checks whether the given (cached) response may be served as "stale" when a revalidation
* is currently in progress.
*
* @param Response $entry
*
* @return bool True when the stale response may be served, false otherwise.
*/
private function mayServeStaleWhileRevalidate(Response $entry)
private function mayServeStaleWhileRevalidate(Response $entry): bool
{
$timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate');
@@ -714,24 +694,20 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$timeout = $this->options['stale_while_revalidate'];
}
return abs($entry->getTtl()) < $timeout;
return abs($entry->getTtl() ?? 0) < $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)
private function waitForLock(Request $request): bool
{
$wait = 0;
while ($this->store->isLocked($request) && $wait < 5000000) {
while ($this->store->isLocked($request) && $wait < 100) {
usleep(50000);
$wait += 50000;
++$wait;
}
return $wait < 5000000;
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.
*/
@@ -21,37 +17,79 @@ use Symfony\Component\HttpFoundation\Response;
* ResponseCacheStrategy knows how to compute the Response cache HTTP header
* based on the different response cache headers.
*
* This implementation changes the master response TTL to the smallest TTL received
* This implementation changes the main response TTL to the smallest TTL received
* or force validation if one of the surrogates has validation cache strategy.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ResponseCacheStrategy implements ResponseCacheStrategyInterface
{
private $cacheable = true;
private $embeddedResponses = 0;
private $ttls = array();
private $maxAges = array();
private $isNotCacheableResponseEmbedded = false;
/**
* Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
*/
private const OVERRIDE_DIRECTIVES = ['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 const INHERIT_DIRECTIVES = ['public', 'immutable'];
private int $embeddedResponses = 0;
private bool $isNotCacheableResponseEmbedded = false;
private int $age = 0;
private array $flagDirectives = [
'no-cache' => null,
'no-store' => null,
'no-transform' => null,
'must-revalidate' => null,
'proxy-revalidate' => null,
'public' => null,
'private' => null,
'immutable' => null,
];
private array $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::OVERRIDE_DIRECTIVES as $directive) {
if ($response->headers->hasCacheControlDirective($directive)) {
$this->flagDirectives[$directive] = true;
}
}
++$this->embeddedResponses;
foreach (self::INHERIT_DIRECTIVES 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;
}
$isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public');
$maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null;
$this->storeRelativeAgeDirective('max-age', $maxAge, $age, $isHeuristicallyCacheable);
$sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge;
$this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge, $age, $isHeuristicallyCacheable);
$expires = $response->getExpires();
$expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0, $isHeuristicallyCacheable);
}
/**
@@ -64,33 +102,133 @@ 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()) {
$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) {
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
*/
private function willMakeFinalResponseUncacheable(Response $response): bool
{
// 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 and the isHeuristicallyCacheable parameter is false, the directive will
* not be set on the final response. In this case, not all responses had the directive set and no
* value can be found that satisfies the requirements of all responses. The directive will be dropped
* from the final response.
*
* If the isHeuristicallyCacheable parameter is true, however, the current response has been marked
* as cacheable in a public (shared) cache, but did not provide an explicit lifetime that would serve
* as an upper bound. In this case, we can proceed and possibly keep the directive on the final response.
*/
private function storeRelativeAgeDirective(string $directive, ?int $value, int $age, bool $isHeuristicallyCacheable)
{
if (null === $value) {
if ($isHeuristicallyCacheable) {
/*
* See https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
* This particular response does not require maximum lifetime; heuristics might be applied.
* Other responses, however, might have more stringent requirements on maximum lifetime.
* So, return early here so that the final response can have the more limiting value set.
*/
return;
}
$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

@@ -27,15 +27,11 @@ interface ResponseCacheStrategyInterface
{
/**
* Adds a Response.
*
* @param Response $response
*/
public function add(Response $response);
/**
* Updates the Response HTTP headers based on the embedded Responses.
*
* @param Response $response
*/
public function update(Response $response);
}

View File

@@ -24,7 +24,7 @@ class Ssi extends AbstractSurrogate
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return 'ssi';
}
@@ -34,7 +34,7 @@ class Ssi extends AbstractSurrogate
*/
public function addSurrogateControl(Response $response)
{
if (false !== strpos($response->getContent(), '<!--#include')) {
if (str_contains($response->getContent(), '<!--#include')) {
$response->headers->set('Surrogate-Control', 'content="SSI/1.0"');
}
}
@@ -42,7 +42,7 @@ class Ssi extends AbstractSurrogate
/**
* {@inheritdoc}
*/
public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
public function renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = ''): string
{
return sprintf('<!--#include virtual="%s" -->', $uri);
}
@@ -50,7 +50,7 @@ class Ssi extends AbstractSurrogate
/**
* {@inheritdoc}
*/
public function process(Request $request, Response $response)
public function process(Request $request, Response $response): Response
{
$type = $response->headers->get('Content-Type');
if (empty($type)) {
@@ -58,20 +58,20 @@ class Ssi extends AbstractSurrogate
}
$parts = explode(';', $type);
if (!in_array($parts[0], $this->contentTypes)) {
if (!\in_array($parts[0], $this->contentTypes)) {
return $response;
}
// we don't use a proper XML parser here as we can have SSI tags in a plain text response
$content = $response->getContent();
$chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
$chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
$chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
$i = 1;
while (isset($chunks[$i])) {
$options = array();
preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
$options = [];
preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
}
@@ -94,5 +94,7 @@ class Ssi extends AbstractSurrogate
// remove SSI/1.0 from the Surrogate-Control header
$this->removeFromControl($response);
return $response;
}
}

View File

@@ -25,24 +25,21 @@ use Symfony\Component\HttpFoundation\Response;
class Store implements StoreInterface
{
protected $root;
private $keyCache;
private $locks;
/** @var \SplObjectStorage<Request, string> */
private \SplObjectStorage $keyCache;
/** @var array<string, resource> */
private array $locks = [];
/**
* Constructor.
*
* @param string $root The path to the cache directory
*
* @throws \RuntimeException
*/
public function __construct($root)
public function __construct(string $root)
{
$this->root = $root;
if (!file_exists($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
if (!is_dir($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
}
$this->keyCache = new \SplObjectStorage();
$this->locks = array();
}
/**
@@ -52,31 +49,29 @@ class Store implements StoreInterface
{
// unlock everything
foreach ($this->locks as $lock) {
flock($lock, LOCK_UN);
flock($lock, \LOCK_UN);
fclose($lock);
}
$this->locks = array();
$this->locks = [];
}
/**
* Tries to lock the cache for a given Request, without blocking.
*
* @param Request $request A Request instance
*
* @return bool|string true if the lock is acquired, the path to the current lock otherwise
*/
public function lock(Request $request)
public function lock(Request $request): bool|string
{
$key = $this->getCacheKey($request);
if (!isset($this->locks[$key])) {
$path = $this->getPath($key);
if (!file_exists(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
if (!is_dir(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
return $path;
}
$h = fopen($path, 'cb');
if (!flock($h, LOCK_EX | LOCK_NB)) {
$h = fopen($path, 'c');
if (!flock($h, \LOCK_EX | \LOCK_NB)) {
fclose($h);
return $path;
@@ -91,16 +86,14 @@ class Store implements StoreInterface
/**
* Releases the lock for the given Request.
*
* @param Request $request A Request instance
*
* @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
*/
public function unlock(Request $request)
public function unlock(Request $request): bool
{
$key = $this->getCacheKey($request);
if (isset($this->locks[$key])) {
flock($this->locks[$key], LOCK_UN);
flock($this->locks[$key], \LOCK_UN);
fclose($this->locks[$key]);
unset($this->locks[$key]);
@@ -110,7 +103,7 @@ class Store implements StoreInterface
return false;
}
public function isLocked(Request $request)
public function isLocked(Request $request): bool
{
$key = $this->getCacheKey($request);
@@ -118,13 +111,13 @@ class Store implements StoreInterface
return true; // shortcut if lock held by this process
}
if (!file_exists($path = $this->getPath($key))) {
if (!is_file($path = $this->getPath($key))) {
return false;
}
$h = fopen($path, 'rb');
flock($h, LOCK_EX | LOCK_NB, $wouldBlock);
flock($h, LOCK_UN); // release the lock we just acquired
$h = fopen($path, 'r');
flock($h, \LOCK_EX | \LOCK_NB, $wouldBlock);
flock($h, \LOCK_UN); // release the lock we just acquired
fclose($h);
return (bool) $wouldBlock;
@@ -132,17 +125,13 @@ class Store implements StoreInterface
/**
* Locates a cached Response for the Request provided.
*
* @param Request $request A Request instance
*
* @return Response|null A Response instance, or null if no cache entry was found
*/
public function lookup(Request $request)
public function lookup(Request $request): ?Response
{
$key = $this->getCacheKey($request);
if (!$entries = $this->getMetadata($key)) {
return;
return null;
}
// find a cached entry that matches the request.
@@ -156,17 +145,18 @@ class Store implements StoreInterface
}
if (null === $match) {
return;
return null;
}
list($req, $headers) = $match;
if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
return $this->restoreResponse($headers, $body);
$headers = $match[1];
if (file_exists($path = $this->getPath($headers['x-content-digest'][0]))) {
return $this->restoreResponse($headers, $path);
}
// 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;
}
/**
@@ -175,42 +165,46 @@ class Store implements StoreInterface
* Existing entries are read and any that match the response are removed. This
* method calls write with the new list of cache entries.
*
* @param Request $request A Request instance
* @param Response $response A Response instance
*
* @return string The key under which the response is stored
*
* @throws \RuntimeException
*/
public function write(Request $request, Response $response)
public function write(Request $request, Response $response): string
{
$key = $this->getCacheKey($request);
$storedEnv = $this->persistRequest($request);
// write the response body to the entity store if this is the original response
if (!$response->headers->has('X-Content-Digest')) {
$digest = $this->generateContentDigest($response);
if ($response->headers->has('X-Body-File')) {
// Assume the response came from disk, but at least perform some safeguard checks
if (!$response->headers->has('X-Content-Digest')) {
throw new \RuntimeException('A restored response must have the X-Content-Digest header.');
}
if (false === $this->save($digest, $response->getContent())) {
$digest = $response->headers->get('X-Content-Digest');
if ($this->getPath($digest) !== $response->headers->get('X-Body-File')) {
throw new \RuntimeException('X-Body-File and X-Content-Digest do not match.');
}
// Everything seems ok, omit writing content to disk
} else {
$digest = $this->generateContentDigest($response);
$response->headers->set('X-Content-Digest', $digest);
if (!$this->save($digest, $response->getContent(), false)) {
throw new \RuntimeException('Unable to store the entity.');
}
$response->headers->set('X-Content-Digest', $digest);
if (!$response->headers->has('Transfer-Encoding')) {
$response->headers->set('Content-Length', strlen($response->getContent()));
$response->headers->set('Content-Length', \strlen($response->getContent()));
}
}
// 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 ($vary != $entry[1]['vary'][0] || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary ?? '', $entry[0], $storedEnv)) {
$entries[] = $entry;
}
}
@@ -218,9 +212,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.');
}
@@ -229,12 +223,8 @@ class Store implements StoreInterface
/**
* Returns content digest for $response.
*
* @param Response $response
*
* @return string
*/
protected function generateContentDigest(Response $response)
protected function generateContentDigest(Response $response): string
{
return 'en'.hash('sha256', $response->getContent());
}
@@ -242,8 +232,6 @@ class Store implements StoreInterface
/**
* Invalidates all cache entries that match the request.
*
* @param Request $request A Request instance
*
* @throws \RuntimeException
*/
public function invalidate(Request $request)
@@ -251,19 +239,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.');
}
}
@@ -272,13 +260,11 @@ class Store implements StoreInterface
* Determines whether two Request HTTP header sets are non-varying based on
* the vary response header value provided.
*
* @param string $vary A Response vary header
* @param array $env1 A Request HTTP header array
* @param array $env2 A Request HTTP header array
*
* @return bool true if the two environments match, false otherwise
* @param string|null $vary A Response vary header
* @param array $env1 A Request HTTP header array
* @param array $env2 A Request HTTP header array
*/
private function requestsMatch($vary, $env1, $env2)
private function requestsMatch(?string $vary, array $env1, array $env2): bool
{
if (empty($vary)) {
return true;
@@ -286,8 +272,8 @@ class Store implements StoreInterface
foreach (preg_split('/[\s,]+/', $vary) as $header) {
$key = str_replace('_', '-', strtolower($header));
$v1 = isset($env1[$key]) ? $env1[$key] : null;
$v2 = isset($env2[$key]) ? $env2[$key] : null;
$v1 = $env1[$key] ?? null;
$v2 = $env2[$key] ?? null;
if ($v1 !== $v2) {
return false;
}
@@ -300,18 +286,14 @@ class Store implements StoreInterface
* Gets all data associated with the given key.
*
* Use this method only if you know what you are doing.
*
* @param string $key The store key
*
* @return array An array of data associated with the key
*/
private function getMetadata($key)
private function getMetadata(string $key): array
{
if (!$entries = $this->load($key)) {
return array();
return [];
}
return unserialize($entries);
return unserialize($entries) ?: [];
}
/**
@@ -319,11 +301,9 @@ class Store implements StoreInterface
*
* This method purges both the HTTP and the HTTPS version of the cache entry.
*
* @param string $url A URL
*
* @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise
*/
public function purge($url)
public function purge(string $url): bool
{
$http = preg_replace('#^https:#', 'http:', $url);
$https = preg_replace('#^http:#', 'https:', $url);
@@ -336,21 +316,17 @@ class Store implements StoreInterface
/**
* Purges data for the given URL.
*
* @param string $url A URL
*
* @return bool true if the URL exists and has been purged, false otherwise
*/
private function doPurge($url)
private function doPurge(string $url): bool
{
$key = $this->getCacheKey(Request::create($url));
if (isset($this->locks[$key])) {
flock($this->locks[$key], LOCK_UN);
flock($this->locks[$key], \LOCK_UN);
fclose($this->locks[$key]);
unset($this->locks[$key]);
}
if (file_exists($path = $this->getPath($key))) {
if (is_file($path = $this->getPath($key))) {
unlink($path);
return true;
@@ -361,67 +337,70 @@ class Store implements StoreInterface
/**
* Loads data for the given key.
*
* @param string $key The store key
*
* @return string The data associated with the key
*/
private function load($key)
private function load(string $key): ?string
{
$path = $this->getPath($key);
return file_exists($path) ? file_get_contents($path) : false;
return is_file($path) && false !== ($contents = @file_get_contents($path)) ? $contents : null;
}
/**
* Save data for the given key.
*
* @param string $key The store key
* @param string $data The data to store
*
* @return bool
*/
private function save($key, $data)
private function save(string $key, string $data, bool $overwrite = true): bool
{
$path = $this->getPath($key);
if (!$overwrite && file_exists($path)) {
return true;
}
if (isset($this->locks[$key])) {
$fp = $this->locks[$key];
@ftruncate($fp, 0);
@fseek($fp, 0);
$len = @fwrite($fp, $data);
if (strlen($data) !== $len) {
if (\strlen($data) !== $len) {
@ftruncate($fp, 0);
return false;
}
} else {
if (!file_exists(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
if (!is_dir(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
return false;
}
$tmpFile = tempnam(dirname($path), basename($path));
if (false === $fp = @fopen($tmpFile, 'wb')) {
$tmpFile = tempnam(\dirname($path), basename($path));
if (false === $fp = @fopen($tmpFile, 'w')) {
@unlink($tmpFile);
return false;
}
@fwrite($fp, $data);
@fclose($fp);
if ($data != file_get_contents($tmpFile)) {
@unlink($tmpFile);
return false;
}
if (false === @rename($tmpFile, $path)) {
@unlink($tmpFile);
return false;
}
}
@chmod($path, 0666 & ~umask());
return true;
}
public function getPath($key)
public function getPath(string $key)
{
return $this->root.DIRECTORY_SEPARATOR.substr($key, 0, 2).DIRECTORY_SEPARATOR.substr($key, 2, 2).DIRECTORY_SEPARATOR.substr($key, 4, 2).DIRECTORY_SEPARATOR.substr($key, 6);
return $this->root.\DIRECTORY_SEPARATOR.substr($key, 0, 2).\DIRECTORY_SEPARATOR.substr($key, 2, 2).\DIRECTORY_SEPARATOR.substr($key, 4, 2).\DIRECTORY_SEPARATOR.substr($key, 6);
}
/**
@@ -433,24 +412,16 @@ class Store implements StoreInterface
* If the same URI can have more than one representation, based on some
* headers, use a Vary header to indicate them, and each representation will
* be stored independently under the same cache key.
*
* @param Request $request A Request instance
*
* @return string A key for the given Request
*/
protected function generateCacheKey(Request $request)
protected function generateCacheKey(Request $request): string
{
return 'md'.hash('sha256', $request->getUri());
}
/**
* Returns a cache key for the given Request.
*
* @param Request $request A Request instance
*
* @return string A key for the given Request
*/
private function getCacheKey(Request $request)
private function getCacheKey(Request $request): string
{
if (isset($this->keyCache[$request])) {
return $this->keyCache[$request];
@@ -461,48 +432,35 @@ class Store implements StoreInterface
/**
* Persists the Request HTTP headers.
*
* @param Request $request A Request instance
*
* @return array An array of HTTP headers
*/
private function persistRequest(Request $request)
private function persistRequest(Request $request): array
{
return $request->headers->all();
}
/**
* Persists the Response HTTP headers.
*
* @param Response $response A Response instance
*
* @return array An array of HTTP headers
*/
private function persistResponse(Response $response)
private function persistResponse(Response $response): array
{
$headers = $response->headers->all();
$headers['X-Status'] = array($response->getStatusCode());
$headers['X-Status'] = [$response->getStatusCode()];
return $headers;
}
/**
* Restores a Response from the HTTP headers and body.
*
* @param array $headers An array of HTTP headers for the Response
* @param string $body The Response body
*
* @return Response
*/
private function restoreResponse($headers, $body = null)
private function restoreResponse(array $headers, string $path = null): Response
{
$status = $headers['X-Status'][0];
unset($headers['X-Status']);
if (null !== $body) {
$headers['X-Body-File'] = array($body);
if (null !== $path) {
$headers['X-Body-File'] = [$path];
}
return new Response($body, $status, $headers);
return new Response($path, $status, $headers);
}
}

View File

@@ -26,12 +26,8 @@ interface StoreInterface
{
/**
* Locates a cached Response for the Request provided.
*
* @param Request $request A Request instance
*
* @return Response|null A Response instance, or null if no cache entry was found
*/
public function lookup(Request $request);
public function lookup(Request $request): ?Response;
/**
* Writes a cache entry to the store for the given Request and Response.
@@ -39,55 +35,42 @@ interface StoreInterface
* Existing entries are read and any that match the response are removed. This
* method calls write with the new list of cache entries.
*
* @param Request $request A Request instance
* @param Response $response A Response instance
*
* @return string The key under which the response is stored
*/
public function write(Request $request, Response $response);
public function write(Request $request, Response $response): string;
/**
* Invalidates all cache entries that match the request.
*
* @param Request $request A Request instance
*/
public function invalidate(Request $request);
/**
* Locks the cache for a given Request.
*
* @param Request $request A Request instance
*
* @return bool|string true if the lock is acquired, the path to the current lock otherwise
*/
public function lock(Request $request);
public function lock(Request $request): bool|string;
/**
* Releases the lock for the given Request.
*
* @param Request $request A Request instance
*
* @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
*/
public function unlock(Request $request);
public function unlock(Request $request): bool;
/**
* Returns whether or not a lock exists.
*
* @param Request $request A Request instance
*
* @return bool true if lock exists, false otherwise
*/
public function isLocked(Request $request);
public function isLocked(Request $request): bool;
/**
* Purges data for the given URL.
*
* @param string $url A URL
*
* @return bool true if the URL exists and has been purged, false otherwise
*/
public function purge($url);
public function purge(string $url): bool;
/**
* Cleanups storage.

View File

@@ -0,0 +1,92 @@
<?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\IpUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class SubRequestHandler
{
public static function handle(HttpKernelInterface $kernel, Request $request, int $type, bool $catch): Response
{
// save global state related to trusted headers and proxies
$trustedProxies = Request::getTrustedProxies();
$trustedHeaderSet = Request::getTrustedHeaderSet();
// remove untrusted values
$remoteAddr = $request->server->get('REMOTE_ADDR');
if (!$remoteAddr || !IpUtils::checkIp($remoteAddr, $trustedProxies)) {
$trustedHeaders = [
'FORWARDED' => $trustedHeaderSet & Request::HEADER_FORWARDED,
'X_FORWARDED_FOR' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_FOR,
'X_FORWARDED_HOST' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_HOST,
'X_FORWARDED_PROTO' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PROTO,
'X_FORWARDED_PORT' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PORT,
'X_FORWARDED_PREFIX' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PREFIX,
];
foreach (array_filter($trustedHeaders) as $name => $key) {
$request->headers->remove($name);
$request->server->remove('HTTP_'.$name);
}
}
// compute trusted values, taking any trusted proxies into account
$trustedIps = [];
$trustedValues = [];
foreach (array_reverse($request->getClientIps()) as $ip) {
$trustedIps[] = $ip;
$trustedValues[] = sprintf('for="%s"', $ip);
}
if ($ip !== $remoteAddr) {
$trustedIps[] = $remoteAddr;
$trustedValues[] = sprintf('for="%s"', $remoteAddr);
}
// set trusted values, reusing as much as possible the global trusted settings
if (Request::HEADER_FORWARDED & $trustedHeaderSet) {
$trustedValues[0] .= sprintf(';host="%s";proto=%s', $request->getHttpHost(), $request->getScheme());
$request->headers->set('Forwarded', $v = implode(', ', $trustedValues));
$request->server->set('HTTP_FORWARDED', $v);
}
if (Request::HEADER_X_FORWARDED_FOR & $trustedHeaderSet) {
$request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps));
$request->server->set('HTTP_X_FORWARDED_FOR', $v);
} elseif (!(Request::HEADER_FORWARDED & $trustedHeaderSet)) {
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet | Request::HEADER_X_FORWARDED_FOR);
$request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps));
$request->server->set('HTTP_X_FORWARDED_FOR', $v);
}
// fix the client IP address by setting it to 127.0.0.1,
// which is the core responsibility of this method
$request->server->set('REMOTE_ADDR', '127.0.0.1');
// ensure 127.0.0.1 is set as trusted proxy
if (!IpUtils::checkIp('127.0.0.1', $trustedProxies)) {
Request::setTrustedProxies(array_merge($trustedProxies, ['127.0.0.1']), Request::getTrustedHeaderSet());
}
try {
return $kernel->handle($request, $type, $catch);
} finally {
// restore global state
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet);
}
}
}

View File

@@ -18,31 +18,21 @@ interface SurrogateInterface
{
/**
* Returns surrogate name.
*
* @return string
*/
public function getName();
public function getName(): string;
/**
* Returns a new cache strategy instance.
*
* @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
*/
public function createCacheStrategy();
public function createCacheStrategy(): ResponseCacheStrategyInterface;
/**
* Checks that at least one surrogate has Surrogate capability.
*
* @param Request $request A Request instance
*
* @return bool true if one surrogate has Surrogate capability, false otherwise
*/
public function hasSurrogateCapability(Request $request);
public function hasSurrogateCapability(Request $request): bool;
/**
* Adds Surrogate-capability to the given Request.
*
* @param Request $request A Request instance
*/
public function addSurrogateCapability(Request $request);
@@ -50,54 +40,34 @@ interface SurrogateInterface
* Adds HTTP headers to specify that the Response needs to be parsed for Surrogate.
*
* This method only adds an Surrogate HTTP header if the Response has some Surrogate tags.
*
* @param Response $response A Response instance
*/
public function addSurrogateControl(Response $response);
/**
* Checks that the Response needs to be parsed for Surrogate tags.
*
* @param Response $response A Response instance
*
* @return bool true if the Response needs to be parsed, false otherwise
*/
public function needsParsing(Response $response);
public function needsParsing(Response $response): bool;
/**
* Renders a Surrogate 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
* @param string $alt An alternate URI
* @param string $comment A comment to add as an esi:include tag
*/
public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '');
public function renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = ''): string;
/**
* Replaces a Response Surrogate tags with the included resource content.
*
* @param Request $request A Request instance
* @param Response $response A Response instance
*
* @return Response
*/
public function process(Request $request, Response $response);
public function process(Request $request, Response $response): Response;
/**
* Handles a Surrogate 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
* @param string $alt An alternative URI
*
* @throws \RuntimeException
* @throws \Exception
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors);
public function handle(HttpCache $cache, string $uri, string $alt, bool $ignoreErrors): string;
}