From 33a97391bc2b01ed77d2f62990d301fae8856475 Mon Sep 17 00:00:00 2001 From: terrafrost Date: Fri, 17 Jul 2015 12:30:44 -0500 Subject: [PATCH] SSH2: make it so you can connect using open sockets --- phpseclib/Net/SSH2.php | 41 ++++++++++++++++++++----------- tests/Functional/Net/SSH2Test.php | 13 ++++++++++ 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/phpseclib/Net/SSH2.php b/phpseclib/Net/SSH2.php index 28d7bfb9..daa77557 100644 --- a/phpseclib/Net/SSH2.php +++ b/phpseclib/Net/SSH2.php @@ -874,7 +874,9 @@ class Net_SSH2 /** * Default Constructor. * - * @param String $host + * $host can either be a string, representing the host, or a stream resource. + * + * @param Mixed $host * @param optional Integer $port * @param optional Integer $timeout * @see Net_SSH2::login() @@ -978,9 +980,16 @@ class Net_SSH2 34 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST') ); - $this->host = $host; - $this->port = $port; - $this->timeout = $timeout; + if (is_resource($host)) { + $this->fsock = $host; + return; + } + + if (is_string($host)) { + $this->host = $host; + $this->port = $port; + $this->timeout = $timeout; + } } /** @@ -1017,19 +1026,21 @@ class Net_SSH2 $this->last_packet = strtok(microtime(), ' ') + strtok(''); // == microtime(true) in PHP5 - $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 - $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout); - if (!$this->fsock) { - user_error(rtrim("Cannot connect to $host. Error $errno. $errstr")); - return false; - } - $elapsed = strtok(microtime(), ' ') + strtok('') - $start; + if (!is_resource($this->fsock)) { + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout); + if (!$this->fsock) { + user_error(rtrim("Cannot connect to $host. Error $errno. $errstr")); + return false; + } + $elapsed = strtok(microtime(), ' ') + strtok('') - $start; - $this->curTimeout-= $elapsed; + $this->curTimeout-= $elapsed; - if ($this->curTimeout <= 0) { - $this->is_timeout = true; - return false; + if ($this->curTimeout <= 0) { + $this->is_timeout = true; + return false; + } } /* According to the SSH2 specs, diff --git a/tests/Functional/Net/SSH2Test.php b/tests/Functional/Net/SSH2Test.php index f6ed5252..c8917de5 100644 --- a/tests/Functional/Net/SSH2Test.php +++ b/tests/Functional/Net/SSH2Test.php @@ -85,4 +85,17 @@ class Functional_Net_SSH2Test extends PhpseclibFunctionalTestCase $this->assertInternalType('string', $ssh->getServerPublicHostKey()); } + + public function testOpenSocketConnect() + { + $fsock = fsockopen($this->getEnv('SSH_HOSTNAME'), 22); + $ssh = new Net_SSH2($fsock); + + $username = $this->getEnv('SSH_USERNAME'); + $password = $this->getEnv('SSH_PASSWORD'); + $this->assertTrue( + $ssh->login($username, $password), + 'SSH2 login using an open socket failed.' + ); + } }