Exemplo n.º 1
0
    def _socket(self):
        if self.socket is not None:
            return self.socket

        host = self.options.get('host')
        port = self.options.get('port')
        connection_timeout = self.options.get('connection_timeout')
        raw_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        if connection_timeout is not None:
            raw_socket.settimeout(connection_timeout)
        raw_socket.connect((host, port))

        ssl_options = self.options.get('ssl')
        if ssl_options is not None and ssl_options is not False:
            from ssl import CertificateError, SSLError
            raw_socket.sendall(messages.SslRequest().to_bytes())
            response = raw_socket.recv(1)
            if response in ('S', b'S'):
                try:
                    if isinstance(ssl_options, ssl.SSLContext):
                        raw_socket = ssl_options.wrap_socket(
                            raw_socket, server_hostname=host)
                    else:
                        raw_socket = ssl.wrap_socket(raw_socket)
                except CertificateError as e:
                    raise errors.ConnectionError('SSL: ' + e.message)
                except SSLError as e:
                    raise errors.ConnectionError('SSL: ' + e.reason)
            else:
                raise SSLNotSupported(
                    "SSL requested but not supported by server")

        self.socket = raw_socket
        return self.socket
Exemplo n.º 2
0
    def _socket(self):
        if self.socket is not None:
            return self.socket

        if self.options.get('ssl'):
            # SSL
            raw_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            raw_socket.connect((self.options['host'], self.options['port']))
            raw_socket.sendall(messages.SslRequest().to_bytes())
            response = raw_socket.recv(1)
            if response == 'S':
                # May want to add certs to this
                raw_socket = ssl.wrap_socket(raw_socket)
            else:
                raise SSLNotSupported("SSL requested but not supported by server")
        else:
            # Non-SSL
            raw_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            raw_socket.connect((self.options['host'], self.options['port']))

        self.socket = raw_socket
        return raw_socket