From: Menno Smits Date: Tue, 1 Sep 2015 00:55:39 +0000 (+1200) Subject: Added support for a socket timeout X-Git-Tag: 1.0.0~1^2~32 X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=2ea3892397789fdd169225ddd1888bd263e23442;p=imapclient.git Added support for a socket timeout Closes #47. --- diff --git a/NEWS.rst b/NEWS.rst index f3022d7..f9a5417 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -2,8 +2,8 @@ 1.0.0 ======= -Enhanced TLS support --------------------- +Enhanced TLS support [API] +-------------------------- The way that IMAPClient establishes TLS/SSL connections has been completed reworked. By default IMAPClient will attempt certificate verification, certificate hostname checking, and will not use @@ -39,8 +39,8 @@ on all of the above. Many thanks to Chris Arndt and Marc-Antoine Parent for their input into these TLS improvements. -STARTTLS support ----------------- +STARTTLS support [NEW] +---------------------- When the server supports it, IMAPClient can now establish an encrypted connection after initially connection unencrypted via STARTTLS. The starttls method takes an SSL context object for controlling the @@ -121,6 +121,12 @@ The following are valid examples:: c.search(['TEXT', u'\u263a'], 'utf-8') # IMAPClient will apply UTF-8 encoding c.search([b'TEXT', b'\xe2\x98\xba'], 'utf-8') # Caller has applied UTF-8 encoding +Socket timeout support [NEW] +---------------------------- +IMAPClient now accepts a timeout at creation time. The timeout applies +while establishing the connection and for all operations on the socket +connected to the IMAP server. + Performance optimisation for parsing message id lists ---------------------------------------------------- A short circuit is now used when parsing a list of message ids which diff --git a/imapclient/config.py b/imapclient/config.py index 76c5ccd..af95a04 100644 --- a/imapclient/config.py +++ b/imapclient/config.py @@ -37,6 +37,7 @@ def parse_config_file(filename): ssl_check_hostname='true', ssl_verify_cert='true', ssl_ca_file=None, + timeout=None, starttls='false', stream='false', oauth='false', @@ -67,11 +68,20 @@ def _read_config_section(parser, section): get = lambda name: parser.get(section, name) getboolean = lambda name: parser.getboolean(section, name) - def getint(name): + def get_allowing_none(name, typefunc): try: - return parser.getint(section, name) + v = parser.get(section, name) except NoOptionError: return None + if not v: + return None + return typefunc(v) + + def getint(name): + return get_allowing_none(name, int) + + def getfloat(name): + return get_allowing_none(name, float) ssl_ca_file = get('ssl_ca_file') if ssl_ca_file: @@ -85,6 +95,7 @@ def _read_config_section(parser, section): ssl_check_hostname=getboolean('ssl_check_hostname'), ssl_verify_cert=getboolean('ssl_verify_cert'), ssl_ca_file=ssl_ca_file, + timeout=getfloat('timeout'), stream=getboolean('stream'), @@ -143,7 +154,8 @@ def create_client_from_config(conf): client = imapclient.IMAPClient(conf.host, port=conf.port, ssl=conf.ssl, ssl_context=ssl_context, - stream=conf.stream) + stream=conf.stream, + timeout=conf.timeout) try: if conf.starttls: client.starttls() diff --git a/imapclient/imap4.py b/imapclient/imap4.py new file mode 100644 index 0000000..a817f1e --- /dev/null +++ b/imapclient/imap4.py @@ -0,0 +1,17 @@ +# Copyright (c) 2015, Menno Smits +# Released subject to the New BSD License +# Please see http://en.wikipedia.org/wiki/BSD_licenses + +import imaplib +import socket + + +class IMAP4WithTimeout(imaplib.IMAP4): + + def __init__(self, address, port, connection_timeout): + self._connection_timeout = connection_timeout + super(IMAP4WithTimeout, self).__init__(address, port) + + def _create_socket(self): + return socket.create_connection((self.host, self.port), + self._connection_timeout) diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py index 5032561..2760584 100644 --- a/imapclient/imapclient.py +++ b/imapclient/imapclient.py @@ -21,6 +21,7 @@ try: except ImportError: oauth_module = None +from . import imap4 from . import response_lexer from . import tls from .datetime_util import datetime_to_INTERNALDATE @@ -95,6 +96,11 @@ class IMAPClient(object): ``False``). This is useful for exotic connection or authentication setups. + Use *timeout* to specify a timeout for the socket connected to the + IMAP server. The timeout applies during the initial connection to + the server and for all future socket reads and writes. The default + is for no timeout to be used. + The *normalise_times* attribute specifies whether datetimes returned by ``fetch()`` are normalised to the local system time and include no timezone information (native), or are datetimes @@ -120,7 +126,7 @@ class IMAPClient(object): ReadOnlyError = imaplib.IMAP4.readonly def __init__(self, host, port=None, use_uid=True, ssl=False, stream=False, - ssl_context=None): + ssl_context=None, timeout=None): if stream: if port is not None: raise ValueError("can't set 'port' when 'stream' True") @@ -139,20 +145,34 @@ class IMAPClient(object): self.log_file = sys.stderr self.normalise_times = True + self._timeout = timeout self._starttls_done = False self._cached_capabilities = None self._imap = self._create_IMAP4() self._imap._mesg = self._log # patch in custom debug log method self._idle_tag = None + self._set_timeout() + def _create_IMAP4(self): if self.stream: return imaplib.IMAP4_stream(self.host) if self.ssl: - return tls.IMAP4_TLS(self.host, self.port, self.ssl_context) + return tls.IMAP4_TLS(self.host, self.port, self.ssl_context, + self._timeout) + + return imap4.IMAP4WithTimeout(self.host, self.port, self._timeout) + + def _set_timeout(self): + if self._timeout is not None: + self._sock.settimeout(self._timeout) - return imaplib.IMAP4(self.host, self.port) + @property + def _sock(self): + # In py2, imaplib has sslobj (for SSL connections), and sock for non-SSL. + # In the py3 version it's just sock. + return getattr(self._imap, 'sslobj', self._imap.sock) def starttls(self, ssl_context=None): """Switch to an SSL encrypted connection by sending a STARTTLS command. @@ -529,12 +549,11 @@ class IMAPClient(object): (1, b'EXISTS'), (1, b'FETCH', (b'FLAGS', (b'\\NotJunk',)))] """ - # In py2, imaplib has sslobj (for SSL connections), and sock for non-SSL. - # In the py3 version it's just sock. - sock = getattr(self._imap, 'sslobj', self._imap.sock) + sock = self._sock # make the socket non-blocking so the timeout can be # implemented for this call + sock.settimeout(None) sock.setblocking(0) try: resps = [] @@ -558,6 +577,7 @@ class IMAPClient(object): return resps finally: sock.setblocking(1) + self._set_timeout() def idle_done(self): """Take the server out of IDLE mode. diff --git a/imapclient/tls.py b/imapclient/tls.py index 6c85fde..0144924 100644 --- a/imapclient/tls.py +++ b/imapclient/tls.py @@ -147,14 +147,15 @@ class IMAP4_TLS(imaplib.IMAP4): Adapted from imaplib.IMAP4_SSL. """ - def __init__(self, host, port, ssl_context): + def __init__(self, host, port, ssl_context, timeout): self.ssl_context = ssl_context + self._timeout = timeout imaplib.IMAP4.__init__(self, host, port) def open(self, host, port): self.host = host self.port = port - sock = socket.create_connection((host, port)) + sock = socket.create_connection((host, port), self._timeout) self.sock = wrap_socket(sock, self.ssl_context, host) self.file = self.sock.makefile('rb')