[HttpFoundation] Find the original request protocol version

This commit is contained in:
Chris Wilkinson 2017-01-31 08:56:27 +00:00 committed by Fabien Potencier
parent 76858808ad
commit 5a37f84713
2 changed files with 54 additions and 0 deletions

View File

@ -1581,6 +1581,30 @@ class Request
return in_array($this->getMethod(), array('GET', 'HEAD'));
}
/**
* Returns the protocol version.
*
* If the application is behind a proxy, the protocol version used in the
* requests between the client and the proxy and between the proxy and the
* server might be different. This returns the former (from the "Via" header)
* if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns
* the latter (from the "SERVER_PROTOCOL" server parameter).
*
* @return string
*/
public function getProtocolVersion()
{
if ($this->isFromTrustedProxy()) {
preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via'), $matches);
if ($matches) {
return 'HTTP/'.$matches[2];
}
}
return $this->server->get('SERVER_PROTOCOL');
}
/**
* Returns the request body content.
*

View File

@ -2188,6 +2188,36 @@ class RequestTest extends TestCase
Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_FORWARDED_PORT');
Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_FORWARDED_PROTO');
}
/**
* @dataProvider protocolVersionProvider
*/
public function testProtocolVersion($serverProtocol, $trustedProxy, $via, $expected)
{
if ($trustedProxy) {
Request::setTrustedProxies(array('1.1.1.1'));
}
$request = new Request();
$request->server->set('SERVER_PROTOCOL', $serverProtocol);
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('Via', $via);
$this->assertSame($expected, $request->getProtocolVersion());
}
public function protocolVersionProvider()
{
return array(
'untrusted without via' => array('HTTP/2.0', false, '', 'HTTP/2.0'),
'untrusted with via' => array('HTTP/2.0', false, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/2.0'),
'trusted without via' => array('HTTP/2.0', true, '', 'HTTP/2.0'),
'trusted with via' => array('HTTP/2.0', true, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'),
'trusted with via and protocol name' => array('HTTP/2.0', true, 'HTTP/1.0 fred, HTTP/1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'),
'trusted with broken via' => array('HTTP/2.0', true, 'HTTP/1^0 foo', 'HTTP/2.0'),
'trusted with partially-broken via' => array('HTTP/2.0', true, '1.0 fred, foo', 'HTTP/1.0'),
);
}
}
class RequestContentProxy extends Request