UIDMaps.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. # Base 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 os.path
  18. import shutil
  19. from os import fsync, unlink
  20. from sys import exc_info
  21. from threading import Lock
  22. try:
  23. import portalocker
  24. except:
  25. try:
  26. import fcntl
  27. except:
  28. pass # Ok if this fails, we can do without.
  29. from offlineimap import OfflineImapError
  30. from .IMAP import IMAPFolder
  31. class MappedIMAPFolder(IMAPFolder):
  32. """IMAP class to map between Folder() instances where both side assign a uid
  33. This Folder is used on the local side, while the remote side should
  34. be an IMAPFolder.
  35. Instance variables (self.):
  36. dryrun: boolean.
  37. r2l: dict mapping message uids: self.r2l[remoteuid]=localuid
  38. l2r: dict mapping message uids: self.r2l[localuid]=remoteuid
  39. #TODO: what is the difference, how are they used?
  40. diskr2l: dict mapping message uids: self.r2l[remoteuid]=localuid
  41. diskl2r: dict mapping message uids: self.r2l[localuid]=remoteuid"""
  42. def __init__(self, imapserver, name, repository, decode=True):
  43. IMAPFolder.__init__(self, imapserver, name, repository, decode=False)
  44. self.dryrun = self.config.getdefaultboolean("general", "dry-run", True)
  45. self.maplock = Lock()
  46. self.diskr2l, self.diskl2r = self._loadmaps()
  47. self.r2l, self.l2r = None, None
  48. # Representing the local IMAP Folder using local UIDs.
  49. # XXX: This should be removed since we inherit from IMAPFolder.
  50. # See commit 3ce514e92ba7 to know more.
  51. self._mb = IMAPFolder(imapserver, name, repository, decode=False)
  52. def _getmapfilename(self):
  53. return os.path.join(self.repository.getmapdir(),
  54. self.getfolderbasename())
  55. def _loadmaps(self):
  56. mapfilename = self._getmapfilename()
  57. mapfilenametmp = "%s.tmp" % mapfilename
  58. mapfilenamelock = "%s.lock" % mapfilename
  59. with self.maplock and open(mapfilenamelock, 'w') as mapfilelock:
  60. try:
  61. fcntl.lockf(mapfilelock, fcntl.LOCK_EX) # Blocks until acquired.
  62. except NameError:
  63. pass # Windows...
  64. if os.path.exists(mapfilenametmp):
  65. self.ui.warn("a previous run might have leave the UIDMaps file"
  66. " in incorrect state; some sync operations might be done"
  67. " again and some emails might become duplicated.")
  68. unlink(mapfilenametmp)
  69. if not os.path.exists(mapfilename):
  70. return {}, {}
  71. file = open(mapfilename, 'rt')
  72. r2l = {}
  73. l2r = {}
  74. while True:
  75. line = file.readline()
  76. if not len(line):
  77. break
  78. try:
  79. line = line.strip()
  80. except ValueError:
  81. raise Exception(
  82. "Corrupt line '%s' in UID mapping file '%s'" %
  83. (line, mapfilename),
  84. exc_info()[2])
  85. (str1, str2) = line.split(':')
  86. loc = int(str1)
  87. rem = int(str2)
  88. r2l[rem] = loc
  89. l2r[loc] = rem
  90. return r2l, l2r
  91. def _savemaps(self):
  92. if self.dryrun is True:
  93. return
  94. mapfilename = self._getmapfilename()
  95. # Do not use the map file directly to prevent from leaving it truncated.
  96. mapfilenametmp = "%s.tmp" % mapfilename
  97. mapfilenamelock = "%s.lock" % mapfilename
  98. with self.maplock and open(mapfilenamelock, 'w') as mapfilelock:
  99. # The "account" lock already prevents from multiple access by
  100. # different processes. However, we still need to protect for
  101. # multiple access from different threads.
  102. try:
  103. fcntl.lockf(mapfilelock, fcntl.LOCK_EX) # Blocks until acquired.
  104. except NameError:
  105. pass # Windows...
  106. with open(mapfilenametmp, 'wt') as mapfilefd:
  107. for (key, value) in list(self.diskl2r.items()):
  108. mapfilefd.write("%d:%d\n" % (key, value))
  109. if self.dofsync():
  110. fsync(mapfilefd)
  111. # The lock is released when the file descriptor ends.
  112. shutil.move(mapfilenametmp, mapfilename)
  113. def _uidlist(self, mapping, items):
  114. try:
  115. return [mapping[x] for x in items]
  116. except KeyError as e:
  117. raise OfflineImapError(
  118. "Could not find UID for msg '{0}' (f:'{1}'."
  119. " This is usually a bad thing and should be "
  120. "reported on the mailing list.".format(
  121. e.args[0], self),
  122. OfflineImapError.ERROR.MESSAGE,
  123. exc_info()[2])
  124. # Interface from BaseFolder
  125. def cachemessagelist(self, min_date=None, min_uid=None):
  126. self._mb.cachemessagelist(min_date=min_date, min_uid=min_uid)
  127. reallist = self._mb.getmessagelist()
  128. self.messagelist = self._mb.messagelist
  129. with self.maplock:
  130. # OK. Now we've got a nice list. First, delete things from the
  131. # summary that have been deleted from the folder.
  132. for luid in list(self.diskl2r.keys()):
  133. if luid not in reallist:
  134. ruid = self.diskl2r[luid]
  135. # XXX: the following KeyError are sightly unexpected. This
  136. # would require more digging to understand how it's
  137. # possible.
  138. errorMessage = ("unexpected error: key {} was not found "
  139. "in memory, see "
  140. "https://github.com/OfflineIMAP/offlineimap/issues/445"
  141. " to know more."
  142. )
  143. try:
  144. del self.diskr2l[ruid]
  145. except KeyError:
  146. self.ui.warn(errorMessage.format(ruid))
  147. try:
  148. del self.diskl2r[luid]
  149. except KeyError:
  150. self.ui.warn(errorMessage.format(ruid))
  151. # Now, assign negative UIDs to local items.
  152. self._savemaps()
  153. nextneg = -1
  154. self.r2l = self.diskr2l.copy()
  155. self.l2r = self.diskl2r.copy()
  156. for luid in list(reallist.keys()):
  157. if luid not in self.l2r:
  158. ruid = nextneg
  159. nextneg -= 1
  160. self.l2r[luid] = ruid
  161. self.r2l[ruid] = luid
  162. def dropmessagelistcache(self):
  163. self._mb.dropmessagelistcache()
  164. # Interface from BaseFolder
  165. def uidexists(self, ruid):
  166. """Checks if the (remote) UID exists in this Folder"""
  167. # This implementation overrides the one in BaseFolder, as it is
  168. # much more efficient for the mapped case.
  169. return ruid in self.r2l
  170. # Interface from BaseFolder
  171. def getmessageuidlist(self):
  172. """Gets a list of (remote) UIDs.
  173. You may have to call cachemessagelist() before calling this function!"""
  174. # This implementation overrides the one in BaseFolder, as it is
  175. # much more efficient for the mapped case.
  176. return list(self.r2l.keys())
  177. # Interface from BaseFolder
  178. def getmessagecount(self):
  179. """Gets the number of messages in this folder.
  180. You may have to call cachemessagelist() before calling this function!"""
  181. # This implementation overrides the one in BaseFolder, as it is
  182. # much more efficient for the mapped case.
  183. return len(self.r2l)
  184. # Interface from BaseFolder
  185. def getmessagelist(self):
  186. """Gets the current message list.
  187. This function's implementation is quite expensive for the mapped UID
  188. case. You must call cachemessagelist() before calling this function!"""
  189. retval = {}
  190. localhash = self._mb.getmessagelist()
  191. with self.maplock:
  192. for key, value in list(localhash.items()):
  193. try:
  194. key = self.l2r[key]
  195. except KeyError:
  196. # Sometimes, the IMAP backend may put in a new message,
  197. # then this function acquires the lock before the system
  198. # has the chance to note it in the mapping. In that case,
  199. # just ignore it.
  200. continue
  201. value = value.copy()
  202. value['uid'] = self.l2r[value['uid']]
  203. retval[key] = value
  204. return retval
  205. # Interface from BaseFolder
  206. def getmessage(self, uid):
  207. """Returns the specified message."""
  208. return self._mb.getmessage(self.r2l[uid])
  209. # Interface from BaseFolder
  210. def savemessage(self, uid, msg, flags, rtime):
  211. """Writes a new message, with the specified uid.
  212. The UIDMaps class will not return a newly assigned uid, as it
  213. internally maps different uids between IMAP servers. So a
  214. successful savemessage() invocation will return the same uid it
  215. has been invoked with. As it maps between 2 IMAP servers which
  216. means the source message must already have an uid, it requires a
  217. positive uid to be passed in. Passing in a message with a
  218. negative uid will do nothing and return the negative uid.
  219. If the uid is > 0, the backend should set the uid to this, if it can.
  220. If it cannot set the uid to that, it will save it anyway.
  221. It will return the uid assigned in any case.
  222. See folder/Base for details. Note that savemessage() does not
  223. check against dryrun settings, so you need to ensure that
  224. savemessage is never called in a dryrun mode.
  225. """
  226. self.ui.savemessage('imap', uid, flags, self)
  227. # Mapped UID instances require the source to already have a
  228. # positive UID, so simply return here.
  229. if uid < 0:
  230. return uid
  231. # If msg uid already exists, just modify the flags.
  232. if uid in self.r2l:
  233. self.savemessageflags(uid, flags)
  234. return uid
  235. newluid = self._mb.savemessage(-1, msg, flags, rtime)
  236. if newluid < 1:
  237. raise OfflineImapError("server of repository '%s' did not return "
  238. "a valid UID (got '%s') for UID '%s' from '%s'" % (
  239. self._mb.getname(), newluid, uid, self.getname()
  240. ),
  241. OfflineImapError.ERROR.MESSAGE
  242. )
  243. with self.maplock:
  244. self.diskl2r[newluid] = uid
  245. self.diskr2l[uid] = newluid
  246. self.l2r[newluid] = uid
  247. self.r2l[uid] = newluid
  248. self._savemaps()
  249. return uid
  250. # Interface from BaseFolder
  251. def getmessageflags(self, uid):
  252. return self._mb.getmessageflags(self.r2l[uid])
  253. # Interface from BaseFolder
  254. def getmessagetime(self, uid):
  255. return None
  256. # Interface from BaseFolder
  257. def savemessageflags(self, uid, flags):
  258. """Note that this function does not check against dryrun settings,
  259. so you need to ensure that it is never called in a
  260. dryrun mode."""
  261. self._mb.savemessageflags(self.r2l[uid], flags)
  262. # Interface from BaseFolder
  263. def addmessageflags(self, uid, flags):
  264. self._mb.addmessageflags(self.r2l[uid], flags)
  265. # Interface from BaseFolder
  266. def addmessagesflags(self, uidlist, flags):
  267. self._mb.addmessagesflags(self._uidlist(self.r2l, uidlist),
  268. flags)
  269. # Interface from BaseFolder
  270. def change_message_uid(self, ruid, new_ruid):
  271. """Change the message from existing ruid to new_ruid
  272. The old remote UID will be changed to a new
  273. UID. The UIDMaps case handles this efficiently by simply
  274. changing the mappings file.
  275. Args:
  276. ruid: Remote UID
  277. new_ruid: New Remote UID
  278. """
  279. if ruid not in self.r2l:
  280. raise OfflineImapError("Cannot change unknown Maildir UID %s" %
  281. ruid, OfflineImapError.ERROR.MESSAGE)
  282. if ruid == new_ruid:
  283. return # sanity check shortcut
  284. with self.maplock:
  285. luid = self.r2l[ruid]
  286. self.l2r[luid] = new_ruid
  287. del self.r2l[ruid]
  288. self.r2l[new_ruid] = luid
  289. # TODO: diskl2r|r2l are a pain to sync and should be done away with
  290. # diskl2r only contains positive UIDs, so wrap in ifs.
  291. if luid > 0:
  292. self.diskl2r[luid] = new_ruid
  293. if ruid > 0:
  294. del self.diskr2l[ruid]
  295. if new_ruid > 0:
  296. self.diskr2l[new_ruid] = luid
  297. self._savemaps()
  298. def _mapped_delete(self, uidlist):
  299. with self.maplock:
  300. needssave = 0
  301. for ruid in uidlist:
  302. luid = self.r2l[ruid]
  303. del self.r2l[ruid]
  304. del self.l2r[luid]
  305. if ruid > 0:
  306. del self.diskr2l[ruid]
  307. del self.diskl2r[luid]
  308. needssave = 1
  309. if needssave:
  310. self._savemaps()
  311. # Interface from BaseFolder
  312. def deletemessageflags(self, uid, flags):
  313. self._mb.deletemessageflags(self.r2l[uid], flags)
  314. # Interface from BaseFolder
  315. def deletemessagesflags(self, uidlist, flags):
  316. self._mb.deletemessagesflags(self._uidlist(self.r2l, uidlist),
  317. flags)
  318. # Interface from BaseFolder
  319. def deletemessage(self, uid):
  320. self._mb.deletemessage(self.r2l[uid])
  321. self._mapped_delete([uid])
  322. # Interface from BaseFolder
  323. def deletemessages(self, uidlist):
  324. self._mb.deletemessages(self._uidlist(self.r2l, uidlist))
  325. self._mapped_delete(uidlist)