Skip to content

Commit

Permalink
SSH2: add setKeepAlive() method
Browse files Browse the repository at this point in the history
  • Loading branch information
terrafrost committed Sep 28, 2020
1 parent 2ae6834 commit 96c4c3b
Showing 1 changed file with 43 additions and 2 deletions.
45 changes: 43 additions & 2 deletions phpseclib/Net/SSH2.php
Expand Up @@ -692,6 +692,14 @@ class Net_SSH2
*/
var $curTimeout;

/**
* Keep Alive Interval
*
* @see self::setKeepAlive()
* @access private
*/
var $keepAlive;

/**
* Real-time log file pointer
*
Expand Down Expand Up @@ -2691,6 +2699,19 @@ function setTimeout($timeout)
$this->timeout = $this->curTimeout = $timeout;
}

/**
* Set Keep Alive
*
* Sends an SSH2_MSG_IGNORE message every x seconds, if x is a positive non-zero number.
*
* @param mixed $timeout
* @access public
*/
function setKeepAlive($interval)
{
$this->keepAlive = $interval;
}

/**
* Get the output from stdError
*
Expand Down Expand Up @@ -3684,8 +3705,15 @@ function _get_channel_packet($client_channel, $skip_extended = false)
$read = array($this->fsock);
$write = $except = null;

if (!$this->curTimeout) {
@stream_select($read, $write, $except, null);
if ($this->curTimeout <= 0) {
if ($this->keepAlive <= 0) {
@stream_select($read, $write, $except, null);
} else {
if (!@stream_select($read, $write, $except, $this->keepAlive) && !count($read)) {
$this->_send_binary_packet(pack('CN', NET_SSH2_MSG_IGNORE, 0));
continue;
}
}
} else {
if ($this->curTimeout < 0) {
$this->is_timeout = true;
Expand All @@ -3696,8 +3724,21 @@ function _get_channel_packet($client_channel, $skip_extended = false)
$write = $except = null;

$start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838

if ($this->keepAlive > 0 && $this->keepAlive < $this->curTimeout) {
if (!@stream_select($read, $write, $except, $this->keepAlive) && !count($read)) {
$this->_send_binary_packet(pack('CN', NET_SSH2_MSG_IGNORE, 0));
$elapsed = strtok(microtime(), ' ') + strtok('') - $start;
$this->curTimeout-= $elapsed;
continue;
}
$elapsed = strtok(microtime(), ' ') + strtok('') - $start;
$this->curTimeout-= $elapsed;
}

$sec = floor($this->curTimeout);
$usec = 1000000 * ($this->curTimeout - $sec);

// on windows this returns a "Warning: Invalid CRT parameters detected" error
if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
$this->is_timeout = true;
Expand Down

1 comment on commit 96c4c3b

@terrafrost
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #1529

Please sign in to comment.