def makefile(self, *args):
"""Specific to Python socket API and required by httplib: convert
response into a file-like object. This implementation reads using recv
and copies the output into a StringIO buffer to simulate a file object
for consumption by httplib
Nb. Ignoring optional file open mode (StringIO is generic and will
open for read and write unless a string is passed to the constructor)
and buffer size - httplib set a zero buffer size which results in recv
reading nothing
@return: file object for data returned from socket
@rtype: cStringIO.StringO
"""
self._makefile_refs += 1
# Optimisation
_buf_size = self.buf_size
i=0
stream = BytesIO()
startTime = datetime.utcnow()
try:
dat = self.__ssl_conn.recv(_buf_size)
while dat:
i+=1
stream.write(dat)
dat = self.__ssl_conn.recv(_buf_size)
except (SSL.ZeroReturnError, SSL.SysCallError):
# Connection is closed - assuming here that all is well and full
# response has been received. httplib will catch an error in
# incomplete content since it checks the content-length header
# against the actual length of data received
pass
if log.getEffectiveLevel() <= logging.DEBUG:
log.debug("Socket.makefile %d recv calls completed in %s", i,
datetime.utcnow() - startTime)
# Make sure to rewind the buffer otherwise consumers of the content will
# read from the end of the buffer
stream.seek(0)
return stream
python类SysCallError()的实例源码
def load_crl(self, crlfile):
'''
Load crl file content to openssl x509 object.
:param crlfile: CRL file path.
:type crlfile: String.
:returns: Informational result dict {'error': Boolean, 'message': if error String else x509 object}
:rtype: Dict.
'''
if not ospath.isfile(crlfile):
x509obj = crypto.CRL()
if self.__verbose:
print("INFO: New CRL " + crlfile + " created.")
res = {"error": False, "message": x509obj}
return(res)
else:
try:
x509obj = crypto.load_crl(
crypto.FILETYPE_PEM, open(crlfile).read())
except SSL.SysCallError as e:
res = {"error": True, "message": e.strerror + " " + e.filename}
#print(e.args, e.errno, e.filename, e.strerror)
except SSL.Error as f:
res = {"error": True, "message": f.strerror + " " + f.filename}
except SSL.WantReadError as r:
res = {"error": True, "message": r.strerror + " " + r.filename}
except SSL.WantWriteError as w:
res = {"error": True, "message": w.strerror + " " + w.filename}
except SSL.WantX509LookupError as x:
res = {"error": True, "message": x.strerror + " " + x.filename}
except Exception as ex:
res = {
"error": True,
"message": ex.strerror +
" " +
ex.filename}
except:
res = {"error": True, "message": "Unexpected error"}
else:
res = {"error": False, "message": x509obj}
finally:
return(res)
def _do_ssl_handshake(self):
try:
self._handshake_reading = False
self._handshake_writing = False
self.socket.do_handshake()
except SSL.WantReadError:
self._handshake_reading = True
return
except SSL.WantWriteError:
self._handshake_writing = True
return
except SSL.SysCallError as e:
err_num = abs(e[0])
if err_num in (errno.EBADF, errno.ENOTCONN, errno.EPERM):
return self.close(exc_info=True)
raise
except SSL.Error as err:
try:
peer = self.socket.getpeername()
except Exception:
peer = '(not connected)'
logger.warning("SSL Error on %s %s: %s",
self.socket.fileno(), peer, err)
return self.close(exc_info=True)
except AttributeError:
return self.close(exc_info=True)
else:
self._ssl_accepting = False
verify_mode = self.socket.get_context().get_verify_mode()
if (verify_mode != SSL.VERIFY_NONE and
self._server_hostname is not None):
try:
verify_hostname(self.socket, self._server_hostname)
except VerificationError as e:
logger.warning("Invalid SSL certificate: {0}".format(e))
self.close(exc_info=True)
return
self._run_ssl_connect_callback()
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise NoSSLError()
raise FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
def makefile(self, *args):
"""Specific to Python socket API and required by httplib: convert
response into a file-like object. This implementation reads using recv
and copies the output into a StringIO buffer to simulate a file object
for consumption by httplib
Nb. Ignoring optional file open mode (StringIO is generic and will
open for read and write unless a string is passed to the constructor)
and buffer size - httplib set a zero buffer size which results in recv
reading nothing
@return: file object for data returned from socket
@rtype: cStringIO.StringO
"""
self._makefile_refs += 1
# Optimisation
_buf_size = self.buf_size
i=0
stream = BytesIO()
startTime = datetime.utcnow()
try:
dat = self.__ssl_conn.recv(_buf_size)
while dat:
i+=1
stream.write(dat)
dat = self.__ssl_conn.recv(_buf_size)
except (SSL.ZeroReturnError, SSL.SysCallError):
# Connection is closed - assuming here that all is well and full
# response has been received. httplib will catch an error in
# incomplete content since it checks the content-length header
# against the actual length of data received
pass
if log.getEffectiveLevel() <= logging.DEBUG:
log.debug("Socket.makefile %d recv calls completed in %s", i,
datetime.utcnow() - startTime)
# Make sure to rewind the buffer otherwise consumers of the content will
# read from the end of the buffer
stream.seek(0)
return stream
def makefile(self, *args):
"""Specific to Python socket API and required by httplib: convert
response into a file-like object. This implementation reads using recv
and copies the output into a StringIO buffer to simulate a file object
for consumption by httplib
Nb. Ignoring optional file open mode (StringIO is generic and will
open for read and write unless a string is passed to the constructor)
and buffer size - httplib set a zero buffer size which results in recv
reading nothing
@return: file object for data returned from socket
@rtype: cStringIO.StringO
"""
self._makefile_refs += 1
# Optimisation
_buf_size = self.buf_size
i=0
stream = BytesIO()
startTime = datetime.utcnow()
try:
dat = self.__ssl_conn.recv(_buf_size)
while dat:
i+=1
stream.write(dat)
dat = self.__ssl_conn.recv(_buf_size)
except (SSL.ZeroReturnError, SSL.SysCallError):
# Connection is closed - assuming here that all is well and full
# response has been received. httplib will catch an error in
# incomplete content since it checks the content-length header
# against the actual length of data received
pass
if log.getEffectiveLevel() <= logging.DEBUG:
log.debug("Socket.makefile %d recv calls completed in %s", i,
datetime.utcnow() - startTime)
# Make sure to rewind the buffer otherwise consumers of the content will
# read from the end of the buffer
stream.seek(0)
return stream
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError as e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ''
errnum = e.args[0]
if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
return ''
raise socket.error(errnum)
except SSL.Error as e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ''
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout('timed out')
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError as e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error as e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
def _ssl_wrap_method(method, is_reader=False):
"""Wrap the given method with SSL error-trapping.
is_reader: if False (the default), EOF errors will be raised.
If True, EOF errors will return "" (to emulate normal sockets).
"""
def ssl_method_wrapper(self, *args, **kwargs):
## print (id(self), method, args, kwargs)
start = time.time()
while True:
try:
return method(self, *args, **kwargs)
except (SSL.WantReadError, SSL.WantWriteError):
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errno = e.args[0]
if is_reader and errno in socket_errors_to_ignore:
return ""
raise socket.error(errno)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if is_reader and thirdarg == 'ssl handshake failure':
return ""
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise NoSSLError()
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
return ssl_method_wrapper
def _ssl_wrap_method(method, is_reader=False):
"""Wrap the given method with SSL error-trapping.
is_reader: if False (the default), EOF errors will be raised.
If True, EOF errors will return "" (to emulate normal sockets).
"""
def ssl_method_wrapper(self, *args, **kwargs):
## print (id(self), method, args, kwargs)
start = time.time()
while True:
try:
return method(self, *args, **kwargs)
except (SSL.WantReadError, SSL.WantWriteError):
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errno = e.args[0]
if is_reader and errno in socket_errors_to_ignore:
return ""
raise socket.error(errno)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if is_reader and thirdarg == 'ssl handshake failure':
return ""
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise NoSSLError()
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
return ssl_method_wrapper
def makefile(self, *args):
"""Specific to Python socket API and required by httplib: convert
response into a file-like object. This implementation reads using recv
and copies the output into a StringIO buffer to simulate a file object
for consumption by httplib
Nb. Ignoring optional file open mode (StringIO is generic and will
open for read and write unless a string is passed to the constructor)
and buffer size - httplib set a zero buffer size which results in recv
reading nothing
@return: file object for data returned from socket
@rtype: cStringIO.StringO
"""
self._makefile_refs += 1
# Optimisation
_buf_size = self.buf_size
i=0
stream = BytesIO()
startTime = datetime.utcnow()
try:
dat = self.__ssl_conn.recv(_buf_size)
while dat:
i+=1
stream.write(dat)
dat = self.__ssl_conn.recv(_buf_size)
except (SSL.ZeroReturnError, SSL.SysCallError):
# Connection is closed - assuming here that all is well and full
# response has been received. httplib will catch an error in
# incomplete content since it checks the content-length header
# against the actual length of data received
pass
if log.getEffectiveLevel() <= logging.DEBUG:
log.debug("Socket.makefile %d recv calls completed in %s", i,
datetime.utcnow() - startTime)
# Make sure to rewind the buffer otherwise consumers of the content will
# read from the end of the buffer
stream.seek(0)
return stream
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error, e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise NoSSLError()
raise FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")
def _safe_call(self, is_reader, call, *args, **kwargs):
"""Wrap the given call with SSL error-trapping.
is_reader: if False EOF errors will be raised. If True, EOF errors
will return "" (to emulate normal sockets).
"""
start = time.time()
while True:
try:
return call(*args, **kwargs)
except SSL.WantReadError:
# Sleep and try again. This is dangerous, because it means
# the rest of the stack has no way of differentiating
# between a "new handshake" error and "client dropped".
# Note this isn't an endless loop: there's a timeout below.
time.sleep(self.ssl_retry)
except SSL.WantWriteError:
time.sleep(self.ssl_retry)
except SSL.SysCallError as e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
errnum = e.args[0]
if is_reader and errnum in wsgiserver.socket_errors_to_ignore:
return ""
raise socket.error(errnum)
except SSL.Error as e:
if is_reader and e.args == (-1, 'Unexpected EOF'):
return ""
thirdarg = None
try:
thirdarg = e.args[0][0][2]
except IndexError:
pass
if thirdarg == 'http request':
# The client is talking HTTP to an HTTPS server.
raise wsgiserver.NoSSLError()
raise wsgiserver.FatalSSLAlert(*e.args)
except:
raise
if time.time() - start > self.ssl_timeout:
raise socket.timeout("timed out")