fsockopen

@see http://php.net/fsockopen
@param string $hostname
@param int $port
@param int $errno
@param string $errstr
@param float $timeout
@return resource
771726
public function fsockopen($hostname, $port = -1, &$errno = 0, &$errstr = '', $timeout = null)
    {
        $this->handle = fsockopen($hostname, $port, $errno, $errstr, (is_null($timeout) ? ini_get("default_socket_timeout") : $timeout));

        if ($this->handle != false && $errno === 0 && $errstr === '') {
            return $this->handle;
        }
        return false;
    }
1226270
public function setConnectTimeout($timeout)
    {
        assert(is_int($timeout));
        assert($timeout >= 0);
        $this->_timeout = $timeout;

        return $this;
    }
1150264
public function connect($host = null, $port = null, $user = null, $pass = null)
    {
        $rcube = rcube::get_instance();

        // disconnect/destroy $this->conn
        $this->disconnect();

        // reset error/response var
        $this->error = $this->response = null;

        // let plugins alter smtp connection config
        $CONFIG = $rcube->plugins->exec_hook('smtp_connect', array(
            'smtp_server'    => $host ?: $rcube->config->get('smtp_server'),
            'smtp_port'      => $port ?: $rcube->config->get('smtp_port', 25),
            'smtp_user'      => $user !== null ? $user : $rcube->config->get('smtp_user'),
            'smtp_pass'      => $pass !== null ? $pass : $rcube->config->get('smtp_pass'),
            'smtp_auth_cid'  => $rcube->config->get('smtp_auth_cid'),
            'smtp_auth_pw'   => $rcube->config->get('smtp_auth_pw'),
            'smtp_auth_type' => $rcube->config->get('smtp_auth_type'),
            'smtp_helo_host' => $rcube->config->get('smtp_helo_host'),
            'smtp_timeout'   => $rcube->config->get('smtp_timeout'),
            'smtp_conn_options'   => $rcube->config->get('smtp_conn_options'),
            'smtp_auth_callbacks' => array(),
        ));

        $smtp_host = rcube_utils::parse_host($CONFIG['smtp_server']);
        // when called from Installer it's possible to have empty $smtp_host here
        if (!$smtp_host) $smtp_host = 'localhost';
        $smtp_port     = is_numeric($CONFIG['smtp_port']) ? $CONFIG['smtp_port'] : 25;
        $smtp_host_url = parse_url($smtp_host);

        // overwrite port
        if (isset($smtp_host_url['host']) && isset($smtp_host_url['port'])) {
            $smtp_host = $smtp_host_url['host'];
            $smtp_port = $smtp_host_url['port'];
        }

        // re-write smtp host
        if (isset($smtp_host_url['host']) && isset($smtp_host_url['scheme'])) {
            $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
        }

        // remove TLS prefix and set flag for use in Net_SMTP::auth()
        if (preg_match('#^tls://#i', $smtp_host)) {
            $smtp_host = preg_replace('#^tls://#i', '', $smtp_host);
            $use_tls   = true;
        }

        // Handle per-host socket options
        rcube_utils::parse_socket_options($CONFIG['smtp_conn_options'], $smtp_host);

        if (!empty($CONFIG['smtp_helo_host'])) {
            $helo_host = $CONFIG['smtp_helo_host'];
        }
        else if (!empty($_SERVER['SERVER_NAME'])) {
            $helo_host = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
        }
        else {
            $helo_host = 'localhost';
        }

        // IDNA Support
        $smtp_host = rcube_utils::idn_to_ascii($smtp_host);

        $this->conn = new Net_SMTP($smtp_host, $smtp_port, $helo_host, false, 0, $CONFIG['smtp_conn_options']);

        if ($rcube->config->get('smtp_debug')) {
            $this->conn->setDebug(true, array($this, 'debug_handler'));
            $this->anonymize_log = 0;
        }

        // register authentication methods
        if (!empty($CONFIG['smtp_auth_callbacks']) && method_exists($this->conn, 'setAuthMethod')) {
            foreach ($CONFIG['smtp_auth_callbacks'] as $callback) {
                $this->conn->setAuthMethod($callback['name'], $callback['function'],
                    isset($callback['prepend']) ? $callback['prepend'] : true);
            }
        }

        // try to connect to server and exit on failure
        $result = $this->conn->connect($CONFIG['smtp_timeout']);

        if (is_a($result, 'PEAR_Error')) {
            $this->response[] = "Connection failed: " . $result->getMessage();

            list($code,) = $this->conn->getResponse();
            $this->error = array('label' => 'smtpconnerror', 'vars' => array('code' => $code));
            $this->conn  = null;

            return false;
        }

        // workaround for timeout bug in Net_SMTP 1.5.[0-1] (#1487843)
        if (method_exists($this->conn, 'setTimeout')
            && ($timeout = ini_get('default_socket_timeout'))
        ) {
            $this->conn->setTimeout($timeout);
        }

        $smtp_user = str_replace('%u', $rcube->get_user_name(), $CONFIG['smtp_user']);
        $smtp_pass = str_replace('%p', $rcube->get_user_password(), $CONFIG['smtp_pass']);
        $smtp_auth_type = $CONFIG['smtp_auth_type'] ?: null;

        if (!empty($CONFIG['smtp_auth_cid'])) {
            $smtp_authz = $smtp_user;
            $smtp_user  = $CONFIG['smtp_auth_cid'];
            $smtp_pass  = $CONFIG['smtp_auth_pw'];
        }

        // attempt to authenticate to the SMTP server
        if ($smtp_user && $smtp_pass) {
            // IDNA Support
            if (strpos($smtp_user, '@')) {
                $smtp_user = rcube_utils::idn_to_ascii($smtp_user);
            }

            $result = $this->conn->auth($smtp_user, $smtp_pass, $smtp_auth_type, $use_tls, $smtp_authz);

            if (is_a($result, 'PEAR_Error')) {
                list($code,) = $this->conn->getResponse();
                $this->error = array('label' => 'smtpautherror', 'vars' => array('code' => $code));
                $this->response[] = 'Authentication failure: ' . $result->getMessage()
                    . ' (Code: ' . $result->getCode() . ')';

                $this->reset();
                $this->disconnect();

                return false;
            }
        }

        return true;
    }
1180852
private function establishConnection($host, $port, $timeout)
    {
        $deferred = new Deferred();

        $timer = $this->loop->addTimer(
            $timeout,
            function () use ($deferred, $timeout) {
                $exception = new \RuntimeException(sprintf('Connection timed out after %d seconds.', $timeout));
                $deferred->reject($exception);
            }
        );

        $this->connector->connect($host.':'.$port)
            ->always(function () use ($timer) {
                $this->loop->cancelTimer($timer);
            })
            ->then(function (DuplexStreamInterface $stream) use ($deferred) {
                $stream->on('data', function ($data) {
                    $this->handleReceive($data);
                });

                $stream->on('close', function () {
                    $this->handleClose();
                });

                $stream->on('error', function (\Exception $e) {
                    $this->handleError($e);
                });

                $deferred->resolve($stream);
            })
            ->otherwise(function (\Exception $e) use ($deferred) {
                $deferred->reject($e);
            });

        return $deferred->promise();
    }
185705
public static function GetSSLCertificateParameters ($domain_name, $port = 443, $timeout = 30) {
		$sp = stream_socket_client(
			sprintf('ssl://%s:%d', $domain_name, $port),
			$errno,
			$errstr,
			$timeout,
			\STREAM_CLIENT_CONNECT,
			stream_context_create(['ssl' => [
				'verify_peer'				=> false,
				'verify_peer_name'			=> false,
				'allow_self_signed'			=> true,
				'capture_peer_cert'			=> true,
				'capture_peer_cert_chain'	=> true,
				'SNI_enabled'				=> true
			]])
		);

		if (!is_resource($sp)) {
			return false;
		}

		$parameters = stream_context_get_params($sp);
		fclose($sp);

		if (!isset($parameters['options']['ssl']['peer_certificate'])) {
			return false;
		}
		$peer_certificate = openssl_x509_parse($parameters['options']['ssl']['peer_certificate']);

		$peer_certificate_chain_list = [];
		foreach ($parameters['options']['ssl']['peer_certificate_chain'] as $peer_certificate_chain) {
			$peer_certificate_chain_list[] = openssl_x509_parse($peer_certificate_chain);
		}

		return [
			'peer_certificate'				=> $peer_certificate,
			'peer_certificate_chain_list'	=> $peer_certificate_chain_list,
			'self_signed_certificate'		=> $peer_certificate['issuer']['CN'] === $domain_name,
		];
	}
771620
public static NetworkPort remotePort(String hostname, int port){
        return new RemoteNetworkPort(hostname, port, NetworkPort.Type.TCP);
    }
597293
private function pingFsockopen() {
    $start = microtime(true);
    // fsockopen prints a bunch of errors if a host is unreachable. Hide those
    // irrelevant errors and deal with the results instead.
    $fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
    if (!$fp) {
      $latency = false;
    }
    else {
      $latency = microtime(true) - $start;
      $latency = round($latency * 1000);
    }
    return $latency;
  }
236781
public function call($hostname, $source, $destination, array $config = [])
    {
        $defaults = [
            'timeout' => null,
            'options' => [],
        ];
        $config = array_merge($defaults, $config);

        $escapedSource = escapeshellarg($source);
        $escapedDestination = escapeshellarg($destination);
        $rsync = "rsync -azP " . implode(' ', $config['options']) . " $escapedSource $escapedDestination";

        $this->pop->command($hostname, $rsync);

        $process = new Process($rsync);
        $process
            ->setTimeout($config['timeout'])
            ->mustRun($this->pop->callback($hostname));
    }
4079
public function setServerParams($host, $port = 11211, $timeout = NULL, $retry_interval = false, $status = NULL, $failure_callback = NULL)
    {
    }
634929
protected function fsockopen()
    {
        return @fsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout);
    }
851056
public function moveToServer(string $host, $port = 6379, int $db = 0, int $timeout = 0, bool $replace = true): bool
    {
        return $this->handle->migrate($host, $port, $this->name, $db, $timeout, false, $replace);
    }
1060670
protected function createConnection($host, $port, $methods, $callbacks)
    {
        return @ssh2_connect($host, $port, $methods, $callbacks);
    }
518947
private function pingFsockopen() {
        $start = microtime(true);

        if (strtolower($this->typeCon) != 'tcp') {
            $this->setPort(7);
            $this->setHost("udp://$this->host");
        }

        // fsockopen prints a bunch of errors if a host is unreachable. Hide those
        // irrelevant errors and deal with the results instead.
        $fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
        if (!$fp) {
            $latency = false;
        } else {
            $latency = microtime(true) - $start;
            $latency = round($latency * 1000);
        }
        return $latency;
    }
496231
public function connect($host = '127.0.0.1', $port = 21)
	{
		$errno = null;
		$err   = null;

		// If already connected, return
		if (\is_resource($this->conn))
		{
			return true;
		}

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			$this->conn = @ftp_connect($host, $port, $this->timeout);

			if ($this->conn === false)
			{
				throw new FilesystemException(sprintf('%1$s: Could not connect to host " %2$s " on port " %3$s "', __METHOD__, $host, $port));
			}

			// Set the timeout for this connection
			ftp_set_option($this->conn, FTP_TIMEOUT_SEC, $this->timeout);

			return true;
		}

		// Connect to the FTP server.
		$this->conn = @ fsockopen($host, $port, $errno, $err, $this->timeout);

		if (!$this->conn)
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Could not connect to host " %2$s " on port " %3$s ". Socket error number: %4$s and error message: %5$s',
					__METHOD__,
					$host,
					$port,
					$errno,
					$err
				)
			);
		}

		// Set the timeout for this connection
		socket_set_timeout($this->conn, $this->timeout, 0);

		// Check for welcome response code
		if (!$this->_verifyResponse(220))
		{
			throw new FilesystemException(sprintf('%1$s: Bad response. Server response: %2$s [Expected: 220]', __METHOD__, $this->response));
		}

		return true;
	}
731984
public function connect($hostname, $port = '389')
    {
        $protocol = $this::PROTOCOL;

        if ($this->isUsingSSL()) {
            $protocol = $this::PROTOCOL_SSL;
        }

        return $this->connection = ldap_connect($protocol.$hostname, $port);
    }
454738
function Net_SFTP($host, $port = 22, $timeout = 10)
    {
        parent::Net_SSH2($host, $port, $timeout);
        $this->packet_types = array(
            1  => 'NET_SFTP_INIT',
            2  => 'NET_SFTP_VERSION',
            /* the format of SSH_FXP_OPEN changed between SFTPv4 and SFTPv5+:
                   SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.1
               pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 */
            3  => 'NET_SFTP_OPEN',
            4  => 'NET_SFTP_CLOSE',
            5  => 'NET_SFTP_READ',
            6  => 'NET_SFTP_WRITE',
            7  => 'NET_SFTP_LSTAT',
            9  => 'NET_SFTP_SETSTAT',
            11 => 'NET_SFTP_OPENDIR',
            12 => 'NET_SFTP_READDIR',
            13 => 'NET_SFTP_REMOVE',
            14 => 'NET_SFTP_MKDIR',
            15 => 'NET_SFTP_RMDIR',
            16 => 'NET_SFTP_REALPATH',
            17 => 'NET_SFTP_STAT',
            /* the format of SSH_FXP_RENAME changed between SFTPv4 and SFTPv5+:
                   SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
               pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.5 */
            18 => 'NET_SFTP_RENAME',

            101=> 'NET_SFTP_STATUS',
            102=> 'NET_SFTP_HANDLE',
            /* the format of SSH_FXP_NAME changed between SFTPv3 and SFTPv4+:
                   SFTPv4+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.4
               pre-SFTPv4 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-7 */
            103=> 'NET_SFTP_DATA',
            104=> 'NET_SFTP_NAME',
            105=> 'NET_SFTP_ATTRS',

            200=> 'NET_SFTP_EXTENDED'
        );
        $this->status_codes = array(
            0 => 'NET_SFTP_STATUS_OK',
            1 => 'NET_SFTP_STATUS_EOF',
            2 => 'NET_SFTP_STATUS_NO_SUCH_FILE',
            3 => 'NET_SFTP_STATUS_PERMISSION_DENIED',
            4 => 'NET_SFTP_STATUS_FAILURE',
            5 => 'NET_SFTP_STATUS_BAD_MESSAGE',
            6 => 'NET_SFTP_STATUS_NO_CONNECTION',
            7 => 'NET_SFTP_STATUS_CONNECTION_LOST',
            8 => 'NET_SFTP_STATUS_OP_UNSUPPORTED'
        );
        // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-7.1
        // the order, in this case, matters quite a lot - see Net_SFTP::_parseAttributes() to understand why
        $this->attributes = array(
            0x00000001 => 'NET_SFTP_ATTR_SIZE',
            0x00000002 => 'NET_SFTP_ATTR_UIDGID', // defined in SFTPv3, removed in SFTPv4+
            0x00000004 => 'NET_SFTP_ATTR_PERMISSIONS',
            0x00000008 => 'NET_SFTP_ATTR_ACCESSTIME',
            // 0x80000000 will yield a floating point on 32-bit systems and converting floating points to integers
            // yields inconsistent behavior depending on how php is compiled.  so we left shift -1 (which, in 
            // two's compliment, consists of all 1 bits) by 31.  on 64-bit systems this'll yield 0xFFFFFFFF80000000.
            // that's not a problem, however, and 'anded' and a 32-bit number, as all the leading 1 bits are ignored.
              -1 << 31 => 'NET_SFTP_ATTR_EXTENDED'
        );
        // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3
        // the flag definitions change somewhat in SFTPv5+.  if SFTPv5+ support is added to this library, maybe name
        // the array for that $this->open5_flags and similarily alter the constant names.
        $this->open_flags = array(
            0x00000001 => 'NET_SFTP_OPEN_READ',
            0x00000002 => 'NET_SFTP_OPEN_WRITE',
            0x00000004 => 'NET_SFTP_OPEN_APPEND',
            0x00000008 => 'NET_SFTP_OPEN_CREATE',
            0x00000010 => 'NET_SFTP_OPEN_TRUNCATE'
        );
        // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2
        // see Net_SFTP::_parseLongname() for an explanation
        $this->file_types = array(
            1 => 'NET_SFTP_TYPE_REGULAR',
            2 => 'NET_SFTP_TYPE_DIRECTORY',
            3 => 'NET_SFTP_TYPE_SYMLINK',
            4 => 'NET_SFTP_TYPE_SPECIAL'
        );
        $this->_define_array(
            $this->packet_types,
            $this->status_codes,
            $this->attributes,
            $this->open_flags,
            $this->file_types
        );
    }
246359
function set_timeout($timeout_recv, $timeout_send)
    {
        $_timeout_recv_sec = (int)$timeout_recv;
        $_timeout_send_sec = (int)$timeout_send;

        $this->timeout_recv = $timeout_recv;
        $this->timeout_send = $timeout_send;

        $_timeout_recv = array(
            'sec' => $_timeout_recv_sec,
            'usec' => (int)(($timeout_recv - $_timeout_recv_sec) * 1000 * 1000)
        );
        $_timeout_send = array(
            'sec' => $_timeout_send_sec,
            'usec' => (int)(($timeout_send - $_timeout_send_sec) * 1000 * 1000)
        );

        $this->setopt(SO_RCVTIMEO, $_timeout_recv);
        $this->setopt(SO_SNDTIMEO, $_timeout_send);
    }