Connect to ftp server

@return bool
@author Dmitry (dio) Levashov
775240
protected function connect() {
		if (!($this->connect = ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {
			return $this->setError('Unable to connect to FTP server '.$this->options['host']);
		}
		if (!ftp_login($this->connect, $this->options['user'], $this->options['pass'])) {
			$this->umount();
			return $this->setError('Unable to login into '.$this->options['host']);
		}
		
		// try switch utf8 mode
		if ($this->encoding) {
			@ftp_exec($this->connect, 'OPTS UTF8 OFF');
		} else {
			@ftp_exec($this->connect, 'OPTS UTF8 ON' );
		}
		
		// switch off extended passive mode - may be usefull for some servers
		@ftp_exec($this->connect, 'epsv4 off' );
		// enter passive mode if required
		ftp_pasv($this->connect, $this->options['mode'] == 'passive');

		// enter root folder
		if (!ftp_chdir($this->connect, $this->root) 
		|| $this->root != ftp_pwd($this->connect)) {
			$this->umount();
			return $this->setError('Unable to open root folder.');
		}
		
		// check for MLST support
		$features = ftp_raw($this->connect, 'FEAT');
		if (!is_array($features)) {
			$this->umount();
			return $this->setError('Server does not support command FEAT.');
		}

		foreach ($features as $feat) {
			if (strpos(trim($feat), 'MLST') === 0) {
				return true;
			}
		}
		
		return $this->setError('Server does not support command MLST.');
	}
1233816
public function isSslConnection()
	{
		$serverSSLVar = $this->input->server->getString('HTTPS', '');

		if (!empty($serverSSLVar) && strtolower($serverSSLVar) !== 'off')
		{
			return true;
		}

		$serverForwarderProtoVar = $this->input->server->getString('HTTP_X_FORWARDED_PROTO', '');

		return !empty($serverForwarderProtoVar) && strtolower($serverForwarderProtoVar) === 'https';
	}
717934
public function connect( $host, $port = 21, $timeout = 10 )
	{
		$resource	= @ftp_connect( $host, $port, $timeout );
		if( !$resource )
			return FALSE;
		$this->host	= $host;
		$this->port	= $port;
		$this->resource	= $resource;
		return TRUE;
	}
988937
public function connect() {
        $host = $this->getAuthenticator()->getHost();
        $port = $this->getAuthenticator()->getPort();
        $this->setConnection(ssh2_connect($host, $port));
        if (false === $this->getConnection()) {
            throw $this->newFTPException("connection failed");
        }
        return $this;
    }
1162684
function connect($clean = true)
    {

        // Don't do anything, if server address is not set
        if(!$this->serverAddress) {
            return false;
        }

        // Is encryption enabled?
        if($this->connMethod!="tcp") {
            $socketContextOptions = [ "ssl" => [] ];
            $socketContextOptions["ssl"]["verify_peer_name"] = $this->verifyPeerName;

            if($this->caFile) {
                $socketContextOptions["ssl"]["cafile"]=$this->caFile;
            }

            if($this->clientCrt) {
                $socketContextOptions["ssl"]["local_cert"]=$this->clientCrt;
            }

            if ($this->clientCrt && $this->clientKey) {
                $socketContextOptions["ssl"]["local_pk"]=$this->clientKey;
            }

            $socketContext = stream_context_create($socketContextOptions);
            $host = $this->connMethod . "://" . $this->serverAddress . ":" . $this->serverPort;

            $this->socket = stream_socket_client(
                $host, $errno, $errstr, 60, STREAM_CLIENT_CONNECT, $socketContext);

            $this->debugMessage("Connecting to: ".$host);
        } else {
            $host = $this->connMethod . "://" . $this->serverAddress . ":" . $this->serverPort;
            $this->socket = stream_socket_client(
                $host, $errno, $errstr, 60, STREAM_CLIENT_CONNECT );
            $this->debugMessage("Connecting to: ".$host);
        }

        //
        if(!$this->socket) {
            $this->socket = null;
            $this->debugMessage("Connection failed.. $errno , $errstr");
            return false;
        }

        //
        stream_set_timeout($this->socket, 10);
        stream_set_blocking($this->socket, false);

        $bytes = 0;
        $buffer = "";

        // ------------------------------------
        // Calculate connect flags

        $var = $clean?2:0;
/*
        if($this->will != NULL)
        {
            $var += 4;                              // Set will flag
            $var += ($this->will['qos'] << 3);      // Set will qos

            if($this->will['retain'])
                $var += 32;                     // Set will retain
        }
*/

        if($this->authPass != NULL) {
            $var += 64;
        }

        if($this->authUser != NULL) {
            $var += 128;
        }

        // ------------------------------------
        // Create CONNECT packet (for MQTT 3.1.1 protocol)

        $buffer .= $this->convertString("MQTT", $bytes);

        $buffer .= chr(0x04);   // Protocol level
        $bytes++;

        $buffer .= chr($var);   // Connect flags
        $bytes++;

        $buffer .= chr($this->keepAlive >> 8);  // Keepalive (MSB)
        $bytes++;

        $buffer .= chr($this->keepAlive & 0xff);    // Keepalive (LSB)
        $bytes++;

        $buffer .= $this->convertString($this->clientID,$bytes);

        //Adding will to payload
        /*
        if($this->will != NULL){
            $buffer .= $this->strwritestring($this->will['topic'],$bytes);
            $buffer .= $this->strwritestring($this->will['content'],$bytes);
        }
        */

        if($this->authUser) {
            $buffer .= $this->convertString($this->authUser,$bytes);
        }

        if($this->authPass) {
            $buffer .= $this->convertString($this->authPass,$bytes);
        }

        $header = $this->createHeader( 0x10 , $bytes );
        fwrite($this->socket, $header, strlen($header));
        fwrite($this->socket, $buffer);

        // Wait for CONNACK packet
        $string = $this->readBytes(4, false);
        if(strlen($string)!=4) {
            $this->debugMessage("Connection failed! Server gave unexpected response (".strlen($string)." bytes).");
            return false;
        }

        if(ord($string{0}) == 0x20 && $string{3} == chr(0)) {
            $this->debugMessage("Connected to MQTT");
        } else {
            $msg = sprintf("Connection failed! Error: 0x%02x 0x%02x",
                ord($string{0}),ord($string{3}) );
            $this->debugMessage($msg);
            return false;
        }

        $this->timeSincePingReq = time();
        $this->timeSincePingResp = time();

        return true;
    }
321352
public function connect()
    {
        if ($this->_connection) {
            return true;
        }
        $config = $this->_config;

        if ($config['timezone'] === 'UTC') {
            $config['timezone'] = '+0:00';
        }

        if (!empty($config['timezone'])) {
            $config['init'][] = sprintf("SET time_zone = '%s'", $config['timezone']);
        }
        if (!empty($config['encoding'])) {
            $config['init'][] = sprintf('SET NAMES %s', $config['encoding']);
        }

        $config['flags'] += [
            PDO::ATTR_PERSISTENT => $config['persistent'],
            PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ];

        if (!empty($config['ssl_key']) && !empty($config['ssl_cert'])) {
            $config['flags'][PDO::MYSQL_ATTR_SSL_KEY] = $config['ssl_key'];
            $config['flags'][PDO::MYSQL_ATTR_SSL_CERT] = $config['ssl_cert'];
        }
        if (!empty($config['ssl_ca'])) {
            $config['flags'][PDO::MYSQL_ATTR_SSL_CA] = $config['ssl_ca'];
        }

        if (empty($config['unix_socket'])) {
            $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']};charset={$config['encoding']}";
        } else {
            $dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
        }

        $this->_connect($dsn, $config);

        if (!empty($config['init'])) {
            $connection = $this->getConnection();
            foreach ((array)$config['init'] as $command) {
                $connection->exec($command);
            }
        }

        return true;
    }
1301502
public function connect()
    {
        if ($this->_connection) {
            return true;
        }
        $config = $this->_config;
        $config['flags'] += [
            PDO::ATTR_PERSISTENT => $config['persistent'],
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ];
        if (empty($config['unix_socket'])) {
            $dsn = "pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
        } else {
            $dsn = "pgsql:dbname={$config['database']}";
        }

        $this->_connect($dsn, $config);
        $this->_connection = $connection = $this->getConnection();
        if (!empty($config['encoding'])) {
            $this->setEncoding($config['encoding']);
        }

        if (!empty($config['schema'])) {
            $this->setSchema($config['schema']);
        }

        if (!empty($config['timezone'])) {
            $config['init'][] = sprintf('SET timezone = %s', $connection->quote($config['timezone']));
        }

        foreach ($config['init'] as $command) {
            $connection->exec($command);
        }

        return true;
    }
795440
public function isConnected()
    {
        try {
            return \is_resource($this->connection) && \ftp_rawlist($this->connection, $this->getRoot()) !== false;
        } catch (\ErrorException $e) {
            if (\strpos($e->getMessage(), 'ftp_rawlist') === false) {
                throw $e;
            }

            return false;
        }
    }
438251
public function connect()
    {
        $socket = $this->createSocket(
            $this->connection->getHostname(),
            $this->connection->getPort(),
            $this->throttle
        );

        $this->setSocket($socket);
    }
648118
private function connect()
    {
        if (!$this->_sock) {
            if ($this->_persistentSocket) {
                $this->_sock = pfsockopen($this->_host, $this->_port, $errno, $errstr, $this->_connectTimeout/1000);
            } else {
                $this->_sock = fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_connectTimeout/1000);
            }

            if (!$this->_sock) {
                throw new \Exception('Unable to connect to FastCGI application: ' . $errstr);
            }

            if (!$this->set_ms_timeout($this->_readWriteTimeout)) {
                throw new \Exception('Unable to set timeout on socket');
            }
        }
    }
629382
protected function connectSftp()
    {
        if ( ! $this->connected) return false;

        $this->ftpConnection = ssh2_sftp($this->connection);

        return true;
    }
1123143
function _connect()
    {
        if ($this->bitmap & self::MASK_CONSTRUCTOR) {
            return false;
        }

        $this->bitmap |= self::MASK_CONSTRUCTOR;

        $this->curTimeout = $this->timeout;

        $this->last_packet = microtime(true);

        if (!is_resource($this->fsock)) {
            $start = microtime(true);
            // with stream_select a timeout of 0 means that no timeout takes place;
            // with fsockopen a timeout of 0 means that you instantly timeout
            // to resolve this incompatibility a timeout of 100,000 will be used for fsockopen if timeout is 0
            $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout == 0 ? 100000 : $this->curTimeout);
            if (!$this->fsock) {
                $host = $this->host . ':' . $this->port;
                user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"));
                return false;
            }
            $elapsed = microtime(true) - $start;

            $this->curTimeout-= $elapsed;

            if ($this->curTimeout <= 0) {
                $this->is_timeout = true;
                return false;
            }
        }

        $this->identifier = $this->_generate_identifier();

        if ($this->send_id_string_first) {
            fputs($this->fsock, $this->identifier . "\r\n");
        }

        /* According to the SSH2 specs,

          "The server MAY send other lines of data before sending the version
           string.  Each line SHOULD be terminated by a Carriage Return and Line
           Feed.  Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
           in ISO-10646 UTF-8 [RFC3629] (language is not specified).  Clients
           MUST be able to process such lines." */
        $data = '';
        while (!feof($this->fsock) && !preg_match('#(.*)^(SSH-(\d\.\d+).*)#ms', $data, $matches)) {
            $line = '';
            while (true) {
                if ($this->curTimeout) {
                    if ($this->curTimeout < 0) {
                        $this->is_timeout = true;
                        return false;
                    }
                    $read = array($this->fsock);
                    $write = $except = null;
                    $start = microtime(true);
                    $sec = floor($this->curTimeout);
                    $usec = 1000000 * ($this->curTimeout - $sec);
                    // on windows this returns a "Warning: Invalid CRT parameters detected" error
                    // the !count() is done as a workaround for <https://bugs.php.net/42682>
                    if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
                        $this->is_timeout = true;
                        return false;
                    }
                    $elapsed = microtime(true) - $start;
                    $this->curTimeout-= $elapsed;
                }

                $temp = stream_get_line($this->fsock, 255, "\n");
                if (strlen($temp) == 255) {
                    continue;
                }

                $line.= "$temp\n";

                // quoting RFC4253, "Implementers who wish to maintain
                // compatibility with older, undocumented versions of this protocol may
                // want to process the identification string without expecting the
                // presence of the carriage return character for reasons described in
                // Section 5 of this document."

                //if (substr($line, -2) == "\r\n") {
                //    break;
                //}

                break;
            }

            $data.= $line;
        }

        if (feof($this->fsock)) {
            user_error('Connection closed by server');
            return false;
        }

        $extra = $matches[1];

        if (defined('NET_SSH2_LOGGING')) {
            $this->_append_log('<-', $matches[0]);
            $this->_append_log('->', $this->identifier . "\r\n");
        }

        $this->server_identifier = trim($temp, "\r\n");
        if (strlen($extra)) {
            $this->errors[] = utf8_decode($data);
        }

        if (version_compare($matches[3], '1.99', '<')) {
            user_error("Cannot connect to SSH $matches[3] servers");
            return false;
        }

        if (!$this->send_id_string_first) {
            fputs($this->fsock, $this->identifier . "\r\n");
        }

        if (!$this->send_kex_first) {
            $response = $this->_get_binary_packet();
            if ($response === false) {
                user_error('Connection closed by server');
                return false;
            }

            if (!strlen($response) || ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
                user_error('Expected SSH_MSG_KEXINIT');
                return false;
            }

            if (!$this->_key_exchange($response)) {
                return false;
            }
        }

        if ($this->send_kex_first && !$this->_key_exchange()) {
            return false;
        }

        $this->bitmap|= self::MASK_CONNECTED;

        return true;
    }
940269
public function connect()
    {
        if ($this->isConnected) {
            return false;
        }

        if (!$this->pdo) {
            $this->beforeConnect && call_user_func($this->beforeConnect, $this);

            $dsn = $this->getDsn();
            $attrs = $this->attrs + array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_STRINGIFY_FETCHES => true,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );

            try {
                $this->pdo = new PDO($dsn, $this->user, $this->password, $attrs);
            } catch (\PDOException $e) {
                $this->connectFails && call_user_func($this->connectFails, $this, $e);
                throw $e;
            }

            $this->afterConnect && call_user_func($this->afterConnect, $this, $this->pdo);
        }

        $this->isConnected = true;

        return true;
    }
22405
public function connect()
    {
        if ($this->connection) {
            $this->disconnect();
        }

        $hasProtocol = strpos($this->_config['host'], '://') !== false;
        if ($hasProtocol) {
            list($this->_config['protocol'], $this->_config['host']) = explode('://', $this->_config['host']);
        }
        $scheme = null;
        if (!empty($this->_config['protocol'])) {
            $scheme = $this->_config['protocol'] . '://';
        }

        $this->_setSslContext($this->_config['host']);
        if (!empty($this->_config['context'])) {
            $context = stream_context_create($this->_config['context']);
        } else {
            $context = stream_context_create();
        }

        $connectAs = STREAM_CLIENT_CONNECT;
        if ($this->_config['persistent']) {
            $connectAs |= STREAM_CLIENT_PERSISTENT;
        }

        set_error_handler([$this, '_connectionErrorHandler']);
        $this->connection = stream_socket_client(
            $scheme . $this->_config['host'] . ':' . $this->_config['port'],
            $errNum,
            $errStr,
            $this->_config['timeout'],
            $connectAs,
            $context
        );
        restore_error_handler();

        if (!empty($errNum) || !empty($errStr)) {
            $this->setLastError($errNum, $errStr);
            throw new SocketException($errStr, $errNum);
        }

        if (!$this->connection && $this->_connectionErrors) {
            $message = implode("\n", $this->_connectionErrors);
            throw new SocketException($message, E_WARNING);
        }

        $this->connected = is_resource($this->connection);
        if ($this->connected) {
            stream_set_timeout($this->connection, $this->_config['timeout']);
        }

        return $this->connected;
    }
357539
public function connect()
    {
        if ($this->connected) {
            return;
        }

        $this->socket = @fsockopen($this->options['hostname'], $this->options['port'], $errno, $errstr, $this->options['timeout']);
        if (!$this->socket) {
            throw new Exception\IOError($errno.' - '.$errstr);
        }

        $this->connected = true;

        return $this;
    }
1238942
public function connect()
	{
		if ($this->host == '')
		{
			return false;
		}

		if ($this->ignore_reqcert_tls)
		{
			putenv('LDAPTLS_REQCERT=never');
		}

		if ($this->ldap_debug)
		{
			ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);
		}

		$this->resource = ldap_connect($this->host, $this->port);

		if (!$this->resource)
		{
			return false;
		}

		if ($this->use_ldapV3 && !ldap_set_option($this->resource, LDAP_OPT_PROTOCOL_VERSION, 3))
		{
			return false;
		}

		if (!ldap_set_option($this->resource, LDAP_OPT_REFERRALS, (int) $this->no_referrals))
		{
			return false;
		}

		if ($this->negotiate_tls && !ldap_start_tls($this->resource))
		{
			return false;
		}

		return true;
	}
1019416
public function connect()
	{
		if ($this->ssl)
		{
			$this->connection = ftp_ssl_connect($this->getHost(), $this->getPort(), $this->getTimeout());
		}
		else
		{
			$this->connection = ftp_connect($this->getHost(), $this->getPort(), $this->getTimeout());
		}

		if (!$this->connection)
		{
			throw new RuntimeException(sprintf('Could not connect to host: %s, port: %s', $this->getHost(), $this->getPort()));
		}

		$this->login();
		$this->setConnectionPassiveMode();
		$this->setConnectionRoot();
	}