Skip to content

Support custom HTTP headers #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions examples/03-custom-proxy-headers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

// A simple example which requests https://google.com/ through an HTTP CONNECT proxy.
// The proxy can be given as first argument and defaults to localhost:8080 otherwise.

use Clue\React\HttpProxy\ProxyConnector;
use React\Socket\Connector;
use React\Socket\ConnectionInterface;
use RingCentral\Psr7;

require __DIR__ . '/../vendor/autoload.php';

$url = isset($argv[1]) ? $argv[1] : '127.0.0.1:8080';

$loop = React\EventLoop\Factory::create();

$proxy = new ProxyConnector($url, new Connector($loop), array(
'X-Custom-Header-1' => 'Value-1',
'X-Custom-Header-2' => 'Value-2',
));
$connector = new Connector($loop, array(
'tcp' => $proxy,
'timeout' => 3.0,
'dns' => false,
));

$connector->connect('tls://google.com:443')->then(function (ConnectionInterface $stream) {
$stream->write("GET / HTTP/1.1\r\nHost: google.com\r\nConnection: close\r\n\r\n");
$stream->on('data', function ($chunk) {
echo $chunk;
});
}, 'printf');

$loop->run();
23 changes: 18 additions & 5 deletions src/ProxyConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ class ProxyConnector implements ConnectorInterface
private $connector;
private $proxyUri;
private $proxyAuth = '';
/** @var array */
private $proxyHeaders;

/**
* Instantiate a new ProxyConnector which uses the given $proxyUrl
Expand All @@ -54,9 +56,10 @@ class ProxyConnector implements ConnectorInterface
* @param ConnectorInterface $connector In its most simple form, the given
* connector will be a \React\Socket\Connector if you want to connect to
* a given IP address.
* @param array $httpHeaders Custom HTTP headers to be sent to the proxy.
* @throws InvalidArgumentException if the proxy URL is invalid
*/
public function __construct($proxyUrl, ConnectorInterface $connector)
public function __construct($proxyUrl, ConnectorInterface $connector, array $httpHeaders = array())
{
// support `http+unix://` scheme for Unix domain socket (UDS) paths
if (preg_match('/^http\+unix:\/\/(.*?@)?(.+?)$/', $proxyUrl, $match)) {
Expand Down Expand Up @@ -90,10 +93,12 @@ public function __construct($proxyUrl, ConnectorInterface $connector)

// prepare Proxy-Authorization header if URI contains username/password
if (isset($parts['user']) || isset($parts['pass'])) {
$this->proxyAuth = 'Proxy-Authorization: Basic ' . base64_encode(
$this->proxyAuth = 'Basic ' . base64_encode(
rawurldecode($parts['user'] . ':' . (isset($parts['pass']) ? $parts['pass'] : ''))
) . "\r\n";
);
}

$this->proxyHeaders = $httpHeaders;
}

public function connect($uri)
Expand Down Expand Up @@ -138,8 +143,9 @@ public function connect($uri)
}

$auth = $this->proxyAuth;
$headers = $this->proxyHeaders;

return $this->connector->connect($proxyUri)->then(function (ConnectionInterface $stream) use ($host, $port, $auth) {
return $this->connector->connect($proxyUri)->then(function (ConnectionInterface $stream) use ($host, $port, $auth, $headers) {
$deferred = new Deferred(function ($_, $reject) use ($stream) {
$reject(new RuntimeException('Connection canceled while waiting for response from proxy (ECONNABORTED)', defined('SOCKET_ECONNABORTED') ? SOCKET_ECONNABORTED : 103));
$stream->close();
Expand Down Expand Up @@ -199,7 +205,14 @@ public function connect($uri)
$deferred->reject(new RuntimeException('Connection to proxy lost while waiting for response (ECONNRESET)', defined('SOCKET_ECONNRESET') ? SOCKET_ECONNRESET : 104));
});

$stream->write("CONNECT " . $host . ":" . $port . " HTTP/1.1\r\nHost: " . $host . ":" . $port . "\r\n" . $auth . "\r\n");
$hostAndPort = sprintf('%s:%d', $host, $port);
$headers['Host'] = $hostAndPort;
if ($auth !== '') {
$headers['Proxy-Authorization'] = $auth;
}
$request = new Psr7\Request('CONNECT', $hostAndPort, $headers);
$request = $request->withRequestTarget($hostAndPort);
$stream->write(Psr7\str($request));

return $deferred->promise()->then(function (ConnectionInterface $stream) use ($fn) {
// Stop buffering when connection has been established.
Expand Down
30 changes: 30 additions & 0 deletions tests/ProxyConnectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,36 @@ public function testWillProxyAuthorizationHeaderIfUnixProxyUriContainsAuthentica
$proxy->connect('google.com:80');
}

public function testWillSendCustomHttpHeadersToProxy()
{
$stream = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('close', 'write'))->getMock();
$stream->expects($this->once())->method('write')->with("CONNECT google.com:80 HTTP/1.1\r\nX-Custom-Header: X-Custom-Value\r\nHost: google.com:80\r\n\r\n");

$promise = \React\Promise\resolve($stream);
$this->connector->expects($this->once())->method('connect')->willReturn($promise);

$proxy = new ProxyConnector('proxy.example.com', $this->connector, array(
'X-Custom-Header' => 'X-Custom-Value',
));

$proxy->connect('google.com:80');
}

public function testWillOverrideProxyAuthorizationHeaderWithCredentialsFromUri()
{
$stream = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('close', 'write'))->getMock();
$stream->expects($this->once())->method('write')->with("CONNECT google.com:80 HTTP/1.1\r\nProxy-Authorization: Basic dXNlcjpwYXNz\r\nHost: google.com:80\r\n\r\n");

$promise = \React\Promise\resolve($stream);
$this->connector->expects($this->once())->method('connect')->willReturn($promise);

$proxy = new ProxyConnector('user:[email protected]', $this->connector, array(
'Proxy-Authorization' => 'foobar',
));

$proxy->connect('google.com:80');
}

public function testRejectsInvalidUri()
{
$this->connector->expects($this->never())->method('connect');
Expand Down