Skip to content

Commit d485d1e

Browse files
committed
Fix leaking SOCKS connection when cancelling before SSH client is ready
1 parent f602b08 commit d485d1e

2 files changed

Lines changed: 36 additions & 2 deletions

File tree

‎src/SshSocksConnector.php‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,12 @@ public function connect($uri)
148148
throw new \RuntimeException('Connection to ' . $uri . ' cancelled while waiting for SSH client');
149149
});
150150

151-
$this->listen->then(function () use ($uri, $that, $socks, $deferred, &$connecting) {
152-
// SSH client process started => start SOCKS connection
151+
$this->listen->then(function () use ($uri, $that, $socks, $deferred, &$connecting, &$cancelled) {
152+
// SSH client process started => start SOCKS connection (unless connection attempt has already been cancelled)
153+
if ($cancelled) {
154+
return;
155+
}
156+
153157
$connecting = $socks->connect($uri)->then(function (ConnectionInterface $connection) use ($that, $deferred) {
154158
// connection to SOCKS server successful => consider idle when connection closes again
155159
$connection->on('close', function () use ($that) {

‎tests/IntegrationSshSocksConnectorTest.php‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,36 @@ public function testConnectCancellationWillRejectWithExceptionWhenProcessExitsBe
161161
Loop::run();
162162
}
163163

164+
public function testConnectCancellationWillNotInvokeSocksConnectorWhenProcessBecomesReadyForOtherPendingConnection()
165+
{
166+
$connector = new SshSocksConnector('host');
167+
168+
$ref = new \ReflectionProperty($connector, 'cmd');
169+
if (PHP_VERSION_ID < 80100) {
170+
$ref->setAccessible(true);
171+
}
172+
$ref->setValue($connector, 'echo "debug1: channel 0: new [port listener]" >&2; exec sleep 10; #');
173+
174+
$socks = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock();
175+
$socks->expects($this->once())->method('connect')->with('example.com:81')->willReturn(\React\Promise\reject(new \RuntimeException('Connection refused')));
176+
177+
$ref = new \ReflectionProperty($connector, 'socks');
178+
if (PHP_VERSION_ID < 80100) {
179+
$ref->setAccessible(true);
180+
}
181+
$ref->setValue($connector, $socks);
182+
183+
$first = $connector->connect('example.com:80');
184+
$first->cancel();
185+
186+
$first->then(null, $this->expectCallableOnceWith($this->isInstanceOf('RuntimeException')));
187+
188+
$second = $connector->connect('example.com:81');
189+
$second->then(null, $this->expectCallableOnceWith($this->isInstanceOf('RuntimeException')));
190+
191+
Loop::run();
192+
}
193+
164194
public function testConnectWillTerminateNewProcessWhenPreviousProcessExitsLateAfterIdleTimeout()
165195
{
166196
$connector = new SshSocksConnector('host');

0 commit comments

Comments
 (0)