oauth_module = None
from . import response_lexer
-from .tls import IMAP4
+from . import tls
from .imap_utf7 import encode as encode_utf7, decode as decode_utf7
from .fixed_offset import FixedOffset
from .response_types import SearchIds
if 'IDLE' not in imaplib.Commands:
imaplib.Commands['IDLE'] = imaplib.Commands['APPEND']
+# ..and STARTTLS
+if 'STARTTLS' not in imaplib.Commands:
+ imaplib.Commands['STARTTLS'] = ('NONAUTH',)
+
# System flags
DELETED = r'\Deleted'
self.log_file = sys.stderr
self.normalise_times = True
+ self._starttls_done = False
self._cached_capabilities = None
self._imap = self._create_IMAP4(**kwargs)
self._imap._mesg = self._log # patch in custom debug log method
# Create the IMAP instance in a separate method to make unit tests easier
if self.stream:
return imaplib.IMAP4_stream(self.host)
- ImapClass = self.ssl and imaplib.IMAP4_SSL or IMAP4
+ ImapClass = self.ssl and imaplib.IMAP4_SSL or imaplib.IMAP4
return ImapClass(self.host, self.port, **kwargs)
def starttls(self, ssl_context=None):
Raises :py:exc:`AbortError` if the server does not support STARTTLS
or an SSL connection is already established.
-
"""
- return self._imap.starttls(ssl_context)
+ if self.ssl or self._starttls_done:
+ raise self.abort('TLS session already established')
+
+ typ, dat = self._imap._simple_command("STARTTLS")
+ if typ != 'OK':
+ raise self.Error("Couldn't establish TLS session")
+
+ self._tls_established = True
+ self._imap.sock = tls.wrap_socket(self._imap.sock, self.host, ssl_context)
+ self._imap.file = self._imap.sock.makefile()
+ return self._imap._untagged_response(typ, dat, "STARTTLS")
def login(self, username, password):
"""Login using *username* and *password*, returning the
server response.
"""
- return self._command_and_check('login', username, password, unpack=True)
+ return self._command_and_check(
+ 'login',
+ to_bytes(username),
+ to_bytes(password),
+ unpack=True,
+ )
def oauth_login(self, url, oauth_token, oauth_token_secret,
consumer_key='anonymous', consumer_secret='anonymous'):
# -*- coding: utf-8 -*-
"""STARTTLS support for imaplib for Python 2.6+ and 3.3+ built on pyOpenSSL."""
-__all__ = ('IMAP4', 'get_default_context')
+__all__ = ('get_default_context', 'wrap_socket')
import sys
import imaplib
except ImportError:
enum_certificates = lambda x: []
+
# third-party dependencies
from six import b, binary_type
from OpenSSL import SSL
from service_identity import VerificationError
from service_identity.pyopenssl import verify_hostname
-
-# add STARTTLS command support in imaplib if necessary
-if 'STARTTLS' not in imaplib.Commands:
- imaplib.Commands['STARTTLS'] = ('NONAUTH',)
-
# taken from Python 3.4 ssl module
_RESTRICTED_SERVER_CIPHERS = (
'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
return context
-class IMAP4(imaplib.IMAP4):
-
- def starttls(self, ssl_context=None):
- """Send a STARTTLS command and wrap the socket with TLS."""
- name = 'STARTTLS'
-
- if (isinstance(self, imaplib.IMAP4_SSL) or
- getattr(self, '_tls_established', False)):
- raise self.abort('TLS session already established')
-
- if name not in self.capabilities:
- raise self.abort('STARTTLS not supported by server')
-
- if not ssl_context:
- ssl_context = get_default_context()
-
- type_, dat = self._simple_command(name)
-
- if type_ == 'OK':
- self.sock = _SSLConnection(ssl_context, self.sock)
- self.sock.set_connect_state()
- self.sock.do_handshake()
+def wrap_socket(sock, host, ssl_context):
+ """XXX
+ """
+ if not ssl_context:
+ ssl_context = get_default_context()
- if getattr(ssl_context, 'check_hostname', True):
- try:
- verify_hostname(self.sock, self.host)
- except VerificationError:
- self.sock.shutdown()
- self.sock.close()
- raise self.abort(
- "Server certificate not valid for %s" % self.host)
+ sock = _SSLConnection(ssl_context, sock)
+ sock.set_connect_state()
+ sock.do_handshake()
- self.file = self.sock.makefile()
- self._tls_established = True
- else:
- raise self.Error("Couldn't establish TLS session")
+ if getattr(ssl_context, 'check_hostname', True):
+ try:
+ verify_hostname(sock, host)
+ except VerificationError:
+ sock.shutdown()
+ sock.close()
+ raise imaplib.Error("Server certificate not valid for %s" % host)
- return self._untagged_response(type_, dat, name)
+ return sock
class _SSLConnection(SSL.Connection):
# lifted from backports.ssl
+# XXX do we really have to copy this here?
class _socketfileobj(object):
"""Custom file-like object to support socket.makefile for pyOpenSSL."""