Skip to content
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

Improve error messages for failed connections #270

Merged
merged 6 commits into from
Sep 3, 2021
Merged
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ $connector = new React\Socket\Connector();
$connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) {
$connection->pipe(new React\Stream\WritableResourceStream(STDOUT));
$connection->write("Hello World!\n");
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
```

Expand Down Expand Up @@ -905,6 +907,8 @@ $connector = new React\Socket\Connector();
$connector->connect($uri)->then(function (React\Socket\ConnectionInterface $connection) {
$connection->write('...');
$connection->end();
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
```

Expand Down
4 changes: 3 additions & 1 deletion examples/11-http-client.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,6 @@
});

$connection->write("GET / HTTP/1.0\r\nHost: $host\r\n\r\n");
}, 'printf');
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
4 changes: 3 additions & 1 deletion examples/12-https-client.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,6 @@
});

$connection->write("GET / HTTP/1.0\r\nHost: $host\r\n\r\n");
}, 'printf');
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
8 changes: 4 additions & 4 deletions examples/21-netcat-client.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@
$connection->pipe($stdout);

// report errors to STDERR
$connection->on('error', function ($error) use ($stderr) {
$stderr->write('Stream ERROR: ' . $error . PHP_EOL);
$connection->on('error', function (Exception $e) use ($stderr) {
$stderr->write('Stream error: ' . $e->getMessage() . PHP_EOL);
});

// report closing and stop reading from input
Expand All @@ -59,6 +59,6 @@
});

$stderr->write('Connected' . PHP_EOL);
}, function ($error) use ($stderr) {
$stderr->write('Connection ERROR: ' . $error . PHP_EOL);
}, function (Exception $e) use ($stderr) {
$stderr->write('Connection error: ' . $e->getMessage() . PHP_EOL);
});
4 changes: 3 additions & 1 deletion examples/22-http-client.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,6 @@
$connection->pipe($stdout);

$connection->write("GET $resource HTTP/1.0\r\nHost: $host\r\n\r\n");
}, 'printf');
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
57 changes: 57 additions & 0 deletions src/Connector.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,61 @@ public function connect($uri)

return $this->connectors[$scheme]->connect($uri);
}


/**
* [internal] Builds on URI from the given URI parts and ip address with original hostname as query
*
* @param array $parts
* @param string $host
* @param string $ip
* @return string
* @internal
*/
public static function uri(array $parts, $host, $ip)
{
$uri = '';

// prepend original scheme if known
if (isset($parts['scheme'])) {
$uri .= $parts['scheme'] . '://';
}

if (\strpos($ip, ':') !== false) {
// enclose IPv6 addresses in square brackets before appending port
$uri .= '[' . $ip . ']';
} else {
$uri .= $ip;
}

// append original port if known
if (isset($parts['port'])) {
$uri .= ':' . $parts['port'];
}

// append orignal path if known
if (isset($parts['path'])) {
$uri .= $parts['path'];
}

// append original query if known
if (isset($parts['query'])) {
$uri .= '?' . $parts['query'];
}

// append original hostname as query if resolved via DNS and if
// destination URI does not contain "hostname" query param already
$args = array();
\parse_str(isset($parts['query']) ? $parts['query'] : '', $args);
if ($host !== $ip && !isset($args['hostname'])) {
$uri .= (isset($parts['query']) ? '&' : '?') . 'hostname=' . \rawurlencode($host);
}

// append original fragment if known
if (isset($parts['fragment'])) {
$uri .= '#' . $parts['fragment'];
}

return $uri;
}
}
88 changes: 41 additions & 47 deletions src/DnsConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,25 @@ public function __construct(ConnectorInterface $connector, ResolverInterface $re

public function connect($uri)
{
$original = $uri;
if (\strpos($uri, '://') === false) {
$parts = \parse_url('tcp://' . $uri);
$uri = 'tcp://' . $uri;
$parts = \parse_url($uri);
unset($parts['scheme']);
} else {
$parts = \parse_url($uri);
}

if (!$parts || !isset($parts['host'])) {
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid'));
return Promise\reject(new \InvalidArgumentException('Given URI "' . $original . '" is invalid'));
}

$host = \trim($parts['host'], '[]');
$connector = $this->connector;

// skip DNS lookup / URI manipulation if this URI already contains an IP
if (false !== \filter_var($host, \FILTER_VALIDATE_IP)) {
return $connector->connect($uri);
return $connector->connect($original);
}

$promise = $this->resolver->resolve($host);
Expand All @@ -44,51 +46,43 @@ public function connect($uri)
return new Promise\Promise(
function ($resolve, $reject) use (&$promise, &$resolved, $uri, $connector, $host, $parts) {
// resolve/reject with result of DNS lookup
$promise->then(function ($ip) use (&$promise, &$resolved, $connector, $host, $parts) {
$promise->then(function ($ip) use (&$promise, &$resolved, $uri, $connector, $host, $parts) {
$resolved = $ip;
$uri = '';

// prepend original scheme if known
if (isset($parts['scheme'])) {
$uri .= $parts['scheme'] . '://';
}

if (\strpos($ip, ':') !== false) {
// enclose IPv6 addresses in square brackets before appending port
$uri .= '[' . $ip . ']';
} else {
$uri .= $ip;
}

// append original port if known
if (isset($parts['port'])) {
$uri .= ':' . $parts['port'];
}

// append orignal path if known
if (isset($parts['path'])) {
$uri .= $parts['path'];
}

// append original query if known
if (isset($parts['query'])) {
$uri .= '?' . $parts['query'];
}

// append original hostname as query if resolved via DNS and if
// destination URI does not contain "hostname" query param already
$args = array();
\parse_str(isset($parts['query']) ? $parts['query'] : '', $args);
if ($host !== $ip && !isset($args['hostname'])) {
$uri .= (isset($parts['query']) ? '&' : '?') . 'hostname=' . \rawurlencode($host);
}

// append original fragment if known
if (isset($parts['fragment'])) {
$uri .= '#' . $parts['fragment'];
}

return $promise = $connector->connect($uri);

return $promise = $connector->connect(
Connector::uri($parts, $host, $ip)
)->then(null, function (\Exception $e) use ($uri) {
if ($e instanceof \RuntimeException) {
$message = \preg_replace('/^(Connection to [^ ]+)[&?]hostname=[^ &]+/', '$1', $e->getMessage());
$e = new \RuntimeException(
'Connection to ' . $uri . ' failed: ' . $message,
$e->getCode(),
$e
);

// avoid garbage references by replacing all closures in call stack.
// what a lovely piece of code!
$r = new \ReflectionProperty('Exception', 'trace');
$r->setAccessible(true);
$trace = $r->getValue($e);

// Exception trace arguments are not available on some PHP 7.4 installs
// @codeCoverageIgnoreStart
foreach ($trace as &$one) {
if (isset($one['args'])) {
foreach ($one['args'] as &$arg) {
if ($arg instanceof \Closure) {
$arg = 'Object(' . \get_class($arg) . ')';
}
}
}
}
// @codeCoverageIgnoreEnd
$r->setValue($e, $trace);
}

throw $e;
});
}, function ($e) use ($uri, $reject) {
$reject(new \RuntimeException('Connection to ' . $uri .' failed during DNS lookup: ' . $e->getMessage(), 0, $e));
})->then($resolve, $reject);
Expand Down
47 changes: 4 additions & 43 deletions src/HappyEyeBallsConnectionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,12 @@ public function check($resolve, $reject)

$that->failureCount++;

$message = \preg_replace('/^(Connection to [^ ]+)[&?]hostname=[^ &]+/', '$1', $e->getMessage());
if (\strpos($ip, ':') === false) {
$that->lastError4 = $e->getMessage();
$that->lastError4 = $message;
$that->lastErrorFamily = 4;
} else {
$that->lastError6 = $e->getMessage();
$that->lastError6 = $message;
$that->lastErrorFamily = 6;
}

Expand Down Expand Up @@ -222,47 +223,7 @@ public function check($resolve, $reject)
*/
public function attemptConnection($ip)
{
$uri = '';

// prepend original scheme if known
if (isset($this->parts['scheme'])) {
$uri .= $this->parts['scheme'] . '://';
}

if (\strpos($ip, ':') !== false) {
// enclose IPv6 addresses in square brackets before appending port
$uri .= '[' . $ip . ']';
} else {
$uri .= $ip;
}

// append original port if known
if (isset($this->parts['port'])) {
$uri .= ':' . $this->parts['port'];
}

// append orignal path if known
if (isset($this->parts['path'])) {
$uri .= $this->parts['path'];
}

// append original query if known
if (isset($this->parts['query'])) {
$uri .= '?' . $this->parts['query'];
}

// append original hostname as query if resolved via DNS and if
// destination URI does not contain "hostname" query param already
$args = array();
\parse_str(isset($this->parts['query']) ? $this->parts['query'] : '', $args);
if ($this->host !== $ip && !isset($args['hostname'])) {
$uri .= (isset($this->parts['query']) ? '&' : '?') . 'hostname=' . \rawurlencode($this->host);
}

// append original fragment if known
if (isset($this->parts['fragment'])) {
$uri .= '#' . $this->parts['fragment'];
}
$uri = Connector::uri($this->parts, $this->host, $ip);

return $this->connector->connect($uri);
}
Expand Down
9 changes: 5 additions & 4 deletions src/HappyEyeBallsConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,24 @@ public function __construct(LoopInterface $loop = null, ConnectorInterface $conn

public function connect($uri)
{

$original = $uri;
if (\strpos($uri, '://') === false) {
$parts = \parse_url('tcp://' . $uri);
$uri = 'tcp://' . $uri;
$parts = \parse_url($uri);
unset($parts['scheme']);
} else {
$parts = \parse_url($uri);
}

if (!$parts || !isset($parts['host'])) {
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid'));
return Promise\reject(new \InvalidArgumentException('Given URI "' . $original . '" is invalid'));
}

$host = \trim($parts['host'], '[]');

// skip DNS lookup / URI manipulation if this URI already contains an IP
if (false !== \filter_var($host, \FILTER_VALIDATE_IP)) {
return $this->connector->connect($uri);
return $this->connector->connect($original);
}

$builder = new HappyEyeBallsConnectionBuilder(
Expand Down
37 changes: 34 additions & 3 deletions src/SecureConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ public function connect($uri)
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid'));
}

$uri = \str_replace('tls://', '', $uri);
$context = $this->context;

$encryption = $this->streamEncryption;
$connected = false;
$promise = $this->connector->connect($uri)->then(function (ConnectionInterface $connection) use ($context, $encryption, $uri, &$promise, &$connected) {
$promise = $this->connector->connect(
\str_replace('tls://', '', $uri)
)->then(function (ConnectionInterface $connection) use ($context, $encryption, $uri, &$promise, &$connected) {
// (unencrypted) TCP/IP connection succeeded
$connected = true;

Expand All @@ -66,6 +66,37 @@ public function connect($uri)
$error->getCode()
);
});
}, function (\Exception $e) use ($uri) {
if ($e instanceof \RuntimeException) {
$message = \preg_replace('/^Connection to [^ ]+/', '', $e->getMessage());
$e = new \RuntimeException(
'Connection to ' . $uri . $message,
$e->getCode(),
$e
);

// avoid garbage references by replacing all closures in call stack.
// what a lovely piece of code!
$r = new \ReflectionProperty('Exception', 'trace');
$r->setAccessible(true);
$trace = $r->getValue($e);

// Exception trace arguments are not available on some PHP 7.4 installs
// @codeCoverageIgnoreStart
foreach ($trace as &$one) {
if (isset($one['args'])) {
foreach ($one['args'] as &$arg) {
if ($arg instanceof \Closure) {
$arg = 'Object(' . \get_class($arg) . ')';
}
}
}
}
// @codeCoverageIgnoreEnd
$r->setValue($e, $trace);
}

throw $e;
});

return new \React\Promise\Promise(
Expand Down
Loading