我们从Python开源项目中,提取了以下10个代码示例,用于说明如何使用socket.sslerror()。
def get_page(self, url, data=None): handlers = [PoolHTTPHandler] opener = urllib2.build_opener(*handlers) if data: data = urllib.urlencode(data) request = urllib2.Request(url, data, self.headers) try: response = opener.open(request) return response.read() except (urllib2.HTTPError, urllib2.URLError), e: raise BrowserError(url, str(e)) except (socket.error, socket.sslerror), msg: raise BrowserError(url, msg) except socket.timeout, e: raise BrowserError(url, "timeout") except KeyboardInterrupt: raise except: raise BrowserError(url, "unknown error")
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)
def patch_ssl(): patch_module('ssl') # On Python 2.5 we use an external 'ssl' module. On all # newer versions, the ssl module is builtin, and 'ssl.SSLError' *is* # 'socket.sslerror', but that's not the case with the external # module. Because our patched functions will raise ssl.SSLError, but # callers on 2.5 could only be expecting to catch 'socket.sslerror' # we make them the same. if version_info[:2] <= (2, 5): from gevent import ssl import socket saved['socket']['sslerror'] = socket.sslerror socket.sslerror = ssl.SSLError
def _put(self, source_path, remote_filename): f = source_path.open("rb") allowedTimeout = globals.timeout if (allowedTimeout == 0): # Allow a total timeout of 1 day allowedTimeout = 2880 while allowedTimeout > 0: try: self.conn.select(remote_filename) body = self.prepareBody(f, remote_filename) # If we don't select the IMAP folder before # append, the message goes into the INBOX. self.conn.select(globals.imap_mailbox) self.conn.append(globals.imap_mailbox, None, None, body) break except (imaplib.IMAP4.abort, socket.error, socket.sslerror): allowedTimeout -= 1 log.Info("Error saving '%s', retrying in 30s " % remote_filename) time.sleep(30) while allowedTimeout > 0: try: self.resetConnection() break except (imaplib.IMAP4.abort, socket.error, socket.sslerror): allowedTimeout -= 1 log.Info("Error reconnecting, retrying in 30s ") time.sleep(30) log.Info("IMAP mail with '%s' subject stored" % remote_filename)
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
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 else: # Fallback for 'SSLError: _ssl.c:489: The handshake operation timed out' for i in xrange(3): try: self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file) break except SSLError, ex: if ex.args[0] == SSL_ERROR_WANT_READ: sys.exc_clear() elif ex.args[0] == SSL_ERROR_WANT_WRITE: sys.exc_clear() else: raise self.connection_alive = True _logger.debug("%s APNS connection established" % self.__class__.__name__)
def _get_socket(self, sslversion=ssl.PROTOCOL_TLSv1): """Sets up an https connection and do an HTTP/raw socket request :param sslversion: version of ssl session :raises: IloConnectionError, for connection failures :returns: ssl wrapped socket object """ err = None sock = None try: for res in socket.getaddrinfo( self.hostname, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: sock = socket.socket(af, socktype, proto) sock.settimeout(self.timeout) # Connecting to {self.hostname} at port {self.port} sock.connect(sa) except socket.timeout: if sock is not None: sock.close() err = exception.IloConnectionError( "Timeout connecting to %(hostname)s:%(port)d" % {'hostname': self.hostname, 'port': self.port}) except socket.error: if sock is not None: sock.close() e = sys.exc_info()[1] err = exception.IloConnectionError( "Error connecting to %(hostname)s:%(port)d : %(error)s" % {'hostname': self.hostname, 'port': self.port, 'error': str(e)}) except Exception: raise exception.IloConnectionError( "Unable to resolve %s" % self.hostname) if err is not None: raise err # wrapping the socket over ssl session try: return ssl.wrap_socket(sock, ssl_version=sslversion) except socket.sslerror: e = sys.exc_info()[1] msg = (getattr(e, 'reason', None) or getattr(e, 'message', None)) # Some older iLO s don't support TLSv1, retry with SSLv3 if ('wrong version number' in msg) and ( sslversion == ssl.PROTOCOL_TLSv1): return self._get_socket(ssl.PROTOCOL_SSLv3) raise exception.IloConnectionError( "Cannot establish ssl session with %(hostname)s:%(port)d : " "%(error)s" % {'hostname': self.hostname, 'port': self.port, 'error': str(e)})
def _connect(self): # Establish an SSL connection _logger.debug("%s APNS connection establishing..." % self.__class__.__name__) # Fallback for socket timeout. for i in range(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 as 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 else: # Fallback for 'SSLError: _ssl.c:489: The handshake operation timed out' for i in range(3): try: self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file) break except SSLError as ex: if ex.args[0] == SSL_ERROR_WANT_READ: sys.exc_clear() elif ex.args[0] == SSL_ERROR_WANT_WRITE: sys.exc_clear() else: raise self.connection_alive = True _logger.debug("%s APNS connection established" % self.__class__.__name__)
def _get(self, remote_filename, local_path): allowedTimeout = globals.timeout if (allowedTimeout == 0): # Allow a total timeout of 1 day allowedTimeout = 2880 while allowedTimeout > 0: try: self.conn.select(globals.imap_mailbox) (result, list) = self.conn.search(None, 'Subject', remote_filename) if result != "OK": raise Exception(list[0]) # check if there is any result if list[0] == '': raise Exception("no mail with subject %s") (result, list) = self.conn.fetch(list[0], "(RFC822)") if result != "OK": raise Exception(list[0]) rawbody = list[0][1] p = email.Parser.Parser() m = p.parsestr(rawbody) mp = m.get_payload(0) body = mp.get_payload(decode=True) break except (imaplib.IMAP4.abort, socket.error, socket.sslerror): allowedTimeout -= 1 log.Info("Error loading '%s', retrying in 30s " % remote_filename) time.sleep(30) while allowedTimeout > 0: try: self.resetConnection() break except (imaplib.IMAP4.abort, socket.error, socket.sslerror): allowedTimeout -= 1 log.Info("Error reconnecting, retrying in 30s ") time.sleep(30) tfile = local_path.open("wb") tfile.write(body) local_path.setdata() log.Info("IMAP mail with '%s' subject fetched" % remote_filename)