Skip to content

Commit

Permalink
Merge pull request #46 from clue-labs/resolving
Browse files Browse the repository at this point in the history
Support Connector without DNS
  • Loading branch information
clue committed Nov 21, 2015
2 parents 5e3c4c6 + 0f07289 commit 0460210
Show file tree
Hide file tree
Showing 7 changed files with 245 additions and 118 deletions.
63 changes: 49 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,42 +22,77 @@ order to complete:
## Usage

In order to use this project, you'll need the following react boilerplate code
to initialize the main loop and select your DNS server if you have not already
set it up anyway.
to initialize the main loop.

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

$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dns = $dnsResolverFactory->createCached('8.8.8.8', $loop);
```

### Async TCP/IP connections

The `React\SocketClient\Connector` provides a single promise-based
`create($host, $ip)` method which resolves as soon as the connection
The `React\SocketClient\TcpConnector` provides a single promise-based
`create($ip, $port)` method which resolves as soon as the connection
succeeds or fails.

```php
$connector = new React\SocketClient\Connector($loop, $dns);
$tcpConnector = new React\SocketClient\TcpConnector($loop);

$connector->create('www.google.com', 80)->then(function (React\Stream\Stream $stream) {
$tcpConnector->create('127.0.0.1', 80)->then(function (React\Stream\Stream $stream) {
$stream->write('...');
$stream->close();
$stream->end();
});

$loop->run();
```

Note that this class only allows you to connect to IP/port combinations.
If you want to connect to hostname/port combinations, see also the following chapter.

### DNS resolution

The `DnsConnector` class decorates a given `TcpConnector` instance by first
looking up the given domain name and then establishing the underlying TCP/IP
connection to the resolved IP address.

It provides the same promise-based `create($host, $port)` method which resolves with
a `Stream` instance that can be used just like above.

Make sure to set up your DNS resolver and underlying TCP connector like this:

```php
$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dns = $dnsResolverFactory->createCached('8.8.8.8', $loop);

$dnsConnector = new React\SocketClient\DnsConnector($tcpConnector, $dns);

$dnsConnector->create('www.google.com', 80)->then(function (React\Stream\Stream $stream) {
$stream->write('...');
$stream->end();
});

$loop->run();
```

The legacy `Connector` class can be used for backwards-compatiblity reasons.
It works very much like the newer `DnsConnector` but instead has to be
set up like this:

```php
$connector = new React\SocketClient\Connector($loop, $dns);

$connector->create('www.google.com', 80)->then($callback);
```

### Async SSL/TLS connections

The `SecureConnector` class decorates a given `Connector` instance by enabling
SSL/TLS encryption as soon as the raw TCP/IP connection succeeds. It provides
the same promise- based `create($host, $ip)` method which resolves with
a `Stream` instance that can be used just like any non-encrypted stream.
SSL/TLS encryption as soon as the raw TCP/IP connection succeeds.

It provides the same promise- based `create($host, $port)` method which resolves with
a `Stream` instance that can be used just like any non-encrypted stream:

```php
$secureConnector = new React\SocketClient\SecureConnector($connector, $loop);
$secureConnector = new React\SocketClient\SecureConnector($dnsConnector, $loop);

$secureConnector->create('www.google.com', 443)->then(function (React\Stream\Stream $stream) {
$stream->write("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n");
Expand Down
91 changes: 6 additions & 85 deletions src/Connector.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,100 +4,21 @@

use React\EventLoop\LoopInterface;
use React\Dns\Resolver\Resolver;
use React\Stream\Stream;
use React\Promise;
use React\Promise\Deferred;

/**
* @deprecated Exists for BC only, consider using the newer DnsConnector instead
*/
class Connector implements ConnectorInterface
{
private $loop;
private $resolver;
private $connector;

public function __construct(LoopInterface $loop, Resolver $resolver)
{
$this->loop = $loop;
$this->resolver = $resolver;
$this->connector = new DnsConnector(new TcpConnector($loop), $resolver);
}

public function create($host, $port)
{
return $this
->resolveHostname($host)
->then(function ($address) use ($port) {
return $this->createSocketForAddress($address, $port);
});
}

public function createSocketForAddress($address, $port)
{
$url = $this->getSocketUrl($address, $port);

$flags = STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT;
$socket = stream_socket_client($url, $errno, $errstr, 0, $flags);

if (!$socket) {
return Promise\reject(new \RuntimeException(
sprintf("connection to %s:%d failed: %s", $address, $port, $errstr),
$errno
));
}

stream_set_blocking($socket, 0);

// wait for connection

return $this
->waitForStreamOnce($socket)
->then(array($this, 'checkConnectedSocket'))
->then(array($this, 'handleConnectedSocket'));
}

protected function waitForStreamOnce($stream)
{
$deferred = new Deferred();

$loop = $this->loop;

$this->loop->addWriteStream($stream, function ($stream) use ($loop, $deferred) {
$loop->removeWriteStream($stream);

$deferred->resolve($stream);
});

return $deferred->promise();
}

public function checkConnectedSocket($socket)
{
// The following hack looks like the only way to
// detect connection refused errors with PHP's stream sockets.
if (false === stream_socket_get_name($socket, true)) {
return Promise\reject(new ConnectionException('Connection refused'));
}

return Promise\resolve($socket);
}

public function handleConnectedSocket($socket)
{
return new Stream($socket, $this->loop);
}

protected function getSocketUrl($host, $port)
{
if (strpos($host, ':') !== false) {
// enclose IPv6 addresses in square brackets before appending port
$host = '[' . $host . ']';
}
return sprintf('tcp://%s:%s', $host, $port);
}

protected function resolveHostname($host)
{
if (false !== filter_var($host, FILTER_VALIDATE_IP)) {
return Promise\resolve($host);
}

return $this->resolver->resolve($host);
return $this->connector->create($host, $port);
}
}
41 changes: 41 additions & 0 deletions src/DnsConnector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace React\SocketClient;

use React\EventLoop\LoopInterface;
use React\Dns\Resolver\Resolver;
use React\Stream\Stream;
use React\Promise;
use React\Promise\Deferred;

class DnsConnector implements ConnectorInterface
{
private $connector;
private $resolver;

public function __construct(ConnectorInterface $connector, Resolver $resolver)
{
$this->connector = $connector;
$this->resolver = $resolver;
}

public function create($host, $port)
{
$connector = $this->connector;

return $this
->resolveHostname($host)
->then(function ($address) use ($connector, $port) {
return $connector->create($address, $port);
});
}

private function resolveHostname($host)
{
if (false !== filter_var($host, FILTER_VALIDATE_IP)) {
return Promise\resolve($host);
}

return $this->resolver->resolve($host);
}
}
88 changes: 88 additions & 0 deletions src/TcpConnector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace React\SocketClient;

use React\EventLoop\LoopInterface;
use React\Dns\Resolver\Resolver;
use React\Stream\Stream;
use React\Promise;
use React\Promise\Deferred;

class TcpConnector implements ConnectorInterface
{
private $loop;

public function __construct(LoopInterface $loop)
{
$this->loop = $loop;
}

public function create($ip, $port)
{
if (false === filter_var($ip, FILTER_VALIDATE_IP)) {
return Promise\reject(new \InvalidArgumentException('Given parameter "' . $ip . '" is not a valid IP'));
}

$url = $this->getSocketUrl($ip, $port);

$socket = stream_socket_client($url, $errno, $errstr, 0, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT);

if (!$socket) {
return Promise\reject(new \RuntimeException(
sprintf("Connection to %s:%d failed: %s", $ip, $port, $errstr),
$errno
));
}

stream_set_blocking($socket, 0);

// wait for connection

return $this
->waitForStreamOnce($socket)
->then(array($this, 'checkConnectedSocket'))
->then(array($this, 'handleConnectedSocket'));
}

private function waitForStreamOnce($stream)
{
$deferred = new Deferred();

$loop = $this->loop;

$this->loop->addWriteStream($stream, function ($stream) use ($loop, $deferred) {
$loop->removeWriteStream($stream);

$deferred->resolve($stream);
});

return $deferred->promise();
}

/** @internal */
public function checkConnectedSocket($socket)
{
// The following hack looks like the only way to
// detect connection refused errors with PHP's stream sockets.
if (false === stream_socket_get_name($socket, true)) {
return Promise\reject(new ConnectionException('Connection refused'));
}

return Promise\resolve($socket);
}

/** @internal */
public function handleConnectedSocket($socket)
{
return new Stream($socket, $this->loop);
}

private function getSocketUrl($ip, $port)
{
if (strpos($ip, ':') !== false) {
// enclose IPv6 addresses in square brackets before appending port
$ip = '[' . $ip . ']';
}
return sprintf('tcp://%s:%s', $ip, $port);
}
}
45 changes: 45 additions & 0 deletions tests/DnsConnectorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace React\Tests\SocketClient;

use React\SocketClient\DnsConnector;
use React\Promise;

class DnsConnectorTest extends TestCase
{
private $tcp;
private $resolver;
private $connector;

public function setUp()
{
$this->tcp = $this->getMock('React\SocketClient\ConnectorInterface');
$this->resolver = $this->getMockBuilder('React\Dns\Resolver\Resolver')->disableOriginalConstructor()->getMock();

$this->connector = new DnsConnector($this->tcp, $this->resolver);
}

public function testPassByResolverIfGivenIp()
{
$this->resolver->expects($this->never())->method('resolve');
$this->tcp->expects($this->once())->method('create')->with($this->equalTo('127.0.0.1'), $this->equalTo(80));

$this->connector->create('127.0.0.1', 80);
}

public function testPassThroughResolverIfGivenHost()
{
$this->resolver->expects($this->once())->method('resolve')->with($this->equalTo('google.com'))->will($this->returnValue(Promise\resolve('1.2.3.4')));
$this->tcp->expects($this->once())->method('create')->with($this->equalTo('1.2.3.4'), $this->equalTo(80));

$this->connector->create('google.com', 80);
}

public function testSkipConnectionIfDnsFails()
{
$this->resolver->expects($this->once())->method('resolve')->with($this->equalTo('example.invalid'))->will($this->returnValue(Promise\reject()));
$this->tcp->expects($this->never())->method('create');

$this->connector->create('example.invalid', 80);
}
}
2 changes: 1 addition & 1 deletion tests/IntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ public function gettingStuffFromGoogleShouldWork()

$factory = new Factory();
$dns = $factory->create('8.8.8.8', $loop);
$connector = new Connector($loop, $dns);

$connected = false;
$response = null;

$connector = new Connector($loop, $dns);
$connector->create('google.com', 80)
->then(function ($conn) use (&$connected) {
$connected = true;
Expand Down
Loading

0 comments on commit 0460210

Please sign in to comment.