Python thrift.transport.TSocket.TSocket() Examples

The following are 30 code examples of thrift.transport.TSocket.TSocket(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module thrift.transport.TSocket , or try the search function .
Example #1
Source File: TSSLSocket.py    From thrift with GNU Lesser General Public License v3.0 6 votes vote down vote up
def accept(self):
        plain_client, addr = self.handle.accept()
        try:
            client = self._wrap_socket(plain_client)
        except (ssl.SSLError, OSError):
            logger.exception('EROR DISINI SOB %s', addr)
            plain_client.close()
            return None
        if self._should_verify:
            client.peercert = client.getpeercert()
            try:
                self._validate_callback(client.peercert, addr[0])
                client.is_valid = True
            except Exception:
                logger.warn('Failed to validate client certificate address: %s',
                            addr[0], exc_info=True)
                client.close()
                plain_client.close()
                return None
        result = TSocket.TSocket()
        result.handle = client
        return result
# BAHAGIALAH KAWAN 
Example #2
Source File: TSSLSocket.py    From galaxy-sdk-python with Apache License 2.0 6 votes vote down vote up
def __init__(self,
               host=None,
               port=9090,
               certfile='cert.pem',
               unix_socket=None):
    """Initialize a TSSLServerSocket

    @param certfile: filename of the server certificate, defaults to cert.pem
    @type certfile: str
    @param host: The hostname or IP to bind the listen socket to,
                 i.e. 'localhost' for only allowing local network connections.
                 Pass None to bind to all interfaces.
    @type host: str
    @param port: The port to listen on for inbound connections.
    @type port: int
    """
    self.setCertfile(certfile)
    TSocket.TServerSocket.__init__(self, host, port) 
Example #3
Source File: _thrift_api.py    From impyla with Apache License 2.0 6 votes vote down vote up
def get_socket(host, port, use_ssl, ca_cert):
    # based on the Impala shell impl
    log.debug('get_socket: host=%s port=%s use_ssl=%s ca_cert=%s',
              host, port, use_ssl, ca_cert)

    if use_ssl:
        if six.PY2:
            from thrift.transport.TSSLSocket import TSSLSocket
            if ca_cert is None:
                return TSSLSocket(host, port, validate=False)
            else:
                return TSSLSocket(host, port, validate=True, ca_certs=ca_cert)
        else:
            from thriftpy2.transport.sslsocket import TSSLSocket
            if ca_cert is None:
                return TSSLSocket(host, port, validate=False)
            else:
                return TSSLSocket(host, port, validate=True, cafile=ca_cert)
    else:
        return TSocket(host, port) 
Example #4
Source File: TSSLSocket.py    From SOLO with GNU General Public License v3.0 6 votes vote down vote up
def accept(self):
        plain_client, addr = self.handle.accept()
        try:
            client = self._wrap_socket(plain_client)
        except (ssl.SSLError, OSError):
            logger.exception('EROR DISINI SOB %s', addr)
            plain_client.close()
            return None
        if self._should_verify:
            client.peercert = client.getpeercert()
            try:
                self._validate_callback(client.peercert, addr[0])
                client.is_valid = True
            except Exception:
                logger.warn('Failed to validate client certificate address: %s',
                            addr[0], exc_info=True)
                client.close()
                plain_client.close()
                return None
        result = TSocket.TSocket()
        result.handle = client
        return result
# BAHAGIALAH KAWAN 
Example #5
Source File: putget_test.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def __init__(self, node=None, host=None, port=None, ks_name='ks', cf_name='cf',
                 cassandra_interface='11'):
        """
        initializes the connection.
         - node: a ccm node. If supplied, the host and port, and cassandra_interface
           will be pulled from the node.
         - host, port: overwritten if node is supplied
         - ks_name, cf_name: all operations are done on the supplied ks and cf
         - cassandra_interface: '07' and '11' are currently supported. This is the
           thrift interface to cassandra. '11' suffices for now except when creating
           keyspaces against cassandra0.7, in which case 07 must be used.
        """
        if node:
            host, port = node.network_interfaces['thrift']
        self.node = node
        self.host = host
        self.port = port
        self.cassandra_interface = cassandra_interface

        # import the correct version of the cassandra thrift interface
        # and set self.Cassandra as the imported module
        module_name = 'cassandra-thrift.v%s' % cassandra_interface
        imp = __import__(module_name, globals(), locals(), ['Cassandra'])
        self.Cassandra = imp.Cassandra

        socket = TSocket.TSocket(host, port)
        self.transport = TTransport.TFramedTransport(socket)
        protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
        self.client = self.Cassandra.Client(protocol)

        socket.open()
        self.open_socket = True

        self.ks_name = ks_name
        self.cf_name = cf_name 
Example #6
Source File: client.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def get_client():
    transport = TSocket.TSocket('localhost', 8200)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = PasteFileService.Client(protocol)
    transport.open()
    return client 
Example #7
Source File: TSSLSocket.py    From ajs2 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, host=None, port=9090, *args, **kwargs):
        """Positional arguments: ``host``, ``port``, ``unix_socket``

        Keyword arguments: ``keyfile``, ``certfile``, ``cert_reqs``, ``ssl_version``,
                           ``ca_certs``, ``ciphers`` (Python 2.7.0 or later)
        See ssl.wrap_socket documentation.

        Alternative keyword arguments: (Python 2.7.9 or later)
          ``ssl_context``: ssl.SSLContext to be used for SSLContext.wrap_socket
          ``server_hostname``: Passed to SSLContext.wrap_socket

        Common keyword argument:
          ``validate_callback`` (cert, hostname) -> None:
              Called after SSL handshake. Can raise when hostname does not
              match the cert.
        """
        if args:
            if len(args) > 3:
                raise TypeError('Too many positional argument')
            if not self._unix_socket_arg(host, port, args, kwargs):
                self._deprecated_arg(args, kwargs, 0, 'certfile')
            self._deprecated_arg(args, kwargs, 1, 'unix_socket')
            self._deprecated_arg(args, kwargs, 2, 'ciphers')

        if 'ssl_context' not in kwargs:
            # Preserve existing behaviors for default values
            if 'cert_reqs' not in kwargs:
                kwargs['cert_reqs'] = ssl.CERT_NONE
            if'certfile' not in kwargs:
                kwargs['certfile'] = 'cert.pem'

        unix_socket = kwargs.pop('unix_socket', None)
        self._validate_callback = \
            kwargs.pop('validate_callback', _match_hostname)
        TSSLBase.__init__(self, True, None, kwargs)
        TSocket.TServerSocket.__init__(self, host, port, unix_socket)
        if self._should_verify and not _match_has_ipaddress:
            raise ValueError('Need ipaddress and backports.ssl_match_hostname '
                             'module to verify client certificate') 
Example #8
Source File: TSSLSocket.py    From ajs2 with GNU General Public License v3.0 5 votes vote down vote up
def accept(self):
        plain_client, addr = self.handle.accept()
        try:
            client = self._wrap_socket(plain_client)
        except ssl.SSLError:
            logger.exception('Error while accepting from %s', addr)
            # failed handshake/ssl wrap, close socket to client
            plain_client.close()
            # raise
            # We can't raise the exception, because it kills most TServer derived
            # serve() methods.
            # Instead, return None, and let the TServer instance deal with it in
            # other exception handling.  (but TSimpleServer dies anyway)
            return None

        if self._should_verify:
            client.peercert = client.getpeercert()
            try:
                self._validate_callback(client.peercert, addr[0])
                client.is_valid = True
            except Exception:
                logger.warn('Failed to validate client certificate address: %s',
                            addr[0], exc_info=True)
                client.close()
                plain_client.close()
                return None

        result = TSocket.TSocket()
        result.handle = client
        return result 
Example #9
Source File: thrift.py    From splunk-elasticsearch with Apache License 2.0 5 votes vote down vote up
def __init__(self, host='localhost', port=9500, framed_transport=False, use_ssl=False, **kwargs):
        """
        :arg framed_transport: use `TTransport.TFramedTransport` instead of
            `TTransport.TBufferedTransport`
        """
        if not THRIFT_AVAILABLE:
            raise ImproperlyConfigured("Thrift is not available.")

        super(ThriftConnection, self).__init__(host=host, port=port, **kwargs)
        self._framed_transport = framed_transport
        self._tsocket_class = TSocket.TSocket
        if use_ssl:
            self._tsocket_class = TSSLSocket.TSSLSocket 
        self._tsocket_args = (host, port) 
Example #10
Source File: thrift.py    From sublime-elasticsearch-client with MIT License 5 votes vote down vote up
def __init__(self, host='localhost', port=9500, framed_transport=False, use_ssl=False, **kwargs):
        """
        :arg framed_transport: use `TTransport.TFramedTransport` instead of
            `TTransport.TBufferedTransport`
        """
        if not THRIFT_AVAILABLE:
            raise ImproperlyConfigured("Thrift is not available.")

        super(ThriftConnection, self).__init__(host=host, port=port, **kwargs)
        self._framed_transport = framed_transport
        self._tsocket_class = TSocket.TSocket
        if use_ssl:
            self._tsocket_class = TSSLSocket.TSSLSocket 
        self._tsocket_args = (host, port) 
Example #11
Source File: TSSLSocket.py    From SOLO with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, host=None, port=9090, *args, **kwargs):
        """PRANKBOT MODIFED: ``host``, ``port``, ``unix_socket``
        Keyword arguments: ``keyfile``, ``certfile``, ``cert_reqs``, ``ssl_version``,
                           ``ca_certs``, ``ciphers`` (Python 2.7.0 or later)
        See ssl.wrap_socket documentation.
        Alternative keyword arguments: (Python 2.7.9 or later)
          ``ssl_context``: ssl.SSLContext to be used for SSLContext.wrap_socket
          ``server_hostname``: Passed to SSLContext.wrap_socket
        Common keyword argument:
          ``validate_callback`` (cert, hostname) -> None:
              Called after SSL handshake. Can raise when hostname does not
              match the cert.
        """
        if args:
            if len(args) > 3:
                raise TypeError('Too many positional argument')
            if not self._unix_socket_arg(host, port, args, kwargs):
                self._deprecated_arg(args, kwargs, 0, 'certfile')
            self._deprecated_arg(args, kwargs, 1, 'unix_socket')
            self._deprecated_arg(args, kwargs, 2, 'ciphers')
        if 'ssl_context' not in kwargs:
            # Preserve existing behaviors for default values
            if 'cert_reqs' not in kwargs:
                kwargs['cert_reqs'] = ssl.CERT_NONE
            if'certfile' not in kwargs:
                kwargs['certfile'] = 'cert.pem'
        unix_socket = kwargs.pop('unix_socket', None)
        self._validate_callback = \
            kwargs.pop('validate_callback', _match_hostname)
        TSSLBase.__init__(self, True, None, kwargs)
        TSocket.TServerSocket.__init__(self, host, port, unix_socket)
        if self._should_verify and not _match_has_ipaddress:
            raise ValueError('Need ipaddress and backports.ssl_match_hostname '
                             'module to verify client certificate') 
Example #12
Source File: client.py    From hazelcast-python-client with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port):
        try:
            # Make socket
            transport = TSocket.TSocket(host=host, port=port)
            # Buffering is critical. Raw sockets are very slow
            transport = TTransport.TBufferedTransport(transport)
            # Wrap in a protocol
            protocol = TBinaryProtocol.TBinaryProtocol(transport)
            self.remote_controller = RemoteController.Client(protocol)
            # Connect!
            transport.open()
        except Thrift.TException as tx:
            self.logger.warn('%s' % tx.message) 
Example #13
Source File: connection_pool.py    From jqdatasdk with MIT License 5 votes vote down vote up
def get_socket_factory(self):
        from thrift.transport import TSocket
        return TSocket.TSocket 
Example #14
Source File: connection_pool.py    From jqdatasdk with MIT License 5 votes vote down vote up
def get_socket_factory(self):
        from thriftpy2.transport import TSocket
        return TSocket 
Example #15
Source File: sync_worker.py    From gunicorn_thrift with MIT License 5 votes vote down vote up
def handle(self, listener, client, addr):
        self.cfg.on_connected(self, addr)
        if self.app.cfg.thrift_client_timeout is not None:
            client.settimeout(self.app.cfg.thrift_client_timeout)

        result = TSocket.TSocket()
        result.setHandle(client)

        try:
            (itrans, otrans), (iprot, oprot) = \
                self.get_thrift_transports_and_protos(result)

            processor = self.get_thrift_processor()

            try:
                while True:
                    processor.process(iprot, oprot)
                    self.notify()
            except TTransport.TTransportException:
                pass
        except socket.timeout:
            self.log.warning('Client timeout: %r', addr)
        except socket.error as e:
            if e.args[0] == errno.ECONNRESET:
                self.log.debug(e)
            else:
                self.log.exception(e)
        except Exception as e:
            self.log.exception(e)
        finally:
            itrans.close()
            otrans.close()
            self.cfg.post_connect_closed(self) 
Example #16
Source File: gevent_worker.py    From gunicorn_thrift with MIT License 5 votes vote down vote up
def handle(self, listener, client, addr):
        self.cfg.on_connected(self, addr)
        if self.app.cfg.thrift_client_timeout is not None:
            client.settimeout(self.app.cfg.thrift_client_timeout)

        result = TSocket.TSocket()
        result.setHandle(client)

        try:
            (itrans, otrans), (iprot, oprot) = \
                self.get_thrift_transports_and_protos(result)

            processor = self.get_thrift_processor()

            try:
                while True:
                    processor.process(iprot, oprot)
            except TTransport.TTransportException:
                pass
        except socket.error as e:
            if e.args[0] == errno.ECONNRESET:
                self.log.debug(e)
            else:
                self.log.exception(e)
        except Exception as e:
            self.log.exception(e)
        finally:
            itrans.close()
            otrans.close()
            self.cfg.post_connect_closed(self) 
Example #17
Source File: flume.py    From openslack-crawler with Apache License 2.0 5 votes vote down vote up
def __init__(self, thrift_host, thrift_port, timeout=None, unix_socket=None):
        self.thrift_host = thrift_host
        self.thrift_port = thrift_port
        self.timeout = timeout
        self.unix_socket = unix_socket
        
        self._socket = TSocket.TSocket(self.thrift_host, self.thrift_port, self.unix_socket)
        self._transport_factory = TTransport.TFramedTransportFactory()
        self._transport = self._transport_factory.getTransport(self._socket) 
Example #18
Source File: TSSLSocket.py    From thrift with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, host=None, port=9090, *args, **kwargs):
        """PRANKBOT MODIFED: ``host``, ``port``, ``unix_socket``
        Keyword arguments: ``keyfile``, ``certfile``, ``cert_reqs``, ``ssl_version``,
                           ``ca_certs``, ``ciphers`` (Python 2.7.0 or later)
        See ssl.wrap_socket documentation.
        Alternative keyword arguments: (Python 2.7.9 or later)
          ``ssl_context``: ssl.SSLContext to be used for SSLContext.wrap_socket
          ``server_hostname``: Passed to SSLContext.wrap_socket
        Common keyword argument:
          ``validate_callback`` (cert, hostname) -> None:
              Called after SSL handshake. Can raise when hostname does not
              match the cert.
        """
        if args:
            if len(args) > 3:
                raise TypeError('Too many positional argument')
            if not self._unix_socket_arg(host, port, args, kwargs):
                self._deprecated_arg(args, kwargs, 0, 'certfile')
            self._deprecated_arg(args, kwargs, 1, 'unix_socket')
            self._deprecated_arg(args, kwargs, 2, 'ciphers')
        if 'ssl_context' not in kwargs:
            # Preserve existing behaviors for default values
            if 'cert_reqs' not in kwargs:
                kwargs['cert_reqs'] = ssl.CERT_NONE
            if'certfile' not in kwargs:
                kwargs['certfile'] = 'cert.pem'
        unix_socket = kwargs.pop('unix_socket', None)
        self._validate_callback = \
            kwargs.pop('validate_callback', _match_hostname)
        TSSLBase.__init__(self, True, None, kwargs)
        TSocket.TServerSocket.__init__(self, host, port, unix_socket)
        if self._should_verify and not _match_has_ipaddress:
            raise ValueError('Need ipaddress and backports.ssl_match_hostname '
                             'module to verify client certificate') 
Example #19
Source File: python3_thrift_hbase2(paper_creator_aff_try).py    From Learning_Python with MIT License 5 votes vote down vote up
def connectHBase():
    '''
    连接远程HBase
    :return: 连接HBase的客户端实例
    '''
    # thrift默认端口是9090
    socket = TSocket.TSocket('10.0.86.245',9090) # 10.0.86.245是master结点ip
    socket.setTimeout(5000)
    transport = TTransport.TBufferedTransport(socket)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Hbase.Client(protocol)
    socket.open()
    return client 
Example #20
Source File: thrift_test.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def get_thrift_client(host='127.0.0.1', port=9160):
    socket = TSocket.TSocket(host, port)
    transport = TTransport.TFramedTransport(socket)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Cassandra.Client(protocol)
    client.transport = transport
    return client 
Example #21
Source File: TSSLSocket.py    From galaxy-sdk-python with Apache License 2.0 5 votes vote down vote up
def __init__(self,
               host='localhost',
               port=9090,
               validate=True,
               ca_certs=None,
               keyfile=None,
               certfile=None,
               unix_socket=None):
    """Create SSL TSocket

    @param validate: Set to False to disable SSL certificate validation
    @type validate: bool
    @param ca_certs: Filename to the Certificate Authority pem file, possibly a
    file downloaded from: http://curl.haxx.se/ca/cacert.pem  This is passed to
    the ssl_wrap function as the 'ca_certs' parameter.
    @type ca_certs: str
    @param keyfile: The private key
    @type keyfile: str
    @param certfile: The cert file
    @type certfile: str
    
    Raises an IOError exception if validate is True and the ca_certs file is
    None, not present or unreadable.
    """
    self.validate = validate
    self.is_valid = False
    self.peercert = None
    if not validate:
      self.cert_reqs = ssl.CERT_NONE
    else:
      self.cert_reqs = ssl.CERT_REQUIRED
    self.ca_certs = ca_certs
    self.keyfile = keyfile
    self.certfile = certfile
    if validate:
      if ca_certs is None or not os.access(ca_certs, os.R_OK):
        raise IOError('Certificate Authority ca_certs file "%s" '
                      'is not readable, cannot validate SSL '
                      'certificates.' % (ca_certs))
    TSocket.TSocket.__init__(self, host, port, unix_socket) 
Example #22
Source File: client.py    From dispel4py with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port):
        self.host = host
        self.port = port
        transport = TSocket.TSocket(host, port)
        self.transport = TTransport.TFramedTransport(transport)
        self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
        self.client = Nimbus.Client(self.protocol) 
Example #23
Source File: TSSLSocket.py    From Protect4 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, host=None, port=9090, *args, **kwargs):
        """Positional arguments: ``host``, ``port``, ``unix_socket``

        Keyword arguments: ``keyfile``, ``certfile``, ``cert_reqs``, ``ssl_version``,
                           ``ca_certs``, ``ciphers`` (Python 2.7.0 or later)
        See ssl.wrap_socket documentation.

        Alternative keyword arguments: (Python 2.7.9 or later)
          ``ssl_context``: ssl.SSLContext to be used for SSLContext.wrap_socket
          ``server_hostname``: Passed to SSLContext.wrap_socket

        Common keyword argument:
          ``validate_callback`` (cert, hostname) -> None:
              Called after SSL handshake. Can raise when hostname does not
              match the cert.
        """
        if args:
            if len(args) > 3:
                raise TypeError('Too many positional argument')
            if not self._unix_socket_arg(host, port, args, kwargs):
                self._deprecated_arg(args, kwargs, 0, 'certfile')
            self._deprecated_arg(args, kwargs, 1, 'unix_socket')
            self._deprecated_arg(args, kwargs, 2, 'ciphers')

        if 'ssl_context' not in kwargs:
            # Preserve existing behaviors for default values
            if 'cert_reqs' not in kwargs:
                kwargs['cert_reqs'] = ssl.CERT_NONE
            if'certfile' not in kwargs:
                kwargs['certfile'] = 'cert.pem'

        unix_socket = kwargs.pop('unix_socket', None)
        self._validate_callback = \
            kwargs.pop('validate_callback', _match_hostname)
        TSSLBase.__init__(self, True, None, kwargs)
        TSocket.TServerSocket.__init__(self, host, port, unix_socket)
        if self._should_verify and not _match_has_ipaddress:
            raise ValueError('Need ipaddress and backports.ssl_match_hostname '
                             'module to verify client certificate') 
Example #24
Source File: TSSLSocket.py    From Protect4 with GNU General Public License v3.0 5 votes vote down vote up
def accept(self):
        plain_client, addr = self.handle.accept()
        try:
            client = self._wrap_socket(plain_client)
        except ssl.SSLError:
            logger.exception('Error while accepting from %s', addr)
            # failed handshake/ssl wrap, close socket to client
            plain_client.close()
            # raise
            # We can't raise the exception, because it kills most TServer derived
            # serve() methods.
            # Instead, return None, and let the TServer instance deal with it in
            # other exception handling.  (but TSimpleServer dies anyway)
            return None

        if self._should_verify:
            client.peercert = client.getpeercert()
            try:
                self._validate_callback(client.peercert, addr[0])
                client.is_valid = True
            except Exception:
                logger.warn('Failed to validate client certificate address: %s',
                            addr[0], exc_info=True)
                client.close()
                plain_client.close()
                return None

        result = TSocket.TSocket()
        result.handle = client
        return result 
Example #25
Source File: python3_thrift_hbase2.py    From Learning_Python with MIT License 5 votes vote down vote up
def connectHBase():
    '''
    连接远程HBase
    :return: 连接HBase的客户端实例
    '''
    # thrift默认端口是9090
    socket = TSocket.TSocket('10.0.86.245',9090) # 10.0.86.245是master结点ip
    socket.setTimeout(5000)
    transport = TTransport.TBufferedTransport(socket)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Hbase.Client(protocol)
    socket.open()
    return client 
Example #26
Source File: conftest.py    From pymapd with Apache License 2.0 5 votes vote down vote up
def _check_open():
    """
    Test to see if OmniSci running on localhost and socket open
    """
    socket = TSocket.TSocket("localhost", 6274)
    transport = TTransport.TBufferedTransport(socket)

    try:
        transport.open()
        return True
    except TTransportException:
        return False 
Example #27
Source File: scannerGet.py    From Learning_Python with MIT License 5 votes vote down vote up
def connectHBase():
    '''
    连接远程HBase
    :return: 连接HBase的客户端实例
    '''
    # thrift默认端口是9090
    socket = TSocket.TSocket('10.0.86.245',9090) # 10.0.86.245是master结点ip
    socket.setTimeout(5000)
    transport = TTransport.TBufferedTransport(socket)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Hbase.Client(protocol)
    socket.open()
    return client 
Example #28
Source File: TSSLSocket.py    From Aditmadzs2 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, host=None, port=9090, *args, **kwargs):
        """Positional arguments: ``host``, ``port``, ``unix_socket``

        Keyword arguments: ``keyfile``, ``certfile``, ``cert_reqs``, ``ssl_version``,
                           ``ca_certs``, ``ciphers`` (Python 2.7.0 or later)
        See ssl.wrap_socket documentation.

        Alternative keyword arguments: (Python 2.7.9 or later)
          ``ssl_context``: ssl.SSLContext to be used for SSLContext.wrap_socket
          ``server_hostname``: Passed to SSLContext.wrap_socket

        Common keyword argument:
          ``validate_callback`` (cert, hostname) -> None:
              Called after SSL handshake. Can raise when hostname does not
              match the cert.
        """
        if args:
            if len(args) > 3:
                raise TypeError('Too many positional argument')
            if not self._unix_socket_arg(host, port, args, kwargs):
                self._deprecated_arg(args, kwargs, 0, 'certfile')
            self._deprecated_arg(args, kwargs, 1, 'unix_socket')
            self._deprecated_arg(args, kwargs, 2, 'ciphers')

        if 'ssl_context' not in kwargs:
            # Preserve existing behaviors for default values
            if 'cert_reqs' not in kwargs:
                kwargs['cert_reqs'] = ssl.CERT_NONE
            if'certfile' not in kwargs:
                kwargs['certfile'] = 'cert.pem'

        unix_socket = kwargs.pop('unix_socket', None)
        self._validate_callback = \
            kwargs.pop('validate_callback', _match_hostname)
        TSSLBase.__init__(self, True, None, kwargs)
        TSocket.TServerSocket.__init__(self, host, port, unix_socket)
        if self._should_verify and not _match_has_ipaddress:
            raise ValueError('Need ipaddress and backports.ssl_match_hostname '
                             'module to verify client certificate') 
Example #29
Source File: TSSLSocket.py    From Aditmadzs2 with GNU General Public License v3.0 5 votes vote down vote up
def accept(self):
        plain_client, addr = self.handle.accept()
        try:
            client = self._wrap_socket(plain_client)
        except ssl.SSLError:
            logger.exception('Error while accepting from %s', addr)
            # failed handshake/ssl wrap, close socket to client
            plain_client.close()
            # raise
            # We can't raise the exception, because it kills most TServer derived
            # serve() methods.
            # Instead, return None, and let the TServer instance deal with it in
            # other exception handling.  (but TSimpleServer dies anyway)
            return None

        if self._should_verify:
            client.peercert = client.getpeercert()
            try:
                self._validate_callback(client.peercert, addr[0])
                client.is_valid = True
            except Exception:
                logger.warn('Failed to validate client certificate address: %s',
                            addr[0], exc_info=True)
                client.close()
                plain_client.close()
                return None

        result = TSocket.TSocket()
        result.handle = client
        return result 
Example #30
Source File: connection_pool.py    From thrift_connector with MIT License 5 votes vote down vote up
def get_socket_factory(self):
        from thrift.transport import TSocket
        return TSocket.TSocket