Skip to content

Commit

Permalink
Throw on socket warnings
Browse files Browse the repository at this point in the history
Fixes #108.
  • Loading branch information
trowski committed Dec 31, 2023
1 parent 88ca6d2 commit 988406c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
34 changes: 17 additions & 17 deletions src/DnsSocketConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,17 @@ final class DnsSocketConnector implements SocketConnector
use ForbidCloning;
use ForbidSerialization;

private readonly \Closure $errorHandler;

public function __construct(private readonly ?DnsResolver $dnsResolver = null)
{
$this->errorHandler = static fn () => true;
}

public function connect(
SocketAddress|string $uri,
?ConnectContext $context = null,
?Cancellation $cancellation = null
): Socket {
$context ??= new ConnectContext;
$cancellation ??= new NullCancellation;
$context ??= new ConnectContext();
$cancellation ??= new NullCancellation();

if ($uri instanceof SocketAddress) {
$uri = match ($uri->getType()) {
Expand All @@ -52,28 +49,31 @@ public function connect(
try {
$streamContext = \stream_context_create($context->withoutTlsContext()->toStreamContextArray());

\set_error_handler($this->errorHandler);

try {
$socket = \stream_socket_client($builtUri, $errno, $errstr, flags: $flags, context: $streamContext);
} finally {
\restore_error_handler();
}
\set_error_handler(static function (int $errno, string $errstr) use (
&$failures,
$uri,
$builtUri,
): never {
$authority = $uri === $builtUri ? $builtUri : $uri . ' @ ' . $builtUri;

if (!$socket) {
throw new ConnectException(\sprintf(
'Connection to %s @ %s failed: (Error #%d) %s%s',
$uri,
$builtUri,
'Connection to %s failed: (Error #%d) %s%s',
$authority,
$errno,
$errstr,
$failures ? '; previous attempts: ' . \implode($failures) : ''
), $errno);
});

try {
$socket = \stream_socket_client($builtUri, flags: $flags, context: $streamContext);
} finally {
\restore_error_handler();
}

\stream_set_blocking($socket, false);

$deferred = new DeferredFuture;
$deferred = new DeferredFuture();
$id = $cancellation->subscribe($deferred->error(...));
$watcher = EventLoop::onWritable(
$socket,
Expand Down
8 changes: 8 additions & 0 deletions test/IntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,12 @@ public function testConnectTls11Allow(): void

$this->expectNotToPerformAssertions();
}

public function testBindToNonAssignableAddress(): void
{
$this->expectException(ConnectException::class);
$this->expectExceptionMessage("Can't assign requested address");

(new DnsSocketConnector())->connect("127.0.0.1:80", (new ConnectContext())->withBindto("128.0.0.1"));
}
}

0 comments on commit 988406c

Please sign in to comment.