Connect to an LDAP server

@param string $host Hostname
@param int $port Port
@param array $options Additonal LDAP options
@return void
962191
public function connect($host, $port, $options)
    {
        $this->_setErrorHandler();
        $this->_connection = ldap_connect($host, $port);
        $this->_unsetErrorHandler();

        if (is_array($options)) {
            foreach ($options as $option => $value) {
                $this->setOption($option, $value);
            }
        }
    }
1261376
function ldap_connect() {
        // Cache ldap connections. They are expensive to set up
        // and can drain the TCP/IP ressources on the server if we
        // are syncing a lot of users (as we try to open a new connection
        // to get the user details). This is the least invasive way
        // to reuse existing connections without greater code surgery.
        if(!empty($this->ldapconnection)) {
            $this->ldapconns++;
            return $this->ldapconnection;
        }

        if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
                                                 $this->config->user_type, $this->config->bind_dn,
                                                 $this->config->bind_pw, $this->config->opt_deref,
                                                 $debuginfo, $this->config->start_tls)) {
            $this->ldapconns = 1;
            $this->ldapconnection = $ldapconnection;
            return $ldapconnection;
        }

        print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
    }
1338935
public function setHost($host, $port = null) {
		$this->host = (string) $host;
		
		if ($port !== null) {
			$this->setPort($port);
		}
		
		return $this;
	}
606106
public function connect($type, $host, $dbname = '', $username = null, $password = null, array $options = array())
    {
        if ($this->PDO) {
            // If this object already has a PDO object, don't attempt a new connection
            return $this;
        }

        $dsn = '';

        if ($type == 'sqlite') {
            $dsn = "{$type}:{$host}";
        } else {
            $dsn = "{$type}:host={$host};dbname={$dbname}";
        }
        $PDO = new PDO($dsn, $username, $password, $options);

        if (!$PDO) {
            return false;
        }

        $this->PDO = $PDO;

        $this->setEscapeChar();
        return $this;
    }
1178696
public function setServer($host, $port = 0)
    {
        assert(is_string($host));
        if ($host[0] == '/') {
            $this->_path = 'unix://'.$host;

            return;
        }
        if (substr($host, 0, 7) == 'unix://') {
            $this->_path = $host;

            return;
        }

        $this->_host = $host;
        if (is_int($port)) {
            if ($port) {
                $this->_port = $port;
            }
        }
        $this->_path = '';

        return $this;
    }
476018
protected function performConnect()
    {
        // Note: Connecting is briefly described in RFC1777.
        // Basicly it works like this:
        //  1. set up TCP connection
        //  2. secure that connection if neccessary
        //  3a. setLDAPVersion to tell server which version we want to speak
        //  3b. perform bind
        //  3c. setLDAPVersion to tell server which version we want to speak
        //      together with a test for supported versions
        //  4. set additional protocol options

        // Return true if we are already connected.
        if ($this->_link !== false) {
            return true;
        }

        // Connnect to the LDAP server if we are not connected.  Note that
        // with some LDAP clients, ldapperformConnect returns a link value even
        // if no connection is made.  We need to do at least one anonymous
        // bind to ensure that a connection is actually valid.
        //
        // Ref: http://www.php.net/manual/en/function.ldap-connect.php

        // Default error message in case all connection attempts
        // fail but no message is set
        $current_error = new PEAR_Error('Unknown connection error');

        // Catch empty $_host_list arrays.
        if (!is_array($this->_host_list) || count($this->_host_list) == 0) {
            $current_error = PEAR::raiseError('No Servers configured! Please '.
               'pass in an array of servers to Net_LDAP2');
            return $current_error;
        }

        // Cycle through the host list.
        foreach ($this->_host_list as $host) {

            // Ensure we have a valid string for host name
            if (is_array($host)) {
                $current_error = PEAR::raiseError('No Servers configured! '.
                   'Please pass in an one dimensional array of servers to '.
                   'Net_LDAP2! (multidimensional array detected!)');
                continue;
            }

            // Skip this host if it is known to be down.
            if (in_array($host, $this->_down_host_list)) {
                continue;
            }

            // Record the host that we are actually connecting to in case
            // we need it later.
            $this->_config['host'] = $host;

            // Attempt a connection.
            $this->_link = @ldap_connect($host, $this->_config['port']);
            if (false === $this->_link) {
                $current_error = PEAR::raiseError('Could not connect to ' .
                    $host . ':' . $this->_config['port']);
                $this->_down_host_list[] = $host;
                continue;
            }

            // If we're supposed to use TLS, do so before we try to bind,
            // as some strict servers only allow binding via secure connections
            if ($this->_config["starttls"] === true) {
                if (self::isError($msg = $this->startTLS())) {
                    $current_error           = $msg;
                    $this->_link             = false;
                    $this->_down_host_list[] = $host;
                    continue;
                }
            }

            // Try to set the configured LDAP version on the connection if LDAP
            // server needs that before binding (eg OpenLDAP).
            // This could be necessary since rfc-1777 states that the protocol version
            // has to be set at the bind request.
            // We use force here which means that the test in the rootDSE is skipped;
            // this is neccessary, because some strict LDAP servers only allow to
            // read the LDAP rootDSE (which tells us the supported protocol versions)
            // with authenticated clients.
            // This may fail in which case we try again after binding.
            // In this case, most probably the bind() or setLDAPVersion()-call
            // below will also fail, providing error messages.
            $version_set = false;
            $ignored_err = $this->setLDAPVersion(0, true);
            if (!self::isError($ignored_err)) {
                $version_set = true;
            }

            // Attempt to bind to the server. If we have credentials configured,
            // we try to use them, otherwise its an anonymous bind.
            // As stated by RFC-1777, the bind request should be the first
            // operation to be performed after the connection is established.
            // This may give an protocol error if the server does not support
            // V2 binds and the above call to setLDAPVersion() failed.
            // In case the above call failed, we try an V2 bind here and set the
            // version afterwards (with checking to the rootDSE).
            $msg = $this->bind();
            if (self::isError($msg)) {
                // The bind failed, discard link and save error msg.
                // Then record the host as down and try next one
                if ($msg->getCode() == 0x02 && !$version_set) {
                    // provide a finer grained error message
                    // if protocol error arieses because of invalid version
                    $msg = new Net_LDAP2_Error($msg->getMessage().
                        " (could not set LDAP protocol version to ".
                        $this->_config['version'].")",
                        $msg->getCode());
                }
                $this->_link             = false;
                $current_error           = $msg;
                $this->_down_host_list[] = $host;
                continue;
            }

            // Set desired LDAP version if not successfully set before.
            // Here, a check against the rootDSE is performed, so we get a
            // error message if the server does not support the version.
            // The rootDSE entry should tell us which LDAP versions are
            // supported. However, some strict LDAP servers only allow
            // bound suers to read the rootDSE.
            if (!$version_set) {
                if (self::isError($msg = $this->setLDAPVersion())) {
                    $current_error           = $msg;
                    $this->_link             = false;
                    $this->_down_host_list[] = $host;
                    continue;
                }
            }

            // Set LDAP parameters, now we know we have a valid connection.
            if (isset($this->_config['options']) &&
                is_array($this->_config['options']) &&
                count($this->_config['options'])) {
                foreach ($this->_config['options'] as $opt => $val) {
                    $err = $this->setOption($opt, $val);
                    if (self::isError($err)) {
                        $current_error           = $err;
                        $this->_link             = false;
                        $this->_down_host_list[] = $host;
                        continue 2;
                    }
                }
            }

            // At this stage we have connected, bound, and set up options,
            // so we have a known good LDAP server.  Time to go home.
            return true;
        }


        // All connection attempts have failed, return the last error.
        return $current_error;
    }
137669
public function addServer($host, $port, $weight=0){
        return $this->connection->addServer($host, $port, $weight);
    }
1042289
protected function ldapConnect(array $config)
    {
        // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
        $connection = @ldap_connect($config['host'], $config['port']);
        if (!is_resource($connection)) {
            $this->abort("Unable to connecto LDAP at [" . $config['host'] . ":" . $config['port'] . "]");
        }

        // set LDAP options
        ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, (int)$config['version']);
        ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
        ldap_set_option($connection, LDAP_OPT_NETWORK_TIMEOUT, 5);

        // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
        $bind = @ldap_bind($connection, $config['domain'] . '\\' . $config['username'], $config['password']);
        if ($bind === false) {
            $this->abort('Cannot bind with user: ' . $config['username'] . '.');
        }

        return $connection;
    }
418556
public function connect($host = '127.0.0.1', $port = 11211)
    {
        if (!isset($this->servers[$host . ':' . $port])) {
            $this->server = new \Memcache();
            $this->server->connect($host, $port);

            $this->servers[$host . ':' . $port] = $this->server;
        } else {
            $this->server = $this->servers[$host . ':' . $port];
        }

        return true;
    }
698128
public function connect($host, $port = 80, $secure = false)
    {
        // If no proxy is set, fall back to Socket adapter
        if (! $this->config['proxy_host']) return parent::connect($host, $port, $secure);

        // Go through a proxy - the connection is actually to the proxy server
        $host = $this->config['proxy_host'];
        $port = $this->config['proxy_port'];

        // If we are connected to the wrong proxy, disconnect first
        if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
            if (is_resource($this->socket)) $this->close();
        }

        // Now, if we are not connected, connect
        if (! is_resource($this->socket) || ! $this->config['keepalive']) {
            $this->socket = @fsockopen($host, $port, $errno, $errstr, (int) $this->config['timeout']);
            if (! $this->socket) {
                $this->close();
                require_once 'Zend/Http/Client/Adapter/Exception.php';
                throw new Zend_Http_Client_Adapter_Exception(
                    'Unable to Connect to proxy server ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
            }

            // Set the stream timeout
            if (!stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
                require_once 'Zend/Http/Client/Adapter/Exception.php';
                throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
            }

            // Update connected_to
            $this->connected_to = array($host, $port);
        }
    }
615157
public function connect($host, $port, Connection $connection, $timeout = 5)
    {
        $deferred = new Deferred();
        $this->disconnect()
            ->then(function () use ($deferred, $host, $port, $connection, $timeout) {
                $this->establishConnection($host, $port, $connection, $timeout)
                    ->then(function () use ($deferred) {
                        $deferred->resolve($this);
                    })
                    ->otherwise(function (\Exception $error) use ($deferred) {
                        $deferred->reject($error);
                    });
            })
            ->otherwise(function () use ($deferred) {
                $deferred->reject($this);
            });

        return $deferred->promise();
    }
681973
protected function addServer($host, array $options = [])
    {
        $port = isset($options['port']) && !empty($options['port']) ? $options['port'] : 11211;
        $weight = isset($options['weight']) && !empty($options['weight']) ? $options['weight'] : 0;

        $this->memcached->addServer($host, $port, $weight);
    }
599589
public function connect(array $options = array())
    {
        $host = $port = null;
        
        if (!is_null($this->host)) {
            $host = 'host='.$this->host.';';
            if (!is_null($this->port)) {
                $port = 'port='.$this->port.';';
            }
        }
        
        $connection = 'mysql:'.$host.$port.'dbname='.$this->name;
        
        $this->connection = new \PDO($connection, $this->user, $this->pass, $options);
        
        $this->trigger('mysql-connect');
        
        return $this;
    }
1018937
public static function Redis($host = '127.0.0.1', $port = 6379, $options = [])
    {
        return new CacheStorage(Storage\Redis::getInstance($host, $port), $options);
    }
471355
public function connect($host, $port = 80, $secure = false)
    {
        // If no proxy is set, fall back to Socket adapter
        if (!$this->config['proxy_host']) {
            return parent::connect($host, $port, $secure);
        }

        /* Url might require stream context even if proxy connection doesn't */
        if ($secure) {
            $this->config['sslusecontext'] = true;
        }

        // Connect (a non-secure connection) to the proxy server
        return parent::connect(
            $this->config['proxy_host'],
            $this->config['proxy_port'],
            false
        );
    }
1268606
public static function udp(string $host, array $options = []) : Socket
    {
        return self::create($host, \array_merge($options, [
            'transport' => 'udp',
            'buffer_size' => 65507,
        ]));
    }
325437
public function createConnection($host, $port, $password = null)
    {
        $socket = $this->socketFactory->createClient(sprintf('%s:%s', $host, $port));

        $conn = new Connection($socket);

        if (!empty($password)) {
            $conn->authenticate($password);
        }

        return $conn;
    }