'Connect to a host on a given (SSL) port.'

def connect(self):

    msg = 'getaddrinfo    returns    an    empty    list'
    if (self.proxy_info and self.proxy_info.isgood()):
        use_proxy = True
        (proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass) = self.proxy_info.astuple()
    else:
        use_proxy = False
    if (use_proxy and proxy_rdns):
        host = proxy_host
        port = proxy_port
    else:
        host = self.host
        port = self.port
    address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
    for (family, socktype, proto, canonname, sockaddr) in address_info:
        try:
            if use_proxy:
                sock = socks.socksocket(family, socktype, proto)
                sock.setproxy(proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass)
            else:
                sock = socket.socket(family, socktype, proto)
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            if has_timeout(self.timeout):
                sock.settimeout(self.timeout)
            sock.connect((self.host, self.port))
            self.sock = _ssl_wrap_socket(sock, self.key_file, self.cert_file, self.disable_ssl_certificate_validation, self.ca_certs)
            if (self.debuglevel > 0):
                print ('connect:    (%s,    %s)' % (self.host, self.port))
                if use_proxy:
                    print ('proxy:    %s' % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass)))
            if (not self.disable_ssl_certificate_validation):
                cert = self.sock.getpeercert()
                hostname = self.host.split(':', 0)[0]
                if (not self._ValidateCertificateHostname(cert, hostname)):
                    raise CertificateHostnameMismatch(('Server    presented    certificate    that    does    not    match    host    %s:    %s' % (hostname, cert)), hostname, cert)
        except ssl_SSLError as e:
            if sock:
                sock.close()
            if self.sock:
                self.sock.close()
            self.sock = None
            if (e.errno == ssl.SSL_ERROR_SSL):
                raise SSLHandshakeError(e)
            else:
                raise
        except (socket.timeout, socket.gaierror):
            raise
        except socket.error as msg:
            if (self.debuglevel > 0):
                print ('connect    fail:    (%s,    %s)' % (self.host, self.port))
                if use_proxy:
                    print ('proxy:    %s' % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass)))
            if self.sock:
                self.sock.close()
            self.sock = None
            continue
        break
    if (not self.sock):
        raise socket.error, msg
