IMAP.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. # IMAP folder support
  2. # Copyright (C) 2002-2016 John Goerzen & contributors.
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. import random
  18. import binascii
  19. import re
  20. import time
  21. from sys import exc_info
  22. from offlineimap import imaputil, imaplibutil, OfflineImapError
  23. from offlineimap import globals
  24. from imaplib2 import MonthNames
  25. from .Base import BaseFolder
  26. from email.errors import HeaderParseError, NoBoundaryInMultipartDefect
  27. # Globals
  28. CRLF = '\r\n'
  29. MSGCOPY_NAMESPACE = 'MSGCOPY_'
  30. class IMAPFolder(BaseFolder):
  31. def __init__(self, imapserver, name, repository, decode=True):
  32. # decode the folder name from IMAP4_utf_7 to utf_8 if
  33. # - utf8foldernames is enabled for the *account*
  34. # - the decode argument is given
  35. # (default True is used when the folder name is the result of
  36. # querying the IMAP server, while False is used when creating
  37. # a folder object from a locally available utf_8 name)
  38. # In any case the given name is first dequoted.
  39. name = imaputil.dequote(name)
  40. if decode and repository.account.utf_8_support:
  41. name = imaputil.IMAP_utf8(name)
  42. self.sep = imapserver.delim
  43. super(IMAPFolder, self).__init__(name, repository)
  44. if repository.getdecodefoldernames():
  45. self.visiblename = imaputil.decode_mailbox_name(self.visiblename)
  46. self.idle_mode = False
  47. self.expunge = repository.getexpunge()
  48. self.root = None # imapserver.root
  49. self.imapserver = imapserver
  50. self.randomgenerator = random.Random()
  51. # self.ui is set in BaseFolder.
  52. self.imap_query = ['BODY.PEEK[]']
  53. # number of times to retry fetching messages
  54. self.retrycount = self.repository.getconfint('retrycount', 2)
  55. fh_conf = self.repository.account.getconf('filterheaders', '')
  56. self.filterheaders = [h for h in re.split(r'\s*,\s*', fh_conf) if h]
  57. # self.copy_ignoreUIDs is used by BaseFolder.
  58. self.copy_ignoreUIDs = repository.get_copy_ignore_UIDs(
  59. self.getvisiblename())
  60. if self.repository.getidlefolders():
  61. self.idle_mode = True
  62. def __selectro(self, imapobj, force=False):
  63. """Select this folder when we do not need write access.
  64. Prefer SELECT to EXAMINE if we can, since some servers
  65. (Courier) do not stabilize UID validity until the folder is
  66. selected.
  67. .. todo: Still valid? Needs verification
  68. :param: Enforce new SELECT even if we are on that folder already.
  69. :returns: raises :exc:`OfflineImapError` severity FOLDER on error"""
  70. try:
  71. imapobj.select(self.getfullIMAPname(), force=force)
  72. except imapobj.readonly:
  73. imapobj.select(self.getfullIMAPname(), readonly=True, force=force)
  74. def getfullIMAPname(self):
  75. name = self.getfullname()
  76. if self.repository.account.utf_8_support:
  77. name = imaputil.utf8_IMAP(name)
  78. return imaputil.foldername_to_imapname(name)
  79. # Interface from BaseFolder
  80. def suggeststhreads(self):
  81. singlethreadperfolder_default = False
  82. if self.idle_mode is True:
  83. singlethreadperfolder_default = True
  84. onethread = self.config.getdefaultboolean(
  85. "Repository %s" % self.repository.getname(),
  86. "singlethreadperfolder", singlethreadperfolder_default)
  87. if onethread is True:
  88. return False
  89. return not globals.options.singlethreading
  90. # Interface from BaseFolder
  91. def waitforthread(self):
  92. self.imapserver.connectionwait()
  93. def getmaxage(self):
  94. if self.config.getdefault("Account %s" %
  95. self.accountname, "maxage", None):
  96. raise OfflineImapError(
  97. "maxage is not supported on IMAP-IMAP sync",
  98. OfflineImapError.ERROR.REPO,
  99. exc_info()[2])
  100. # Interface from BaseFolder
  101. def getinstancelimitnamespace(self):
  102. return MSGCOPY_NAMESPACE + self.repository.getname()
  103. # Interface from BaseFolder
  104. def get_uidvalidity(self):
  105. """Retrieve the current connections UIDVALIDITY value
  106. UIDVALIDITY value will be cached on the first call.
  107. :returns: The UIDVALIDITY as (long) number."""
  108. if hasattr(self, '_uidvalidity'):
  109. # Use cached value if existing.
  110. return self._uidvalidity
  111. imapobj = self.imapserver.acquireconnection()
  112. try:
  113. # SELECT (if not already done) and get current UIDVALIDITY.
  114. self.__selectro(imapobj)
  115. typ, uidval = imapobj.response('UIDVALIDITY')
  116. assert uidval != [None] and uidval is not None, \
  117. "response('UIDVALIDITY') returned [None]!"
  118. self._uidvalidity = int(uidval[-1])
  119. return self._uidvalidity
  120. finally:
  121. self.imapserver.releaseconnection(imapobj)
  122. # Interface from BaseFolder
  123. def quickchanged(self, statusfolder):
  124. # An IMAP folder has definitely changed if the number of
  125. # messages or the UID of the last message have changed. Otherwise
  126. # only flag changes could have occurred.
  127. retry = True # Should we attempt another round or exit?
  128. imapdata = None
  129. while retry:
  130. retry = False
  131. imapobj = self.imapserver.acquireconnection()
  132. try:
  133. # Select folder and get number of messages.
  134. restype, imapdata = imapobj.select(self.getfullIMAPname(), True,
  135. True)
  136. self.imapserver.releaseconnection(imapobj)
  137. except OfflineImapError as e:
  138. # Retry on dropped connections, raise otherwise.
  139. self.imapserver.releaseconnection(imapobj, True)
  140. if e.severity == OfflineImapError.ERROR.FOLDER_RETRY:
  141. retry = True
  142. else:
  143. raise
  144. except:
  145. # Cleanup and raise on all other errors.
  146. self.imapserver.releaseconnection(imapobj, True)
  147. raise
  148. # 1. Some mail servers do not return an EXISTS response
  149. # if the folder is empty. 2. ZIMBRA servers can return
  150. # multiple EXISTS replies in the form 500, 1000, 1500,
  151. # 1623 so check for potentially multiple replies.
  152. if imapdata == [None]:
  153. return True
  154. maxmsgid = 0
  155. for msgid in imapdata:
  156. maxmsgid = max(int(msgid), maxmsgid)
  157. # Different number of messages than last time?
  158. if maxmsgid != statusfolder.getmessagecount():
  159. return True
  160. return False
  161. def _msgs_to_fetch(self, imapobj, min_date=None, min_uid=None):
  162. """Determines sequence numbers of messages to be fetched.
  163. Message sequence numbers (MSNs) are more easily compacted
  164. into ranges which makes transactions slightly faster.
  165. Arguments:
  166. - imapobj: instance of IMAPlib
  167. - min_date (optional): a time_struct; only fetch messages newer
  168. than this
  169. - min_uid (optional): only fetch messages with UID >= min_uid
  170. This function should be called with at MOST one of min_date OR
  171. min_uid set but not BOTH.
  172. Returns: range(s) for messages or None if no messages
  173. are to be fetched."""
  174. def search(search_conditions):
  175. """Actually request the server with the specified conditions.
  176. Returns: range(s) for messages or None if no messages
  177. are to be fetched."""
  178. try:
  179. res_type, res_data = imapobj.search(None, search_conditions)
  180. if res_type != 'OK':
  181. msg = "SEARCH in folder [%s]%s failed. " \
  182. "Search string was '%s'. " \
  183. "Server responded '[%s] %s'" % \
  184. (self.getrepository(), self, search_cond,
  185. res_type, res_data)
  186. raise OfflineImapError(msg, OfflineImapError.ERROR.FOLDER)
  187. except Exception as e:
  188. msg = "SEARCH in folder [%s]%s failed. "\
  189. "Search string was '%s'. Error: %s" % \
  190. (self.getrepository(), self, search_cond, str(e))
  191. raise OfflineImapError(msg, OfflineImapError.ERROR.FOLDER)
  192. """
  193. In Py2, with IMAP, imaplib2 returned a list of one element string.
  194. ['1, 2, 3, ...'] -> in Py3 is [b'1 2 3,...']
  195. In Py2, with Davmail, imaplib2 returned a list of strings.
  196. ['1', '2', '3', ...] -> in Py3 should be [b'1', b'2', b'3',...]
  197. In my tests with Py3, I get a list with one element: [b'1 2 3 ...']
  198. Then I convert the values to string and I get ['1 2 3 ...']
  199. With Davmail, it should be [b'1', b'2', b'3',...]
  200. When I convert the values to string, I get ['1', '2', '3',...]
  201. """
  202. res_data = [x.decode('utf-8') for x in res_data]
  203. # Then, I can do the check in the same way than Python 2
  204. # with string comparison:
  205. if len(res_data) > 0 and (' ' in res_data[0] or res_data[0] == ''):
  206. res_data = res_data[0].split()
  207. # Some servers are broken.
  208. if 0 in res_data:
  209. self.ui.warn("server returned UID with 0; ignoring.")
  210. res_data.remove(0)
  211. return res_data
  212. a = self.getfullIMAPname()
  213. res_type, imapdata = imapobj.select(a, True, True)
  214. if imapdata == [None] or imapdata[0] == b'0':
  215. # Empty folder, no need to populate message list.
  216. return None
  217. # imaplib2 returns the type as string, like "OK" but
  218. # returns imapdata as list of bytes, like [b'0'] so we need decode it
  219. # to use the existing code
  220. imapdata = [x.decode('utf-8') for x in imapdata]
  221. conditions = []
  222. # 1. min_uid condition.
  223. if min_uid is not None:
  224. conditions.append("UID %d:*" % min_uid)
  225. # 2. date condition.
  226. elif min_date is not None:
  227. # Find out what the oldest message is that we should look at.
  228. conditions.append("SINCE %02d-%s-%d" % (
  229. min_date[2], MonthNames[min_date[1]], min_date[0]))
  230. # 3. maxsize condition.
  231. maxsize = self.getmaxsize()
  232. if maxsize is not None:
  233. conditions.append("SMALLER %d" % maxsize)
  234. if len(conditions) >= 1:
  235. # Build SEARCH command.
  236. search_cond = "(%s)" % ' '.join(conditions)
  237. search_result = search(search_cond)
  238. return imaputil.uid_sequence(search_result)
  239. # By default consider all messages in this folder.
  240. return '1:*'
  241. # Interface from BaseFolder
  242. def msglist_item_initializer(self, uid):
  243. return {'uid': uid, 'flags': set(), 'time': 0}
  244. # Interface from BaseFolder
  245. def cachemessagelist(self, min_date=None, min_uid=None):
  246. self.ui.loadmessagelist(self.repository, self)
  247. self.dropmessagelistcache()
  248. imapobj = self.imapserver.acquireconnection()
  249. try:
  250. msgsToFetch = self._msgs_to_fetch(
  251. imapobj, min_date=min_date, min_uid=min_uid)
  252. if not msgsToFetch:
  253. return # No messages to sync.
  254. # Get the flags and UIDs for these. single-quotes prevent
  255. # imaplib2 from quoting the sequence.
  256. fetch_msg = "%s" % msgsToFetch
  257. self.ui.debug('imap', "calling imaplib2 fetch command: %s %s" %
  258. (fetch_msg, '(FLAGS UID INTERNALDATE)'))
  259. res_type, response = imapobj.fetch(
  260. fetch_msg, '(FLAGS UID INTERNALDATE)')
  261. if res_type != 'OK':
  262. msg = "FETCHING UIDs in folder [%s]%s failed. "\
  263. "Server responded '[%s] %s'" % \
  264. (self.getrepository(), self, res_type, response)
  265. raise OfflineImapError(msg, OfflineImapError.ERROR.FOLDER)
  266. finally:
  267. self.imapserver.releaseconnection(imapobj)
  268. for messagestr in response:
  269. # Looks like: '1 (FLAGS (\\Seen Old) UID 4807)' or None if no msg.
  270. # Discard initial message number.
  271. if messagestr is None:
  272. continue
  273. messagestr = messagestr.decode('utf-8').split(' ', 1)[1]
  274. options = imaputil.flags2hash(messagestr)
  275. if 'UID' not in options:
  276. self.ui.warn('No UID in message with options %s' %
  277. str(options), minor=1)
  278. else:
  279. uid = int(options['UID'])
  280. self.messagelist[uid] = self.msglist_item_initializer(uid)
  281. flags = imaputil.flagsimap2maildir(options['FLAGS'])
  282. keywords = imaputil.flagsimap2keywords(options['FLAGS'])
  283. rtime = imaplibutil.Internaldate2epoch(
  284. messagestr.encode('utf-8'))
  285. self.messagelist[uid] = {'uid': uid,
  286. 'flags': flags,
  287. 'time': rtime,
  288. 'keywords': keywords}
  289. self.ui.messagelistloaded(self.repository, self, self.getmessagecount())
  290. # Interface from BaseFolder
  291. def getmessage(self, uid):
  292. """Retrieve message with UID from the IMAP server (incl body).
  293. After this function all CRLFs will be transformed to '\n'.
  294. :returns: the message body or throws and OfflineImapError
  295. (probably severity MESSAGE) if e.g. no message with
  296. this UID could be found.
  297. """
  298. data = self._fetch_from_imap(str(uid), self.retrycount)
  299. # Data looks now e.g.
  300. # ['320 (17061 BODY[] {2565}',<email.message.EmailMessage object>]
  301. # Is a list of two elements. Message is at [1]
  302. msg = data[1]
  303. if self.ui.is_debugging('imap'):
  304. # Optimization: don't create the debugging objects unless needed
  305. msg_s = msg.as_string(policy=self.policy['8bit-RFC'])
  306. if len(msg_s) > 200:
  307. dbg_output = "%s...%s" % (msg_s[:150], msg_s[-50:])
  308. else:
  309. dbg_output = msg_s
  310. self.ui.debug('imap', "Returned object from fetching %d: '%s'" %
  311. (uid, dbg_output))
  312. return msg
  313. # Interface from BaseFolder
  314. def getmessagetime(self, uid):
  315. return self.messagelist[uid]['time']
  316. # Interface from BaseFolder
  317. def getmessageflags(self, uid):
  318. return self.messagelist[uid]['flags']
  319. # Interface from BaseFolder
  320. def getmessagekeywords(self, uid):
  321. return self.messagelist[uid]['keywords']
  322. def __generate_randomheader(self, msg, policy=None):
  323. """Returns a unique X-OfflineIMAP header
  324. Generate an 'X-OfflineIMAP' mail header which contains a random
  325. unique value (which is based on the mail content, and a random
  326. number). This header allows us to fetch a mail after APPENDing
  327. it to an IMAP server and thus find out the UID that the server
  328. assigned it.
  329. :returns: (headername, headervalue) tuple, consisting of strings
  330. headername == 'X-OfflineIMAP' and headervalue will be a
  331. random string
  332. """
  333. headername = 'X-OfflineIMAP'
  334. if policy is None:
  335. output_policy = self.policy['8bit-RFC']
  336. else:
  337. output_policy = policy
  338. # We need a random component too. If we ever upload the same
  339. # mail twice (e.g. in different folders), we would still need to
  340. # get the UID for the correct one. As we won't have too many
  341. # mails with identical content, the randomness requirements are
  342. # not extremly critial though.
  343. # Compute unsigned crc32 of 'msg' (as bytes) into a unique hash.
  344. # NB: crc32 returns unsigned only starting with python 3.0.
  345. headervalue = '{}-{}'.format(
  346. (binascii.crc32(msg.as_bytes(policy=output_policy)) & 0xffffffff),
  347. self.randomgenerator.randint(0, 9999999999))
  348. return headername, headervalue
  349. def __savemessage_searchforheader(self, imapobj, headername, headervalue):
  350. self.ui.debug('imap',
  351. '__savemessage_searchforheader called for %s: %s' %
  352. (headername, headervalue))
  353. # Now find the UID it got.
  354. headervalue = imapobj._quote(headervalue)
  355. try:
  356. matchinguids = imapobj.uid('search', 'HEADER',
  357. headername, headervalue)[1][0]
  358. # Returned value is type bytes
  359. matchinguids = matchinguids.decode('utf-8')
  360. except imapobj.error as err:
  361. # IMAP server doesn't implement search or had a problem.
  362. self.ui.debug('imap',
  363. "__savemessage_searchforheader: got IMAP error '%s' "
  364. "while attempting to UID SEARCH for message with "
  365. "header %s" % (err, headername))
  366. return 0
  367. self.ui.debug('imap',
  368. "__savemessage_searchforheader got initial "
  369. "matchinguids: " + repr(matchinguids))
  370. if matchinguids == '':
  371. self.ui.debug('imap',
  372. "__savemessage_searchforheader: UID SEARCH "
  373. "for message with header %s yielded no results" %
  374. headername)
  375. return 0
  376. matchinguids = matchinguids.split(' ')
  377. self.ui.debug('imap', '__savemessage_searchforheader: matchinguids now '
  378. + repr(matchinguids))
  379. if len(matchinguids) != 1 or matchinguids[0] is None:
  380. raise OfflineImapError(
  381. "While attempting to find UID for message with "
  382. "header %s, got wrong-sized matchinguids of %s" %
  383. (headername, str(matchinguids)),
  384. OfflineImapError.ERROR.MESSAGE
  385. )
  386. return int(matchinguids[0])
  387. def __savemessage_fetchheaders(self, imapobj, headername, headervalue):
  388. """ We fetch all new mail headers and search for the right
  389. X-OfflineImap line by hand. The response from the server has form:
  390. (
  391. 'OK',
  392. [
  393. (
  394. '185 (RFC822.HEADER {1789}',
  395. '... mail headers ...'
  396. ),
  397. ' UID 2444)',
  398. (
  399. '186 (RFC822.HEADER {1789}',
  400. '... 2nd mail headers ...'
  401. ),
  402. ' UID 2445)'
  403. ]
  404. )
  405. We need to locate the UID just after mail headers containing our
  406. X-OfflineIMAP line.
  407. Returns UID when found, 0 when not found."""
  408. self.ui.debug('imap', '__savemessage_fetchheaders called for %s: %s' %
  409. (headername, headervalue))
  410. # Run "fetch X:* rfc822.header".
  411. # Since we stored the mail we are looking for just recently, it would
  412. # not be optimal to fetch all messages. So we'll find highest message
  413. # UID in our local messagelist and search from there (exactly from
  414. # UID+1). That works because UIDs are guaranteed to be unique and
  415. # ascending.
  416. if self.getmessagelist():
  417. start = 1 + max(self.getmessagelist().keys())
  418. else:
  419. # Folder was empty - start from 1.
  420. start = 1
  421. result = imapobj.uid('FETCH', '%d:*' % start, 'rfc822.header')
  422. if result[0] != 'OK':
  423. msg = 'Error fetching mail headers: %s' % '. '.join(result[1])
  424. raise OfflineImapError(msg, OfflineImapError.ERROR.MESSAGE)
  425. # result is like:
  426. # [
  427. # ('185 (RFC822.HEADER {1789}', '... mail headers ...'),
  428. # ' UID 2444)',
  429. # ('186 (RFC822.HEADER {1789}', '... 2nd mail headers ...'),
  430. # ' UID 2445)'
  431. # ]
  432. result = result[1]
  433. found = None
  434. # item is like:
  435. # ('185 (RFC822.HEADER {1789}', '... mail headers ...'), ' UID 2444)'
  436. for item in result:
  437. if found is None and type(item) == tuple:
  438. # Decode the value
  439. item = [x.decode('utf-8') for x in item]
  440. # Walk just tuples.
  441. if re.search(r"(?:^|\\r|\\n)%s:\s*%s(?:\\r|\\n)" %
  442. (headername, headervalue),
  443. item[1], flags=re.IGNORECASE):
  444. found = item[0]
  445. elif found is not None:
  446. if isinstance(item, bytes):
  447. item = item.decode('utf-8')
  448. uid = re.search(r"UID\s+(\d+)", item, flags=re.IGNORECASE)
  449. if uid:
  450. return int(uid.group(1))
  451. else:
  452. # This parsing is for Davmail.
  453. # https://github.com/OfflineIMAP/offlineimap/issues/479
  454. # item is like:
  455. # ')'
  456. # and item[0] stored in "found" is like:
  457. # '1694 (UID 1694 RFC822.HEADER {1294}'
  458. uid = re.search(r"\d+\s+\(UID\s+(\d+)", found,
  459. flags=re.IGNORECASE)
  460. if uid:
  461. return int(uid.group(1))
  462. self.ui.warn("Can't parse FETCH response, "
  463. "can't find UID in %s" % item)
  464. self.ui.debug('imap', "Got: %s" % repr(result))
  465. else:
  466. self.ui.warn("Can't parse FETCH response, "
  467. "we awaited string: %s" % repr(item))
  468. return 0
  469. def __getmessageinternaldate(self, msg, rtime=None):
  470. """Parses mail and returns an INTERNALDATE string
  471. It will use information in the following order, falling back as an
  472. attempt fails:
  473. - rtime parameter
  474. - Date header of email
  475. We return None, if we couldn't find a valid date. In this case
  476. the IMAP server will use the server local time when appening
  477. (per RFC).
  478. Note, that imaplib's Time2Internaldate is inherently broken as
  479. it returns localized date strings which are invalid for IMAP
  480. servers. However, that function is called for *every* append()
  481. internally. So we need to either pass in `None` or the correct
  482. string (in which case Time2Internaldate() will do nothing) to
  483. append(). The output of this function is designed to work as
  484. input to the imapobj.append() function.
  485. TODO: We should probably be returning a bytearray rather than a
  486. string here, because the IMAP server will expect plain
  487. ASCII. However, imaplib.Time2INternaldate currently returns a
  488. string so we go with the same for now.
  489. :param rtime: epoch timestamp to be used rather than analyzing
  490. the email.
  491. :returns: string in the form of "DD-Mmm-YYYY HH:MM:SS +HHMM"
  492. (including double quotes) or `None` in case of failure
  493. (which is fine as value for append)."""
  494. if rtime is None:
  495. rtime = self.get_message_date(msg)
  496. if rtime is None:
  497. return None
  498. datetuple = time.localtime(rtime)
  499. try:
  500. # Check for invalid dates.
  501. if datetuple[0] < 1981:
  502. raise ValueError
  503. # Check for invalid dates.
  504. datetuple_check = time.localtime(time.mktime(datetuple))
  505. if datetuple[:2] != datetuple_check[:2]:
  506. raise ValueError
  507. except (ValueError, OverflowError):
  508. # Argh, sometimes it's a valid format but year is 0102
  509. # or something. Argh. It seems that Time2Internaldate
  510. # will rause a ValueError if the year is 0102 but not 1902,
  511. # but some IMAP servers nonetheless choke on 1902.
  512. self.ui.debug('imap', "Message with invalid date %s. "
  513. "Server will use local time." % datetuple)
  514. return None
  515. # Produce a string representation of datetuple that works as
  516. # INTERNALDATE.
  517. num2mon = {1: 'Jan', 2: 'Feb', 3: 'Mar',
  518. 4: 'Apr', 5: 'May', 6: 'Jun',
  519. 7: 'Jul', 8: 'Aug', 9: 'Sep',
  520. 10: 'Oct', 11: 'Nov', 12: 'Dec'}
  521. # tm_isdst coming from email.parsedate is not usable, we still use it
  522. # here, mhh.
  523. if datetuple.tm_isdst == 1:
  524. zone = -time.altzone
  525. else:
  526. zone = -time.timezone
  527. offset_h, offset_m = divmod(zone // 60, 60)
  528. internaldate = '"%02d-%s-%04d %02d:%02d:%02d %+03d%02d"' % \
  529. (datetuple.tm_mday, num2mon[datetuple.tm_mon],
  530. datetuple.tm_year, datetuple.tm_hour,
  531. datetuple.tm_min, datetuple.tm_sec,
  532. offset_h, offset_m)
  533. return internaldate
  534. # Interface from BaseFolder
  535. def savemessage(self, uid, msg, flags, rtime):
  536. """Save the message on the Server
  537. This backend always assigns a new uid, so the uid arg is ignored.
  538. This function will update the self.messagelist dict to contain
  539. the new message after sucessfully saving it.
  540. See folder/Base for details. Note that savemessage() does not
  541. check against dryrun settings, so you need to ensure that
  542. savemessage is never called in a dryrun mode.
  543. :param uid: Message UID
  544. :param msg: Message Object
  545. :param flags: Message flags
  546. :param rtime: A timestamp to be used as the mail date
  547. :returns: the UID of the new message as assigned by the server. If the
  548. message is saved, but it's UID can not be found, it will
  549. return 0. If the message can't be written (folder is
  550. read-only for example) it will return -1."""
  551. self.ui.savemessage('imap', uid, flags, self)
  552. # Already have it, just save modified flags.
  553. if uid > 0 and self.uidexists(uid):
  554. self.savemessageflags(uid, flags)
  555. return uid
  556. # Filter user requested headers before uploading to the IMAP server
  557. self.deletemessageheaders(msg, self.filterheaders)
  558. # Should just be able to set the policy, to use CRLF in msg output
  559. output_policy = self.policy['8bit-RFC']
  560. # Get the date of the message, so we can pass it to the server.
  561. date = self.__getmessageinternaldate(msg, rtime)
  562. # Message-ID is handy for debugging messages.
  563. try:
  564. msg_id = self.getmessageheader(msg, "message-id")
  565. if not msg_id:
  566. msg_id = '[unknown message-id]'
  567. except (HeaderParseError, IndexError):
  568. msg_id = '[broken message-id]'
  569. retry_left = 2 # succeeded in APPENDING?
  570. imapobj = self.imapserver.acquireconnection()
  571. # NB: in the finally clause for this try we will release
  572. # NB: the acquired imapobj, so don't do that twice unless
  573. # NB: you will put another connection to imapobj. If you
  574. # NB: really do need to release connection manually, set
  575. # NB: imapobj to None.
  576. try:
  577. while retry_left:
  578. # XXX: we can mangle message only once, out of the loop
  579. # UIDPLUS extension provides us with an APPENDUID response.
  580. use_uidplus = 'UIDPLUS' in imapobj.capabilities
  581. if not use_uidplus:
  582. # Insert a random unique header that we can fetch later.
  583. (headername, headervalue) = self.__generate_randomheader(
  584. msg)
  585. self.ui.debug('imap', 'savemessage: header is: %s: %s' %
  586. (headername, headervalue))
  587. self.addmessageheader(msg, headername, headervalue)
  588. if self.ui.is_debugging('imap'):
  589. # Optimization: don't create the debugging objects unless needed
  590. msg_s = msg.as_string(policy=output_policy)
  591. if len(msg_s) > 200:
  592. dbg_output = "%s...%s" % (msg_s[:150], msg_s[-50:])
  593. else:
  594. dbg_output = msg_s
  595. self.ui.debug('imap', "savemessage: date: %s, content: '%s'" %
  596. (date, dbg_output))
  597. try:
  598. # Select folder for append and make the box READ-WRITE.
  599. imapobj.select(self.getfullIMAPname())
  600. except imapobj.readonly:
  601. # readonly exception. Return original uid to notify that
  602. # we did not save the message. (see savemessage in Base.py)
  603. self.ui.msgtoreadonly(self, uid)
  604. return uid
  605. # Do the APPEND.
  606. try:
  607. (typ, dat) = imapobj.append(
  608. self.getfullIMAPname(),
  609. imaputil.flagsmaildir2imap(flags),
  610. date, msg.as_bytes(policy=output_policy))
  611. # This should only catch 'NO' responses since append()
  612. # will raise an exception for 'BAD' responses:
  613. if typ != 'OK':
  614. # For example, Groupwise IMAP server
  615. # can return something like:
  616. #
  617. # NO APPEND The 1500 MB storage limit \
  618. # has been exceeded.
  619. #
  620. # In this case, we should immediately abort
  621. # the repository sync and continue
  622. # with the next account.
  623. err_msg = \
  624. "Saving msg (%s) in folder '%s', " \
  625. "repository '%s' failed (abort). " \
  626. "Server responded: %s %s\n" % \
  627. (msg_id, self, self.getrepository(), typ, dat)
  628. raise OfflineImapError(err_msg, OfflineImapError.ERROR.REPO)
  629. retry_left = 0 # Mark as success.
  630. except imapobj.abort as e:
  631. # Connection has been reset, release connection and retry.
  632. retry_left -= 1
  633. self.imapserver.releaseconnection(imapobj, True)
  634. imapobj = self.imapserver.acquireconnection()
  635. if not retry_left:
  636. raise OfflineImapError(
  637. "Saving msg (%s) in folder '%s', "
  638. "repository '%s' failed (abort). "
  639. "Server responded: %s\n" %
  640. (msg_id, self, self.getrepository(), str(e)),
  641. OfflineImapError.ERROR.MESSAGE,
  642. exc_info()[2])
  643. # XXX: is this still needed?
  644. self.ui.error(e, exc_info()[2])
  645. except imapobj.error as e: # APPEND failed
  646. # If the server responds with 'BAD', append()
  647. # raise()s directly. So we catch that too.
  648. # drop conn, it might be bad.
  649. self.imapserver.releaseconnection(imapobj, True)
  650. imapobj = None
  651. raise OfflineImapError(
  652. "Saving msg (%s) folder '%s', repo '%s'"
  653. "failed (error). Server responded: %s\n" %
  654. (msg_id, self, self.getrepository(), str(e)),
  655. OfflineImapError.ERROR.MESSAGE,
  656. exc_info()[2])
  657. # Checkpoint. Let it write out stuff, etc. Eg searches for
  658. # just uploaded messages won't work if we don't do this.
  659. (typ, dat) = imapobj.check()
  660. assert (typ == 'OK')
  661. # Get the new UID, do we use UIDPLUS?
  662. if use_uidplus:
  663. # Get new UID from the APPENDUID response, it could look
  664. # like OK [APPENDUID 38505 3955] APPEND completed with
  665. # 38505 bein folder UIDvalidity and 3955 the new UID.
  666. # note: we would want to use .response() here but that
  667. # often seems to return [None], even though we have
  668. # data. TODO
  669. resp = imapobj._get_untagged_response('APPENDUID')
  670. if resp == [None] or resp is None:
  671. self.ui.warn("Server supports UIDPLUS but got no APPENDUID "
  672. "appending a message. Got: %s." % str(resp))
  673. return 0
  674. try:
  675. # Convert the UID from [b'4 1532'] to ['4 1532']
  676. s_uid = [x.decode('utf-8') for x in resp]
  677. # Now, read the UID field
  678. uid = int(s_uid[-1].split(' ')[1])
  679. except ValueError:
  680. uid = 0 # Definetly not what we should have.
  681. except Exception:
  682. raise OfflineImapError("Unexpected response: %s" %
  683. str(resp),
  684. OfflineImapError.ERROR.MESSAGE)
  685. if uid == 0:
  686. self.ui.warn("savemessage: Server supports UIDPLUS, but"
  687. " we got no usable UID back. APPENDUID "
  688. "reponse was '%s'" % str(resp))
  689. else:
  690. try:
  691. # We don't use UIDPLUS.
  692. uid = self.__savemessage_searchforheader(imapobj,
  693. headername,
  694. headervalue)
  695. # See docs for savemessage in Base.py for explanation
  696. # of this and other return values.
  697. if uid == 0:
  698. self.ui.debug('imap',
  699. 'savemessage: attempt to get new UID '
  700. 'UID failed. Search headers manually.')
  701. uid = self.__savemessage_fetchheaders(imapobj,
  702. headername,
  703. headervalue)
  704. self.ui.warn("savemessage: Searching mails for new "
  705. "Message-ID failed. "
  706. "Could not determine new UID on %s." %
  707. self.getname())
  708. # Something wrong happened while trying to get the UID. Explain
  709. # the error might be about the 'get UID' process not necesseraly
  710. # the APPEND.
  711. except Exception:
  712. self.ui.warn("%s: could not determine the UID while we got "
  713. "no error while appending the "
  714. "email with '%s: %s'" %
  715. (self.getname(), headername, headervalue))
  716. raise
  717. finally:
  718. if imapobj:
  719. self.imapserver.releaseconnection(imapobj)
  720. if uid: # Avoid UID FETCH 0 crash happening later on.
  721. self.messagelist[uid] = self.msglist_item_initializer(uid)
  722. self.messagelist[uid]['flags'] = flags
  723. self.ui.debug('imap', 'savemessage: returning new UID %d' % uid)
  724. return uid
  725. def _fetch_from_imap(self, uids, retry_num=1):
  726. """Fetches data from IMAP server.
  727. Arguments:
  728. - uids: message UIDS (OfflineIMAP3: First UID returned only)
  729. - retry_num: number of retries to make
  730. Returns: data obtained by this query."""
  731. imapobj = self.imapserver.acquireconnection()
  732. try:
  733. query = "(%s)" % (" ".join(self.imap_query))
  734. fails_left = retry_num # Retry on dropped connection.
  735. while fails_left:
  736. try:
  737. imapobj.select(self.getfullIMAPname(), readonly=True)
  738. res_type, data = imapobj.uid('fetch', uids, query)
  739. break
  740. except imapobj.abort as e:
  741. fails_left -= 1
  742. # self.ui.error() will show the original traceback.
  743. if fails_left <= 0:
  744. message = ("%s, while fetching msg %r in folder %r."
  745. " Max retry reached (%d)" %
  746. (e, uids, self.name, retry_num))
  747. raise OfflineImapError(message,
  748. OfflineImapError.ERROR.MESSAGE)
  749. self.ui.error("%s. While fetching msg %r in folder %r."
  750. " Query: %s Retrying (%d/%d)" % (
  751. e, uids, self.name, query,
  752. retry_num - fails_left, retry_num))
  753. # Release dropped connection, and get a new one.
  754. self.imapserver.releaseconnection(imapobj, True)
  755. imapobj = self.imapserver.acquireconnection()
  756. finally:
  757. # The imapobj here might be different than the one created before
  758. # the ``try`` clause. So please avoid transforming this to a nice
  759. # ``with`` without taking this into account.
  760. self.imapserver.releaseconnection(imapobj)
  761. # Ensure to not consider unsolicited FETCH responses caused by flag
  762. # changes from concurrent connections. These appear as strings in
  763. # 'data' (the BODY response appears as a tuple). This should leave
  764. # exactly one response.
  765. if res_type == 'OK':
  766. data = [res for res in data if not isinstance(res, bytes)]
  767. # Could not fetch message. Note: it is allowed by rfc3501 to return any
  768. # data for the UID FETCH command.
  769. if data == [None] or res_type != 'OK' or len(data) != 1:
  770. severity = OfflineImapError.ERROR.MESSAGE
  771. reason = "IMAP server '%s' failed to fetch messages UID '%s'. " \
  772. "Server responded: %s %s" % (self.getrepository(), uids,
  773. res_type, data)
  774. if data == [None] or len(data) < 1:
  775. # IMAP server did not find a message with this UID.
  776. reason = "IMAP server '%s' does not have a message " \
  777. "with UID '%s'" % (self.getrepository(), uids)
  778. raise OfflineImapError(reason, severity)
  779. # JI: In offlineimap, this function returned a tuple of strings for each
  780. # fetched UID, offlineimap3 calls to the imap object return bytes and so
  781. # originally a fixed, utf-8 conversion was done and *only* the first
  782. # response (d[0]) was returned. Note that this alters the behavior
  783. # between code bases. However, it seems like a single UID is the intent
  784. # of this function so retaining the modfication here for now.
  785. #
  786. # TODO: Can we assume the server response containing the meta data is
  787. # always 'utf-8' encoded? Assuming yes for now.
  788. #
  789. # Convert responses, d[0][0], into a 'utf-8' string (from bytes) and
  790. # Convert email, d[0][1], into a message object (from bytes)
  791. ndata0 = data[0][0].decode('utf-8')
  792. try: ndata1 = self.parser['8bit-RFC'].parsebytes(data[0][1])
  793. except:
  794. err = exc_info()
  795. response_type = type(data[0][1]).__name__
  796. msg_id = self._extract_message_id(data[0][1])[0].decode('ascii',errors='surrogateescape')
  797. raise OfflineImapError(
  798. "Exception parsing message with ID ({}) from imaplib (response type: {}).\n {}: {}".format(
  799. msg_id, response_type, err[0].__name__, err[1]),
  800. OfflineImapError.ERROR.MESSAGE)
  801. if len(ndata1.defects) > 0:
  802. # We don't automatically apply fixes as to attempt to preserve the original message
  803. self.ui.warn("UID {} has defects: {}".format(uids, ndata1.defects))
  804. if any(isinstance(defect, NoBoundaryInMultipartDefect) for defect in ndata1.defects):
  805. # (Hopefully) Rare defect from a broken client where multipart boundary is
  806. # not properly quoted. Attempt to solve by fixing the boundary and parsing
  807. self.ui.warn(" ... applying multipart boundary fix.")
  808. ndata1 = self.parser['8bit-RFC'].parsebytes(self._quote_boundary_fix(data[0][1]))
  809. try:
  810. # See if the defects after fixes are preventing us from obtaining bytes
  811. _ = ndata1.as_bytes(policy=self.policy['8bit-RFC'])
  812. except UnicodeEncodeError as err:
  813. # Unknown issue which is causing failure of as_bytes()
  814. msg_id = self.getmessageheader(ndata1, "message-id")
  815. if msg_id is None:
  816. msg_id = '<Unknown Message-ID>'
  817. raise OfflineImapError(
  818. "UID {} ({}) has defects preventing it from being processed!\n {}: {}".format(
  819. uids, msg_id, type(err).__name__, err),
  820. OfflineImapError.ERROR.MESSAGE)
  821. ndata = [ndata0, ndata1]
  822. return ndata
  823. def _store_to_imap(self, imapobj, uid, field, data):
  824. """Stores data to IMAP server
  825. Arguments:
  826. - imapobj: instance of IMAPlib to use
  827. - uid: message UID
  828. - field: field name to be stored/updated
  829. - data: field contents
  830. """
  831. imapobj.select(self.getfullIMAPname())
  832. res_type, retdata = imapobj.uid('store', uid, field, data)
  833. if res_type != 'OK':
  834. severity = OfflineImapError.ERROR.MESSAGE
  835. reason = "IMAP server '%s' failed to store %s " \
  836. "for message UID '%d'." \
  837. "Server responded: %s %s" % (
  838. self.getrepository(), field, uid, res_type, retdata)
  839. raise OfflineImapError(reason, severity)
  840. return retdata[0]
  841. # Interface from BaseFolder
  842. def savemessageflags(self, uid, flags):
  843. """Change a message's flags to `flags`.
  844. Note that this function does not check against dryrun settings,
  845. so you need to ensure that it is never called in a
  846. dryrun mode."""
  847. imapobj = self.imapserver.acquireconnection()
  848. try:
  849. result = self._store_to_imap(imapobj, str(uid), 'FLAGS',
  850. imaputil.flagsmaildir2imap(flags))
  851. except imapobj.readonly:
  852. self.ui.flagstoreadonly(self, [uid], flags)
  853. return
  854. finally:
  855. self.imapserver.releaseconnection(imapobj)
  856. if not result:
  857. self.messagelist[uid]['flags'] = flags
  858. else:
  859. flags = imaputil.flags2hash(imaputil.imapsplit(result)[1])['FLAGS']
  860. self.messagelist[uid]['flags'] = imaputil.flagsimap2maildir(flags)
  861. # Interface from BaseFolder
  862. def addmessageflags(self, uid, flags):
  863. self.addmessagesflags([uid], flags)
  864. def __addmessagesflags_noconvert(self, uidlist, flags):
  865. self.__processmessagesflags('+', uidlist, flags)
  866. # Interface from BaseFolder
  867. def addmessagesflags(self, uidlist, flags):
  868. """This is here for the sake of UIDMaps.py -- deletemessages must
  869. add flags and get a converted UID, and if we don't have noconvert,
  870. then UIDMaps will try to convert it twice."""
  871. self.__addmessagesflags_noconvert(uidlist, flags)
  872. # Interface from BaseFolder
  873. def deletemessageflags(self, uid, flags):
  874. self.deletemessagesflags([uid], flags)
  875. # Interface from BaseFolder
  876. def deletemessagesflags(self, uidlist, flags):
  877. self.__processmessagesflags('-', uidlist, flags)
  878. def __processmessagesflags_real(self, operation, uidlist, flags):
  879. imapobj = self.imapserver.acquireconnection()
  880. try:
  881. try:
  882. imapobj.select(self.getfullIMAPname())
  883. except imapobj.readonly:
  884. self.ui.flagstoreadonly(self, uidlist, flags)
  885. return
  886. response = imapobj.uid('store',
  887. imaputil.uid_sequence(uidlist),
  888. operation + 'FLAGS',
  889. imaputil.flagsmaildir2imap(flags))
  890. if response[0] != 'OK':
  891. raise OfflineImapError(
  892. 'Error with store: %s' % '. '.join(response[1]),
  893. OfflineImapError.ERROR.MESSAGE)
  894. response = response[1]
  895. finally:
  896. self.imapserver.releaseconnection(imapobj)
  897. # Some IMAP servers do not always return a result. Therefore,
  898. # only update the ones that it talks about, and manually fix
  899. # the others.
  900. needupdate = list(uidlist)
  901. for result in response:
  902. if result is None:
  903. # Compensate for servers that don't return anything from
  904. # STORE.
  905. continue
  906. attributehash = imaputil.flags2hash(imaputil.imapsplit(result)[1])
  907. if not ('UID' in attributehash and 'FLAGS' in attributehash):
  908. # Compensate for servers that don't return a UID attribute.
  909. continue
  910. flagstr = attributehash['FLAGS']
  911. uid = int(attributehash['UID'])
  912. self.messagelist[uid]['flags'] = imaputil.flagsimap2maildir(flagstr)
  913. try:
  914. needupdate.remove(uid)
  915. except ValueError: # Let it slide if it's not in the list.
  916. pass
  917. for uid in needupdate:
  918. if operation == '+':
  919. self.messagelist[uid]['flags'] |= flags
  920. elif operation == '-':
  921. self.messagelist[uid]['flags'] -= flags
  922. def __processmessagesflags(self, operation, uidlist, flags):
  923. # Hack for those IMAP servers with a limited line length.
  924. batch_size = 100
  925. for i in range(0, len(uidlist), batch_size):
  926. self.__processmessagesflags_real(operation,
  927. uidlist[i:i + batch_size], flags)
  928. return
  929. # Interface from BaseFolder
  930. def change_message_uid(self, uid, new_uid):
  931. """Change the message from existing uid to new_uid
  932. If the backend supports it. IMAP does not and will throw errors."""
  933. raise OfflineImapError('IMAP backend cannot change a messages UID from '
  934. '%d to %d' %
  935. (uid, new_uid), OfflineImapError.ERROR.MESSAGE)
  936. # Interface from BaseFolder
  937. def deletemessage(self, uid):
  938. self.__deletemessages_noconvert([uid])
  939. # Interface from BaseFolder
  940. def deletemessages(self, uidlist):
  941. self.__deletemessages_noconvert(uidlist)
  942. def __deletemessages_noconvert(self, uidlist):
  943. if not len(uidlist):
  944. return
  945. self.__addmessagesflags_noconvert(uidlist, set('T'))
  946. imapobj = self.imapserver.acquireconnection()
  947. try:
  948. try:
  949. imapobj.select(self.getfullIMAPname())
  950. except imapobj.readonly:
  951. self.ui.deletereadonly(self, uidlist)
  952. return
  953. if self.expunge:
  954. assert (imapobj.expunge()[0] == 'OK')
  955. finally:
  956. self.imapserver.releaseconnection(imapobj)
  957. for uid in uidlist:
  958. del self.messagelist[uid]