2007-07-04 19:53:48 +02:00
|
|
|
# imaplib utilities
|
2016-06-04 00:49:57 +02:00
|
|
|
# Copyright (C) 2002-2016 John Goerzen & contributors
|
2007-07-04 19:36:33 +02:00
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program; if not, write to the Free Software
|
|
|
|
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
2020-08-28 20:05:52 +02:00
|
|
|
import datetime
|
2011-04-13 10:52:18 +02:00
|
|
|
import os
|
|
|
|
import fcntl
|
2011-03-11 22:13:21 +01:00
|
|
|
import time
|
|
|
|
import subprocess
|
Update to match semantics of new imaplib2
The biggest change here is that imapobj.untagged_responses is no
longer a dictionary, but a list. To access it, I use the semi-private
_get_untagged_response method.
* offlineimap/folder/IMAP.py (IMAPFolder.quickchanged,
IMAPFolder.cachemessagelist): imaplib2 now explicitly removes its
EXISTS response on select(), so instead we use the return values from
select() to get the number of messages.
* offlineimap/imapserver.py (UsefulIMAPMixIn.select): imaplib2 now
stores untagged_responses for different mailboxes, which confuses us
because it seems like our mailboxes are "still" in read-only mode when
we just re-opened them. Additionally, we have to return the value
from imaplib2's select() so that the above thing works.
* offlineimap/imapserver.py (UsefulIMAPMixIn._mesg): imaplib2 now
calls _mesg with the name of a thread, so we display this
information in debug output. This requires a corresponding change to
imaplibutil.new_mesg.
* offlineimap/imaplibutil.py: We override IMAP4_SSL.open, whose
default arguments have changed, so update the default arguments. We
also subclass imaplib.IMAP4 in a few different places, which now
relies on having a read_fd file descriptor to poll on.
Signed-off-by: Ethan Glasser-Camp <ethan@betacantrips.com>
Signed-off-by: Nicolas Sebrecht <nicolas.s-dev@laposte.net>
2011-03-10 21:36:20 +01:00
|
|
|
import threading
|
2019-06-10 13:47:37 +02:00
|
|
|
import rfc6555
|
2015-02-15 15:16:20 +01:00
|
|
|
import socket
|
2015-02-17 10:33:56 +01:00
|
|
|
import errno
|
2016-06-04 00:49:57 +02:00
|
|
|
import zlib
|
2016-06-29 03:42:57 +02:00
|
|
|
from sys import exc_info
|
2018-05-14 00:20:37 +02:00
|
|
|
from hashlib import sha512, sha384, sha256, sha224, sha1
|
2011-09-12 09:50:41 +02:00
|
|
|
|
2016-07-25 03:20:53 +02:00
|
|
|
import six
|
|
|
|
|
2011-05-07 18:39:13 +02:00
|
|
|
from offlineimap import OfflineImapError
|
2016-06-29 03:42:57 +02:00
|
|
|
from offlineimap.ui import getglobalui
|
2020-08-28 20:05:52 +02:00
|
|
|
from offlineimap.virtual_imaplib2 import IMAP4, IMAP4_SSL, InternalDate
|
2016-05-17 19:56:52 +02:00
|
|
|
|
2007-07-04 20:17:27 +02:00
|
|
|
|
2011-11-02 08:40:03 +01:00
|
|
|
class UsefulIMAPMixIn(object):
|
2014-03-16 13:27:35 +01:00
|
|
|
def __getselectedfolder(self):
|
2011-07-06 23:15:33 +02:00
|
|
|
if self.state == 'SELECTED':
|
|
|
|
return self.mailbox
|
2011-03-22 15:51:43 +01:00
|
|
|
return None
|
|
|
|
|
2015-01-01 21:41:11 +01:00
|
|
|
def select(self, mailbox='INBOX', readonly=False, force=False):
|
2011-05-07 18:39:13 +02:00
|
|
|
"""Selects a mailbox on the IMAP server
|
|
|
|
|
|
|
|
:returns: 'OK' on success, nothing if the folder was already
|
2015-01-01 21:41:11 +01:00
|
|
|
selected or raises an :exc:`OfflineImapError`."""
|
|
|
|
|
2015-01-14 22:58:25 +01:00
|
|
|
if self.__getselectedfolder() == mailbox and \
|
2020-08-29 20:17:18 +02:00
|
|
|
self.is_readonly == readonly and \
|
|
|
|
not force:
|
2011-03-22 15:51:43 +01:00
|
|
|
# No change; return.
|
|
|
|
return
|
2011-09-01 11:00:59 +02:00
|
|
|
try:
|
2011-11-02 08:40:03 +01:00
|
|
|
result = super(UsefulIMAPMixIn, self).select(mailbox, readonly)
|
2012-08-05 20:40:52 +02:00
|
|
|
except self.readonly as e:
|
|
|
|
# pass self.readonly to our callers
|
|
|
|
raise
|
2012-02-05 10:14:23 +01:00
|
|
|
except self.abort as e:
|
2011-09-01 11:00:59 +02:00
|
|
|
# self.abort is raised when we are supposed to retry
|
2020-08-29 20:17:18 +02:00
|
|
|
errstr = "Server '%s' closed connection, error on SELECT '%s'. Ser" \
|
|
|
|
"ver said: %s" % (self.host, mailbox, e.args[0])
|
2011-09-01 11:00:59 +02:00
|
|
|
severity = OfflineImapError.ERROR.FOLDER_RETRY
|
2016-06-29 03:42:57 +02:00
|
|
|
six.reraise(OfflineImapError,
|
|
|
|
OfflineImapError(errstr, severity),
|
|
|
|
exc_info()[2])
|
2011-03-22 15:51:43 +01:00
|
|
|
if result[0] != 'OK':
|
2020-08-29 20:17:18 +02:00
|
|
|
# in case of error, bail out with OfflineImapError
|
|
|
|
errstr = "Error SELECTing mailbox '%s', server reply:\n%s" % \
|
|
|
|
(mailbox, result)
|
2011-05-07 18:39:13 +02:00
|
|
|
severity = OfflineImapError.ERROR.FOLDER
|
2011-11-02 08:40:03 +01:00
|
|
|
raise OfflineImapError(errstr, severity)
|
2011-03-22 15:51:43 +01:00
|
|
|
return result
|
|
|
|
|
2014-03-16 13:27:35 +01:00
|
|
|
# Overrides private function from IMAP4 (@imaplib2)
|
2011-03-22 15:51:43 +01:00
|
|
|
def _mesg(self, s, tn=None, secs=None):
|
|
|
|
new_mesg(self, s, tn, secs)
|
|
|
|
|
2015-02-15 15:16:20 +01:00
|
|
|
# Overrides private function from IMAP4 (@imaplib2)
|
|
|
|
def open_socket(self):
|
|
|
|
"""open_socket()
|
|
|
|
Open socket choosing first address family available."""
|
2019-06-10 13:47:37 +02:00
|
|
|
if self.af == socket.AF_UNSPEC:
|
|
|
|
# happy-eyeballs!
|
|
|
|
return rfc6555.create_connection((self.host, self.port))
|
|
|
|
else:
|
|
|
|
return self._open_socket_for_af(self.af)
|
|
|
|
|
|
|
|
def _open_socket_for_af(self, af):
|
2015-02-15 15:16:20 +01:00
|
|
|
msg = (-1, 'could not open socket')
|
2019-06-10 13:47:37 +02:00
|
|
|
for res in socket.getaddrinfo(self.host, self.port, af, socket.SOCK_STREAM):
|
2015-02-15 15:16:20 +01:00
|
|
|
af, socktype, proto, canonname, sa = res
|
|
|
|
try:
|
|
|
|
# use socket of our own, possiblly socksified socket.
|
|
|
|
s = self.socket(af, socktype, proto)
|
2016-05-08 15:10:57 +02:00
|
|
|
except socket.error as msg:
|
2015-02-15 15:16:20 +01:00
|
|
|
continue
|
|
|
|
try:
|
|
|
|
for i in (0, 1):
|
|
|
|
try:
|
|
|
|
s.connect(sa)
|
|
|
|
break
|
2016-05-08 15:10:57 +02:00
|
|
|
except socket.error as msg:
|
2015-02-15 15:16:20 +01:00
|
|
|
if len(msg.args) < 2 or msg.args[0] != errno.EINTR:
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
raise socket.error(msg)
|
2016-05-08 15:10:57 +02:00
|
|
|
except socket.error as msg:
|
2015-02-15 15:16:20 +01:00
|
|
|
s.close()
|
|
|
|
continue
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise socket.error(msg)
|
|
|
|
|
|
|
|
return s
|
|
|
|
|
2015-01-01 21:41:11 +01:00
|
|
|
|
2011-03-22 15:51:44 +01:00
|
|
|
class IMAP4_Tunnel(UsefulIMAPMixIn, IMAP4):
|
2007-07-04 19:36:33 +02:00
|
|
|
"""IMAP4 client class over a tunnel
|
|
|
|
|
|
|
|
Instantiate with: IMAP4_Tunnel(tunnelcmd)
|
|
|
|
|
|
|
|
tunnelcmd -- shell command to generate the tunnel.
|
|
|
|
The result will be in PREAUTH stage."""
|
|
|
|
|
2011-04-13 10:52:18 +02:00
|
|
|
def __init__(self, tunnelcmd, **kwargs):
|
2015-02-15 15:16:20 +01:00
|
|
|
if "use_socket" in kwargs:
|
|
|
|
self.socket = kwargs['use_socket']
|
|
|
|
del kwargs['use_socket']
|
2011-04-13 10:52:18 +02:00
|
|
|
IMAP4.__init__(self, tunnelcmd, **kwargs)
|
2007-07-04 19:36:33 +02:00
|
|
|
|
|
|
|
def open(self, host, port):
|
|
|
|
"""The tunnelcmd comes in on host!"""
|
2015-01-01 21:41:11 +01:00
|
|
|
|
2011-04-13 10:52:18 +02:00
|
|
|
self.host = host
|
2007-07-04 19:36:33 +02:00
|
|
|
self.process = subprocess.Popen(host, shell=True, close_fds=True,
|
2020-08-29 20:17:18 +02:00
|
|
|
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
2007-07-04 19:36:33 +02:00
|
|
|
(self.outfd, self.infd) = (self.process.stdin, self.process.stdout)
|
Update to match semantics of new imaplib2
The biggest change here is that imapobj.untagged_responses is no
longer a dictionary, but a list. To access it, I use the semi-private
_get_untagged_response method.
* offlineimap/folder/IMAP.py (IMAPFolder.quickchanged,
IMAPFolder.cachemessagelist): imaplib2 now explicitly removes its
EXISTS response on select(), so instead we use the return values from
select() to get the number of messages.
* offlineimap/imapserver.py (UsefulIMAPMixIn.select): imaplib2 now
stores untagged_responses for different mailboxes, which confuses us
because it seems like our mailboxes are "still" in read-only mode when
we just re-opened them. Additionally, we have to return the value
from imaplib2's select() so that the above thing works.
* offlineimap/imapserver.py (UsefulIMAPMixIn._mesg): imaplib2 now
calls _mesg with the name of a thread, so we display this
information in debug output. This requires a corresponding change to
imaplibutil.new_mesg.
* offlineimap/imaplibutil.py: We override IMAP4_SSL.open, whose
default arguments have changed, so update the default arguments. We
also subclass imaplib.IMAP4 in a few different places, which now
relies on having a read_fd file descriptor to poll on.
Signed-off-by: Ethan Glasser-Camp <ethan@betacantrips.com>
Signed-off-by: Nicolas Sebrecht <nicolas.s-dev@laposte.net>
2011-03-10 21:36:20 +01:00
|
|
|
# imaplib2 polls on this fd
|
|
|
|
self.read_fd = self.infd.fileno()
|
2007-07-04 19:36:33 +02:00
|
|
|
|
2011-04-13 10:52:18 +02:00
|
|
|
self.set_nonblocking(self.read_fd)
|
|
|
|
|
|
|
|
def set_nonblocking(self, fd):
|
2015-01-01 21:41:11 +01:00
|
|
|
"""Mark fd as nonblocking"""
|
|
|
|
|
2011-04-13 10:52:18 +02:00
|
|
|
# get the file's current flag settings
|
|
|
|
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
|
|
|
|
# clear non-blocking mode from flags
|
|
|
|
fl = fl & ~os.O_NONBLOCK
|
|
|
|
fcntl.fcntl(fd, fcntl.F_SETFL, fl)
|
|
|
|
|
2007-07-04 19:36:33 +02:00
|
|
|
def read(self, size):
|
2011-04-13 10:52:18 +02:00
|
|
|
"""data = read(size)
|
|
|
|
Read at most 'size' bytes from remote."""
|
2007-07-04 19:36:33 +02:00
|
|
|
|
2011-04-13 10:52:18 +02:00
|
|
|
if self.decompressor is None:
|
|
|
|
return os.read(self.read_fd, size)
|
|
|
|
|
|
|
|
if self.decompressor.unconsumed_tail:
|
|
|
|
data = self.decompressor.unconsumed_tail
|
|
|
|
else:
|
|
|
|
data = os.read(self.read_fd, 8192)
|
|
|
|
|
|
|
|
return self.decompressor.decompress(data, size)
|
2007-07-04 19:36:33 +02:00
|
|
|
|
|
|
|
def send(self, data):
|
2011-04-13 10:52:18 +02:00
|
|
|
if self.compressor is not None:
|
|
|
|
data = self.compressor.compress(data)
|
|
|
|
data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
|
2007-07-04 19:36:33 +02:00
|
|
|
self.outfd.write(data)
|
|
|
|
|
|
|
|
def shutdown(self):
|
|
|
|
self.infd.close()
|
|
|
|
self.outfd.close()
|
|
|
|
self.process.wait()
|
|
|
|
|
|
|
|
|
Update to match semantics of new imaplib2
The biggest change here is that imapobj.untagged_responses is no
longer a dictionary, but a list. To access it, I use the semi-private
_get_untagged_response method.
* offlineimap/folder/IMAP.py (IMAPFolder.quickchanged,
IMAPFolder.cachemessagelist): imaplib2 now explicitly removes its
EXISTS response on select(), so instead we use the return values from
select() to get the number of messages.
* offlineimap/imapserver.py (UsefulIMAPMixIn.select): imaplib2 now
stores untagged_responses for different mailboxes, which confuses us
because it seems like our mailboxes are "still" in read-only mode when
we just re-opened them. Additionally, we have to return the value
from imaplib2's select() so that the above thing works.
* offlineimap/imapserver.py (UsefulIMAPMixIn._mesg): imaplib2 now
calls _mesg with the name of a thread, so we display this
information in debug output. This requires a corresponding change to
imaplibutil.new_mesg.
* offlineimap/imaplibutil.py: We override IMAP4_SSL.open, whose
default arguments have changed, so update the default arguments. We
also subclass imaplib.IMAP4 in a few different places, which now
relies on having a read_fd file descriptor to poll on.
Signed-off-by: Ethan Glasser-Camp <ethan@betacantrips.com>
Signed-off-by: Nicolas Sebrecht <nicolas.s-dev@laposte.net>
2011-03-10 21:36:20 +01:00
|
|
|
def new_mesg(self, s, tn=None, secs=None):
|
2020-08-29 20:17:18 +02:00
|
|
|
if secs is None:
|
|
|
|
secs = time.time()
|
|
|
|
if tn is None:
|
|
|
|
tn = threading.currentThread().getName()
|
|
|
|
tm = time.strftime('%M:%S', time.localtime(secs))
|
|
|
|
getglobalui().debug('imap', ' %s.%02d %s %s' % (tm, (secs * 100) % 100, tn, s))
|
2007-07-04 19:36:33 +02:00
|
|
|
|
2011-08-15 11:55:42 +02:00
|
|
|
|
2011-03-22 15:51:44 +01:00
|
|
|
class WrappedIMAP4_SSL(UsefulIMAPMixIn, IMAP4_SSL):
|
2015-01-01 21:41:11 +01:00
|
|
|
"""Improved version of imaplib.IMAP4_SSL overriding select()."""
|
|
|
|
|
2011-09-12 09:50:41 +02:00
|
|
|
def __init__(self, *args, **kwargs):
|
2016-02-23 01:45:18 +01:00
|
|
|
if "af" in kwargs:
|
|
|
|
self.af = kwargs['af']
|
|
|
|
del kwargs['af']
|
2015-02-15 15:16:20 +01:00
|
|
|
if "use_socket" in kwargs:
|
|
|
|
self.socket = kwargs['use_socket']
|
|
|
|
del kwargs['use_socket']
|
2011-09-12 09:50:41 +02:00
|
|
|
self._fingerprint = kwargs.get('fingerprint', None)
|
2014-05-06 23:22:29 +02:00
|
|
|
if type(self._fingerprint) != type([]):
|
|
|
|
self._fingerprint = [self._fingerprint]
|
2012-02-05 13:40:06 +01:00
|
|
|
if 'fingerprint' in kwargs:
|
2011-09-12 09:50:41 +02:00
|
|
|
del kwargs['fingerprint']
|
|
|
|
super(WrappedIMAP4_SSL, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def open(self, host=None, port=None):
|
2014-05-06 23:22:29 +02:00
|
|
|
if not self.ca_certs and not self._fingerprint:
|
2015-01-01 21:41:11 +01:00
|
|
|
raise OfflineImapError("No CA certificates "
|
2020-08-29 20:17:18 +02:00
|
|
|
"and no server fingerprints configured. "
|
|
|
|
"You must configure at least something, otherwise "
|
|
|
|
"having SSL helps nothing.", OfflineImapError.ERROR.REPO)
|
2011-09-12 09:50:41 +02:00
|
|
|
super(WrappedIMAP4_SSL, self).open(host, port)
|
2014-05-06 23:22:29 +02:00
|
|
|
if self._fingerprint:
|
2018-05-14 00:20:37 +02:00
|
|
|
server_cert = self.sock.getpeercert(True)
|
|
|
|
hashes = sha512, sha384, sha256, sha224, sha1
|
|
|
|
server_fingerprints = [hash(server_cert).hexdigest() for hash in hashes]
|
2011-09-12 09:50:41 +02:00
|
|
|
# compare fingerprints
|
2018-05-14 00:20:37 +02:00
|
|
|
matches = [(server_fingerprint in self._fingerprint) for server_fingerprint in server_fingerprints]
|
|
|
|
if not any(matches):
|
2018-05-14 09:56:33 +02:00
|
|
|
raise OfflineImapError("Server SSL fingerprint(s) '%s' "
|
2020-08-29 20:17:18 +02:00
|
|
|
"for hostname '%s' "
|
|
|
|
"does not match configured fingerprint(s) %s. "
|
|
|
|
"Please verify and set 'cert_fingerprint' accordingly "
|
|
|
|
"if not set yet." %
|
|
|
|
(list(zip([hash.__name__ for hash in hashes], server_fingerprints)), host,
|
|
|
|
self._fingerprint),
|
|
|
|
OfflineImapError.ERROR.REPO)
|
2010-12-16 13:43:47 +01:00
|
|
|
|
|
|
|
|
2011-03-22 15:51:44 +01:00
|
|
|
class WrappedIMAP4(UsefulIMAPMixIn, IMAP4):
|
2015-01-01 21:41:11 +01:00
|
|
|
"""Improved version of imaplib.IMAP4 overriding select()."""
|
|
|
|
|
2015-02-15 15:16:20 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
2016-02-23 01:45:18 +01:00
|
|
|
if "af" in kwargs:
|
|
|
|
self.af = kwargs['af']
|
|
|
|
del kwargs['af']
|
2015-02-15 15:16:20 +01:00
|
|
|
if "use_socket" in kwargs:
|
|
|
|
self.socket = kwargs['use_socket']
|
|
|
|
del kwargs['use_socket']
|
|
|
|
IMAP4.__init__(self, *args, **kwargs)
|
2010-12-16 13:43:46 +01:00
|
|
|
|
Update to match semantics of new imaplib2
The biggest change here is that imapobj.untagged_responses is no
longer a dictionary, but a list. To access it, I use the semi-private
_get_untagged_response method.
* offlineimap/folder/IMAP.py (IMAPFolder.quickchanged,
IMAPFolder.cachemessagelist): imaplib2 now explicitly removes its
EXISTS response on select(), so instead we use the return values from
select() to get the number of messages.
* offlineimap/imapserver.py (UsefulIMAPMixIn.select): imaplib2 now
stores untagged_responses for different mailboxes, which confuses us
because it seems like our mailboxes are "still" in read-only mode when
we just re-opened them. Additionally, we have to return the value
from imaplib2's select() so that the above thing works.
* offlineimap/imapserver.py (UsefulIMAPMixIn._mesg): imaplib2 now
calls _mesg with the name of a thread, so we display this
information in debug output. This requires a corresponding change to
imaplibutil.new_mesg.
* offlineimap/imaplibutil.py: We override IMAP4_SSL.open, whose
default arguments have changed, so update the default arguments. We
also subclass imaplib.IMAP4 in a few different places, which now
relies on having a read_fd file descriptor to poll on.
Signed-off-by: Ethan Glasser-Camp <ethan@betacantrips.com>
Signed-off-by: Nicolas Sebrecht <nicolas.s-dev@laposte.net>
2011-03-10 21:36:20 +01:00
|
|
|
|
2007-07-04 19:36:33 +02:00
|
|
|
def Internaldate2epoch(resp):
|
|
|
|
"""Convert IMAP4 INTERNALDATE to UT.
|
|
|
|
|
2015-01-01 21:41:11 +01:00
|
|
|
Returns seconds since the epoch."""
|
2007-07-04 19:36:33 +02:00
|
|
|
|
2015-03-21 07:15:25 +01:00
|
|
|
from calendar import timegm
|
|
|
|
|
2007-07-04 19:36:33 +02:00
|
|
|
mo = InternalDate.match(resp)
|
|
|
|
if not mo:
|
|
|
|
return None
|
|
|
|
|
2020-08-28 20:05:52 +02:00
|
|
|
# Get the month number
|
|
|
|
datetime_object = datetime.datetime.strptime(mo.group('mon'), "%b")
|
|
|
|
mon = datetime_object.month
|
|
|
|
|
2007-07-04 19:36:33 +02:00
|
|
|
zonen = mo.group('zonen')
|
|
|
|
|
|
|
|
day = int(mo.group('day'))
|
|
|
|
year = int(mo.group('year'))
|
|
|
|
hour = int(mo.group('hour'))
|
|
|
|
min = int(mo.group('min'))
|
|
|
|
sec = int(mo.group('sec'))
|
|
|
|
zoneh = int(mo.group('zoneh'))
|
|
|
|
zonem = int(mo.group('zonem'))
|
|
|
|
|
|
|
|
# INTERNALDATE timezone must be subtracted to get UT
|
|
|
|
|
2020-08-29 20:17:18 +02:00
|
|
|
zone = (zoneh * 60 + zonem) * 60
|
2007-07-04 19:36:33 +02:00
|
|
|
if zonen == '-':
|
|
|
|
zone = -zone
|
|
|
|
|
|
|
|
tt = (year, mon, day, hour, min, sec, -1, -1, -1)
|
|
|
|
|
2015-03-21 07:15:25 +01:00
|
|
|
return timegm(tt) - zone
|