imaplibutil.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # imaplib utilities
  2. # Copyright (C) 2002-2016 John Goerzen & contributors
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. import os
  17. import fcntl
  18. import time
  19. import subprocess
  20. import threading
  21. import socket
  22. import errno
  23. import zlib
  24. from sys import exc_info
  25. from hashlib import sha1
  26. import six
  27. from offlineimap import OfflineImapError
  28. from offlineimap.ui import getglobalui
  29. from offlineimap.virtual_imaplib2 import IMAP4, IMAP4_SSL, InternalDate, Mon2num
  30. class UsefulIMAPMixIn(object):
  31. def __getselectedfolder(self):
  32. if self.state == 'SELECTED':
  33. return self.mailbox
  34. return None
  35. def select(self, mailbox='INBOX', readonly=False, force=False):
  36. """Selects a mailbox on the IMAP server
  37. :returns: 'OK' on success, nothing if the folder was already
  38. selected or raises an :exc:`OfflineImapError`."""
  39. if self.__getselectedfolder() == mailbox and \
  40. self.is_readonly == readonly and \
  41. not force:
  42. # No change; return.
  43. return
  44. try:
  45. result = super(UsefulIMAPMixIn, self).select(mailbox, readonly)
  46. except self.readonly as e:
  47. # pass self.readonly to our callers
  48. raise
  49. except self.abort as e:
  50. # self.abort is raised when we are supposed to retry
  51. errstr = "Server '%s' closed connection, error on SELECT '%s'. Ser"\
  52. "ver said: %s" % (self.host, mailbox, e.args[0])
  53. severity = OfflineImapError.ERROR.FOLDER_RETRY
  54. six.reraise(OfflineImapError,
  55. OfflineImapError(errstr, severity),
  56. exc_info()[2])
  57. if result[0] != 'OK':
  58. #in case of error, bail out with OfflineImapError
  59. errstr = "Error SELECTing mailbox '%s', server reply:\n%s" %\
  60. (mailbox, result)
  61. severity = OfflineImapError.ERROR.FOLDER
  62. raise OfflineImapError(errstr, severity)
  63. return result
  64. # Overrides private function from IMAP4 (@imaplib2)
  65. def _mesg(self, s, tn=None, secs=None):
  66. new_mesg(self, s, tn, secs)
  67. # Overrides private function from IMAP4 (@imaplib2)
  68. def open_socket(self):
  69. """open_socket()
  70. Open socket choosing first address family available."""
  71. msg = (-1, 'could not open socket')
  72. for res in socket.getaddrinfo(self.host, self.port, self.af, socket.SOCK_STREAM):
  73. af, socktype, proto, canonname, sa = res
  74. try:
  75. # use socket of our own, possiblly socksified socket.
  76. s = self.socket(af, socktype, proto)
  77. except socket.error as msg:
  78. continue
  79. try:
  80. for i in (0, 1):
  81. try:
  82. s.connect(sa)
  83. break
  84. except socket.error as msg:
  85. if len(msg.args) < 2 or msg.args[0] != errno.EINTR:
  86. raise
  87. else:
  88. raise socket.error(msg)
  89. except socket.error as msg:
  90. s.close()
  91. continue
  92. break
  93. else:
  94. raise socket.error(msg)
  95. return s
  96. class IMAP4_Tunnel(UsefulIMAPMixIn, IMAP4):
  97. """IMAP4 client class over a tunnel
  98. Instantiate with: IMAP4_Tunnel(tunnelcmd)
  99. tunnelcmd -- shell command to generate the tunnel.
  100. The result will be in PREAUTH stage."""
  101. def __init__(self, tunnelcmd, **kwargs):
  102. if "use_socket" in kwargs:
  103. self.socket = kwargs['use_socket']
  104. del kwargs['use_socket']
  105. IMAP4.__init__(self, tunnelcmd, **kwargs)
  106. def open(self, host, port):
  107. """The tunnelcmd comes in on host!"""
  108. self.host = host
  109. self.process = subprocess.Popen(host, shell=True, close_fds=True,
  110. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  111. (self.outfd, self.infd) = (self.process.stdin, self.process.stdout)
  112. # imaplib2 polls on this fd
  113. self.read_fd = self.infd.fileno()
  114. self.set_nonblocking(self.read_fd)
  115. def set_nonblocking(self, fd):
  116. """Mark fd as nonblocking"""
  117. # get the file's current flag settings
  118. fl = fcntl.fcntl(fd, fcntl.F_GETFL)
  119. # clear non-blocking mode from flags
  120. fl = fl & ~os.O_NONBLOCK
  121. fcntl.fcntl(fd, fcntl.F_SETFL, fl)
  122. def read(self, size):
  123. """data = read(size)
  124. Read at most 'size' bytes from remote."""
  125. if self.decompressor is None:
  126. return os.read(self.read_fd, size)
  127. if self.decompressor.unconsumed_tail:
  128. data = self.decompressor.unconsumed_tail
  129. else:
  130. data = os.read(self.read_fd, 8192)
  131. return self.decompressor.decompress(data, size)
  132. def send(self, data):
  133. if self.compressor is not None:
  134. data = self.compressor.compress(data)
  135. data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
  136. self.outfd.write(data)
  137. def shutdown(self):
  138. self.infd.close()
  139. self.outfd.close()
  140. self.process.wait()
  141. def new_mesg(self, s, tn=None, secs=None):
  142. if secs is None:
  143. secs = time.time()
  144. if tn is None:
  145. tn = threading.currentThread().getName()
  146. tm = time.strftime('%M:%S', time.localtime(secs))
  147. getglobalui().debug('imap', ' %s.%02d %s %s' % (tm, (secs*100)%100, tn, s))
  148. class WrappedIMAP4_SSL(UsefulIMAPMixIn, IMAP4_SSL):
  149. """Improved version of imaplib.IMAP4_SSL overriding select()."""
  150. def __init__(self, *args, **kwargs):
  151. if "af" in kwargs:
  152. self.af = kwargs['af']
  153. del kwargs['af']
  154. if "use_socket" in kwargs:
  155. self.socket = kwargs['use_socket']
  156. del kwargs['use_socket']
  157. self._fingerprint = kwargs.get('fingerprint', None)
  158. if type(self._fingerprint) != type([]):
  159. self._fingerprint = [self._fingerprint]
  160. if 'fingerprint' in kwargs:
  161. del kwargs['fingerprint']
  162. super(WrappedIMAP4_SSL, self).__init__(*args, **kwargs)
  163. def open(self, host=None, port=None):
  164. if not self.ca_certs and not self._fingerprint:
  165. raise OfflineImapError("No CA certificates "
  166. "and no server fingerprints configured. "
  167. "You must configure at least something, otherwise "
  168. "having SSL helps nothing.", OfflineImapError.ERROR.REPO)
  169. super(WrappedIMAP4_SSL, self).open(host, port)
  170. if self._fingerprint:
  171. # compare fingerprints
  172. fingerprint = sha1(self.sock.getpeercert(True)).hexdigest()
  173. if fingerprint not in self._fingerprint:
  174. raise OfflineImapError("Server SSL fingerprint '%s' "
  175. "for hostname '%s' "
  176. "does not match configured fingerprint(s) %s. "
  177. "Please verify and set 'cert_fingerprint' accordingly "
  178. "if not set yet."%
  179. (fingerprint, host, self._fingerprint),
  180. OfflineImapError.ERROR.REPO)
  181. class WrappedIMAP4(UsefulIMAPMixIn, IMAP4):
  182. """Improved version of imaplib.IMAP4 overriding select()."""
  183. def __init__(self, *args, **kwargs):
  184. if "af" in kwargs:
  185. self.af = kwargs['af']
  186. del kwargs['af']
  187. if "use_socket" in kwargs:
  188. self.socket = kwargs['use_socket']
  189. del kwargs['use_socket']
  190. IMAP4.__init__(self, *args, **kwargs)
  191. def Internaldate2epoch(resp):
  192. """Convert IMAP4 INTERNALDATE to UT.
  193. Returns seconds since the epoch."""
  194. from calendar import timegm
  195. mo = InternalDate.match(resp)
  196. if not mo:
  197. return None
  198. mon = Mon2num[mo.group('mon')]
  199. zonen = mo.group('zonen')
  200. day = int(mo.group('day'))
  201. year = int(mo.group('year'))
  202. hour = int(mo.group('hour'))
  203. min = int(mo.group('min'))
  204. sec = int(mo.group('sec'))
  205. zoneh = int(mo.group('zoneh'))
  206. zonem = int(mo.group('zonem'))
  207. # INTERNALDATE timezone must be subtracted to get UT
  208. zone = (zoneh*60 + zonem)*60
  209. if zonen == '-':
  210. zone = -zone
  211. tt = (year, mon, day, hour, min, sec, -1, -1, -1)
  212. return timegm(tt) - zone