Python socket.sslerror() Examples

The following are 10 code examples of socket.sslerror(). 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 socket , or try the search function .
Example #1
Source File: reporter.py    From mishkal with GNU General Public License v3.0 6 votes vote down vote up
def report(self, exc_data):
        msg = self.assemble_email(exc_data)
        server = smtplib.SMTP(self.smtp_server)
        if self.smtp_use_tls:
            server.ehlo()
            server.starttls()
            server.ehlo()
        if self.smtp_username and self.smtp_password:
            server.login(self.smtp_username, self.smtp_password)
        server.sendmail(self.from_address,
                        self.to_addresses, msg.as_string())
        try:
            server.quit()
        except sslerror:
            # sslerror is raised in tls connections on closing sometimes
            pass 
Example #2
Source File: client.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def connect(self,server=None,proxy=None,ssl=None,use_srv=None):
        """ Make a tcp/ip connection, protect it with tls/ssl if possible and start XMPP stream.
            Returns None or 'tcp' or 'tls', depending on the result."""
        if not server: server=(self.Server,self.Port)
        if proxy: sock=transports.HTTPPROXYsocket(proxy,server,use_srv)
        else: sock=transports.TCPsocket(server,use_srv)
        connected=sock.PlugIn(self)
        if not connected: 
            sock.PlugOut()
            return
        self._Server,self._Proxy=server,proxy
        self.connected='tcp'
        if (ssl is None and self.Connection.getPort() in (5223, 443)) or ssl:
            try:               # FIXME. This should be done in transports.py
                transports.TLS().PlugIn(self,now=1)
                self.connected='ssl'
            except socket.sslerror:
                return
        dispatcher.Dispatcher().PlugIn(self)
        while self.Dispatcher.Stream._document_attrs is None:
            if not self.Process(1): return
        if self.Dispatcher.Stream._document_attrs.has_key('version') and self.Dispatcher.Stream._document_attrs['version']=='1.0':
            while not self.Dispatcher.Stream.features and self.Process(1): pass      # If we get version 1.0 stream the features tag MUST BE presented
        return self.connected 
Example #3
Source File: httplib.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def _read(self):
        buf = ''
        # put in a loop so that we retry on transient errors
        while True:
            try:
                buf = self._ssl.read(self._bufsize)
            except socket.sslerror, err:
                if (err[0] == socket.SSL_ERROR_WANT_READ
                    or err[0] == socket.SSL_ERROR_WANT_WRITE):
                    continue
                if (err[0] == socket.SSL_ERROR_ZERO_RETURN
                    or err[0] == socket.SSL_ERROR_EOF):
                    break
                raise
            except socket.error, err:
                if err[0] == errno.EINTR:
                    continue
                if err[0] == errno.EBADF:
                    # XXX socket was closed?
                    break
                raise 
Example #4
Source File: imaplib2.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def ssl_wrap_socket(self):

        # Allow sending of keep-alive messages - seems to prevent some servers
        # from closing SSL, leading to deadlocks.
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        try:
            import ssl
            if self.ca_certs is not None:
                cert_reqs = ssl.CERT_REQUIRED
            else:
                cert_reqs = ssl.CERT_NONE

            if self.ssl_version == "tls1":
                ssl_version = ssl.PROTOCOL_TLSv1
            elif self.ssl_version == "ssl2":
                ssl_version = ssl.PROTOCOL_SSLv2
            elif self.ssl_version == "ssl3":
                ssl_version = ssl.PROTOCOL_SSLv3
            elif self.ssl_version == "ssl23" or self.ssl_version is None:
                ssl_version = ssl.PROTOCOL_SSLv23
            else:
                raise socket.sslerror("Invalid SSL version requested: %s", self.ssl_version)

            self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ca_certs=self.ca_certs, cert_reqs=cert_reqs, ssl_version=ssl_version)
            ssl_exc = ssl.SSLError
            self.read_fd = self.sock.fileno()
        except ImportError:
            # No ssl module, and socket.ssl has no fileno(), and does not allow certificate verification
            raise socket.sslerror("imaplib2 SSL mode does not work without ssl module")

        if self.cert_verify_cb is not None:
            cert_err = self.cert_verify_cb(self.sock.getpeercert(), self.host)
            if cert_err:
                raise ssl_exc(cert_err) 
Example #5
Source File: smtp.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def close(self):
        """Closes the connection to the email server."""
        try:
            try:
                self.connection.quit()
            except socket.sslerror:
                # This happens when calling quit() on a TLS connection
                # sometimes.
                self.connection.close()
            except:
                if self.fail_silently:
                    return
                raise
        finally:
            self.connection = None 
Example #6
Source File: transports.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def receive(self):
        """ Reads all pending incoming data.
            In case of disconnection calls owner's disconnected() method and then raises IOError exception."""
        try: received = self._recv(BUFLEN)
        except socket.sslerror,e:
            self._seen_data=0
            if e[0]==socket.SSL_ERROR_WANT_READ: return ''
            if e[0]==socket.SSL_ERROR_WANT_WRITE: return ''
            self.DEBUG('Socket error while receiving data','error')
            sys.exc_clear()
            self._owner.disconnected()
            raise IOError("Disconnected from server") 
Example #7
Source File: test_socket_ssl.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_rude_shutdown():
    # This test deadlocks, see http://bugs.jython.org/issue1049
    if test_support.is_jython:
        return
    try:
        import thread
    except ImportError:
        return

    # some random port to connect to
    PORT = 9934
    def listener():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', PORT))
        s.listen(5)
        s.accept()
        del s
        thread.exit()

    def connector():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(('localhost', PORT))
        try:
            ssl_sock = socket.ssl(s)
        except socket.sslerror:
            pass
        else:
            raise test_support.TestFailed, \
                        'connecting to closed SSL socket failed'

    thread.start_new_thread(listener, ())
    time.sleep(1)
    connector() 
Example #8
Source File: apns.py    From pushkin with MIT License 5 votes vote down vote up
def _connect(self):
        # Establish an SSL connection
        _logger.debug("%s APNS connection establishing..." % self.__class__.__name__)

        # Fallback for socket timeout.
        for i in xrange(3):
            try:
                self._socket = socket(AF_INET, SOCK_STREAM)
                self._socket.settimeout(self.timeout)
                self._socket.connect((self.server, self.port))
                break
            except timeout:
                pass
            except:
                raise

        if self.enhanced:
            self._last_activity_time = time.time()
            self._socket.setblocking(False)
            self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file,
                                    do_handshake_on_connect=False)
            while True:
                try:
                    self._ssl.do_handshake()
                    break
                except ssl.SSLError, err:
                    if ssl.SSL_ERROR_WANT_READ == err.args[0]:
                        select.select([self._ssl], [], [])
                    elif ssl.SSL_ERROR_WANT_WRITE == err.args[0]:
                        select.select([], [self._ssl], [])
                    else:
                        raise 
Example #9
Source File: imaplib2.py    From imapfw with MIT License 4 votes vote down vote up
def ssl_wrap_socket(self):

        try:
            import ssl

            TLS_MAP = {}
            if hasattr(ssl, "PROTOCOL_TLSv1_2"):        # py3
                TLS_MAP[TLS_SECURE] = {
                    "tls1_2": ssl.PROTOCOL_TLSv1_2,
                    "tls1_1": ssl.PROTOCOL_TLSv1_1,
                }
            else:
                TLS_MAP[TLS_SECURE] = {}
            TLS_MAP[TLS_NO_SSL] = TLS_MAP[TLS_SECURE].copy()
            TLS_MAP[TLS_NO_SSL].update({
                "tls1": ssl.PROTOCOL_TLSv1,
            })
            TLS_MAP[TLS_COMPAT] = TLS_MAP[TLS_NO_SSL].copy()
            TLS_MAP[TLS_COMPAT].update({
                "ssl23": ssl.PROTOCOL_SSLv23,
                None: ssl.PROTOCOL_SSLv23,
            })
            if hasattr(ssl, "PROTOCOL_SSLv3"):          # Might not be available.
                TLS_MAP[TLS_COMPAT].update({
                    "ssl3": ssl.PROTOCOL_SSLv3
                })

            if self.ca_certs is not None:
                cert_reqs = ssl.CERT_REQUIRED
            else:
                cert_reqs = ssl.CERT_NONE

            if self.tls_level not in TLS_MAP:
                raise RuntimeError("unknown tls_level: %s" % self.tls_level)

            if self.ssl_version not in TLS_MAP[self.tls_level]:
                raise socket.sslerror("Invalid SSL version '%s' requested for tls_version '%s'" % (self.ssl_version, self.tls_level))

            ssl_version =  TLS_MAP[self.tls_level][self.ssl_version]

            self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ca_certs=self.ca_certs, cert_reqs=cert_reqs, ssl_version=ssl_version)
            ssl_exc = ssl.SSLError
            self.read_fd = self.sock.fileno()
        except ImportError:
            # No ssl module, and socket.ssl has no fileno(), and does not allow certificate verification
            raise socket.sslerror("imaplib SSL mode does not work without ssl module")

        if self.cert_verify_cb is not None:
            cert_err = self.cert_verify_cb(self.sock.getpeercert(), self.host)
            if cert_err:
                raise ssl_exc(cert_err)

        # Allow sending of keep-alive messages - seems to prevent some servers
        # from closing SSL, leading to deadlocks.
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 
Example #10
Source File: transporttest.py    From conary with Apache License 2.0 4 votes vote down vote up
def testRetrying(self):
        """We test that conary retries in a bunch of cases"""
        class successException(Exception):
            '''This exception will be raised in place of actually calling
            the actual function'''
            pass

        self.mockMax = 0
        self.theException = None
        self.theReturn = socket.socket()

        def mockCountdown(*args, **kwargs):
            if self.mockMax <= 1:
                raise successException
            else:
                self.mockMax -= 1
            raise self.theException

        try:
            # setup
            self.openRepository()
            client = conaryclient.ConaryClient(self.cfg)
            self.mock(transport.URLOpener, 'createConnection',
                      mockCountdown)

            # test ssl errors
            self.theException = socket.sslerror(socket.SSL_ERROR_EOF,
                                                'A particular ssl error')
            self.mockMax = 2
            try:
                client.repos.c['localhost'].checkVersion()
            except errors.OpenError, e:
                if 'successException' not in e.args[0]:
                    raise

            self.mockMax = 6
            try:
                client.repos.c['localhost'].checkVersion()
            except errors.OpenError, e:
                if 'A particular ssl error' not in e.args[0]:
                    raise

            # test gai errors