From 56cf65a4f5e4f2e164c49b3e6e76703853dcf045 Mon Sep 17 00:00:00 2001 From: Abyr Valg Date: Thu, 31 Aug 2017 10:30:26 +0300 Subject: [PATCH 1/2] Remove circular reference from stream reader --- src/ProxyConnector.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ProxyConnector.php b/src/ProxyConnector.php index c7801f8..e500fc6 100644 --- a/src/ProxyConnector.php +++ b/src/ProxyConnector.php @@ -134,14 +134,11 @@ public function connect($uri) // keep buffering data until headers are complete $buffer = ''; - $fn = function ($chunk) use (&$buffer, &$fn, $deferred, $stream) { + $fn = function ($chunk) use (&$buffer, $deferred, $stream) { $buffer .= $chunk; $pos = strpos($buffer, "\r\n\r\n"); if ($pos !== false) { - // end of headers received => stop buffering - $stream->removeListener('data', $fn); - // try to parse headers as response message try { $response = Psr7\parse_response(substr($buffer, 0, $pos)); @@ -191,7 +188,10 @@ public function connect($uri) $stream->write("CONNECT " . $host . ":" . $port . " HTTP/1.1\r\nHost: " . $host . ":" . $port . "\r\n" . $auth . "\r\n"); - return $deferred->promise(); + return $deferred->promise()->always(function () use ($stream, $fn) { + // Stop buffering when connection has been established or rejected. + $stream->removeListener('data', $fn); + }); }, function (Exception $e) use ($proxyUri) { throw new RuntimeException('Unable to connect to proxy (ECONNREFUSED)', defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111, $e); }); From a6816e5e6673fdd5514c5e66dc36f08b4f246324 Mon Sep 17 00:00:00 2001 From: Abyr Valg Date: Thu, 31 Aug 2017 12:13:08 +0300 Subject: [PATCH 2/2] Remove listener only on sucessful attempt --- src/ProxyConnector.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ProxyConnector.php b/src/ProxyConnector.php index e500fc6..dd070f3 100644 --- a/src/ProxyConnector.php +++ b/src/ProxyConnector.php @@ -188,9 +188,10 @@ public function connect($uri) $stream->write("CONNECT " . $host . ":" . $port . " HTTP/1.1\r\nHost: " . $host . ":" . $port . "\r\n" . $auth . "\r\n"); - return $deferred->promise()->always(function () use ($stream, $fn) { - // Stop buffering when connection has been established or rejected. + return $deferred->promise()->then(function (ConnectionInterface $stream) use ($fn) { + // Stop buffering when connection has been established. $stream->removeListener('data', $fn); + return new Promise\FulfilledPromise($stream); }); }, function (Exception $e) use ($proxyUri) { throw new RuntimeException('Unable to connect to proxy (ECONNREFUSED)', defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111, $e);