imaputil.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. # IMAP utility module
  2. # Copyright (C) 2002-2015 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 re
  18. import string
  19. from offlineimap.ui import getglobalui
  20. ## Globals
  21. # Message headers that use space as the separator (for label storage)
  22. SPACE_SEPARATED_LABEL_HEADERS = ('X-Label', 'Keywords')
  23. # Find the modified UTF-7 shifts of an international mailbox name.
  24. MUTF7_SHIFT_RE = re.compile(r'&[^-]*-|\+')
  25. def __debug(*args):
  26. msg = []
  27. for arg in args:
  28. msg.append(str(arg))
  29. getglobalui().debug('imap', " ".join(msg))
  30. def dequote(s):
  31. """Takes string which may or may not be quoted and unquotes it.
  32. It only considers double quotes. This function does NOT consider
  33. parenthised lists to be quoted."""
  34. if s and s.startswith('"') and s.endswith('"'):
  35. s = s[1:-1] # Strip off the surrounding quotes.
  36. s = s.replace('\\"', '"')
  37. s = s.replace('\\\\', '\\')
  38. return s
  39. def quote(s):
  40. """Takes an unquoted string and quotes it.
  41. It only adds double quotes. This function does NOT consider
  42. parenthised lists to be quoted."""
  43. s = s.replace('"', '\\"')
  44. s = s.replace('\\', '\\\\')
  45. return '"%s"'% s
  46. def flagsplit(s):
  47. """Converts a string of IMAP flags to a list
  48. :returns: E.g. '(\\Draft \\Deleted)' returns ['\\Draft','\\Deleted'].
  49. (FLAGS (\\Seen Old) UID 4807) returns
  50. ['FLAGS,'(\\Seen Old)','UID', '4807']
  51. """
  52. if s[0] != '(' or s[-1] != ')':
  53. raise ValueError("Passed s '%s' is not a flag list"% s)
  54. return imapsplit(s[1:-1])
  55. def __options2hash(list):
  56. """convert list [1,2,3,4,5,6] to {1:2, 3:4, 5:6}"""
  57. # effectively this does dict(zip(l[::2],l[1::2])), however
  58. # measurements seemed to have indicated that the manual variant is
  59. # faster for mosly small lists.
  60. retval = {}
  61. counter = 0
  62. while (counter < len(list)):
  63. retval[list[counter]] = list[counter + 1]
  64. counter += 2
  65. __debug("__options2hash returning:", retval)
  66. return retval
  67. def flags2hash(flags):
  68. """Converts IMAP response string from eg IMAP4.fetch() to a hash.
  69. E.g. '(FLAGS (\\Seen Old) UID 4807)' leads to
  70. {'FLAGS': '(\\Seen Old)', 'UID': '4807'}"""
  71. return __options2hash(flagsplit(flags))
  72. def imapsplit(imapstring):
  73. """Takes a string from an IMAP conversation and returns a list containing
  74. its components. One example string is:
  75. (\\HasNoChildren) "." "INBOX.Sent"
  76. The result from parsing this will be:
  77. ['(\\HasNoChildren)', '"."', '"INBOX.Sent"']"""
  78. if not isinstance(imapstring, str):
  79. __debug("imapsplit() got a non-string input; working around.")
  80. # Sometimes, imaplib will throw us a tuple if the input
  81. # contains a literal. See Python bug
  82. # #619732 at https://sourceforge.net/tracker/index.php?func=detail&aid=619732&group_id=5470&atid=105470
  83. # One example is:
  84. # result[0] = '() "\\\\" Admin'
  85. # result[1] = ('() "\\\\" {19}', 'Folder\\2')
  86. #
  87. # This function will effectively get result[0] or result[1], so
  88. # if we get the result[1] version, we need to parse apart the tuple
  89. # and figure out what to do with it. Each even-numbered
  90. # part of it should end with the {} number, and each odd-numbered
  91. # part should be directly a part of the result. We'll
  92. # artificially quote it to help out.
  93. retval = []
  94. for i in range(len(imapstring)):
  95. if i % 2: # Odd: quote then append.
  96. arg = imapstring[i]
  97. # Quote code lifted from imaplib
  98. arg = arg.replace('\\', '\\\\')
  99. arg = arg.replace('"', '\\"')
  100. arg = '"%s"' % arg
  101. __debug("imapsplit() non-string [%d]: Appending %s"% (i, arg))
  102. retval.append(arg)
  103. else:
  104. # Even -- we have a string that ends with a literal
  105. # size specifier. We need to strip off that, then run
  106. # what remains through the regular imapsplit parser.
  107. # Recursion to the rescue.
  108. arg = imapstring[i]
  109. arg = re.sub('\{\d+\}$', '', arg)
  110. __debug("imapsplit() non-string [%d]: Feeding %s to recursion"%\
  111. (i, arg))
  112. retval.extend(imapsplit(arg))
  113. __debug("imapsplit() non-string: returning %s" % str(retval))
  114. return retval
  115. workstr = imapstring.strip()
  116. retval = []
  117. while len(workstr):
  118. # handle parenthized fragments (...()...)
  119. if workstr[0] == '(':
  120. rparenc = 1 # count of right parenthesis to match
  121. rpareni = 1 # position to examine
  122. while rparenc: # Find the end of the group.
  123. if workstr[rpareni] == ')': # end of a group
  124. rparenc -= 1
  125. elif workstr[rpareni] == '(': # start of a group
  126. rparenc += 1
  127. rpareni += 1 # Move to next character.
  128. parenlist = workstr[0:rpareni]
  129. workstr = workstr[rpareni:].lstrip()
  130. retval.append(parenlist)
  131. elif workstr[0] == '"':
  132. # quoted fragments '"...\"..."'
  133. (quoted, rest) = __split_quoted(workstr)
  134. retval.append(quoted)
  135. workstr = rest
  136. else:
  137. splits = None
  138. # Python2
  139. if hasattr(string, 'split'):
  140. splits = string.split(workstr, maxsplit = 1)
  141. # Python3
  142. else:
  143. splits = str.split(workstr, maxsplit = 1)
  144. splitslen = len(splits)
  145. # The unquoted word is splits[0]; the remainder is splits[1]
  146. if splitslen == 2:
  147. # There's an unquoted word, and more string follows.
  148. retval.append(splits[0])
  149. workstr = splits[1] # split will have already lstripped it
  150. continue
  151. elif splitslen == 1:
  152. # We got a last unquoted word, but nothing else
  153. retval.append(splits[0])
  154. # Nothing remains. workstr would be ''
  155. break
  156. elif splitslen == 0:
  157. # There was not even an unquoted word.
  158. break
  159. return retval
  160. flagmap = [('\\Seen', 'S'),
  161. ('\\Answered', 'R'),
  162. ('\\Flagged', 'F'),
  163. ('\\Deleted', 'T'),
  164. ('\\Draft', 'D')]
  165. def flagsimap2maildir(flagstring):
  166. """Convert string '(\\Draft \\Deleted)' into a flags set(DR)."""
  167. retval = set()
  168. imapflaglist = flagstring[1:-1].split()
  169. for imapflag, maildirflag in flagmap:
  170. if imapflag in imapflaglist:
  171. retval.add(maildirflag)
  172. return retval
  173. def flagsimap2keywords(flagstring):
  174. """Convert string '(\\Draft \\Deleted somekeyword otherkeyword)' into a
  175. keyword set (somekeyword otherkeyword)."""
  176. imapflagset = set(flagstring[1:-1].split())
  177. serverflagset = set([flag for (flag, c) in flagmap])
  178. return imapflagset - serverflagset
  179. def flagsmaildir2imap(maildirflaglist):
  180. """Convert set of flags ([DR]) into a string '(\\Deleted \\Draft)'."""
  181. retval = []
  182. for imapflag, maildirflag in flagmap:
  183. if maildirflag in maildirflaglist:
  184. retval.append(imapflag)
  185. return '(' + ' '.join(sorted(retval)) + ')'
  186. def uid_sequence(uidlist):
  187. """Collapse UID lists into shorter sequence sets
  188. [1,2,3,4,5,10,12,13] will return "1:5,10,12:13". This function sorts
  189. the list, and only collapses if subsequent entries form a range.
  190. :returns: The collapsed UID list as string."""
  191. def getrange(start, end):
  192. if start == end:
  193. return(str(start))
  194. return "%s:%s"% (start, end)
  195. if not len(uidlist): return '' # Empty list, return
  196. start, end = None, None
  197. retval = []
  198. # Force items to be longs and sort them
  199. sorted_uids = sorted(map(int, uidlist))
  200. for item in iter(sorted_uids):
  201. item = int(item)
  202. if start == None: # First item
  203. start, end = item, item
  204. elif item == end + 1: # Next item in a range
  205. end = item
  206. else: # Starting a new range
  207. retval.append(getrange(start, end))
  208. start, end = item, item
  209. retval.append(getrange(start, end)) # Add final range/item
  210. return ",".join(retval)
  211. def __split_quoted(s):
  212. """Looks for the ending quote character in the string that starts
  213. with quote character, splitting out quoted component and the
  214. rest of the string (without possible space between these two
  215. parts.
  216. First character of the string is taken to be quote character.
  217. Examples:
  218. - "this is \" a test" (\\None) => ("this is \" a test", (\\None))
  219. - "\\" => ("\\", )
  220. """
  221. if len(s) == 0:
  222. return ('', '')
  223. q = quoted = s[0]
  224. rest = s[1:]
  225. while True:
  226. next_q = rest.find(q)
  227. if next_q == -1:
  228. raise ValueError("can't find ending quote '%s' in '%s'"% (q, s))
  229. # If quote is preceeded by even number of backslashes,
  230. # then it is the ending quote, otherwise the quote
  231. # character is escaped by backslash, so we should
  232. # continue our search.
  233. is_escaped = False
  234. i = next_q - 1
  235. while i >= 0 and rest[i] == '\\':
  236. i -= 1
  237. is_escaped = not is_escaped
  238. quoted += rest[0:next_q + 1]
  239. rest = rest[next_q + 1:]
  240. if not is_escaped:
  241. return (quoted, rest.lstrip())
  242. def format_labels_string(header, labels):
  243. """Formats labels for embedding into a message,
  244. with format according to header name.
  245. Headers from SPACE_SEPARATED_LABEL_HEADERS keep space-separated list
  246. of labels, the rest uses comma (',') as the separator.
  247. Also see parse_labels_string() and modify it accordingly
  248. if logics here gets changed."""
  249. if header in SPACE_SEPARATED_LABEL_HEADERS:
  250. sep = ' '
  251. else:
  252. sep = ','
  253. return sep.join(labels)
  254. def parse_labels_string(header, labels_str):
  255. """Parses a string into a set of labels, with a format according to
  256. the name of the header.
  257. See __format_labels_string() for explanation on header handling
  258. and keep these two functions synced with each other.
  259. TODO: add test to ensure that
  260. - format_labels_string * parse_labels_string is unity
  261. and
  262. - parse_labels_string * format_labels_string is unity
  263. """
  264. if header in SPACE_SEPARATED_LABEL_HEADERS:
  265. sep = ' '
  266. else:
  267. sep = ','
  268. labels = labels_str.strip().split(sep)
  269. return set([l.strip() for l in labels if l.strip()])
  270. def labels_from_header(header_name, header_value):
  271. """Helper that builds label set from the corresponding header value.
  272. Arguments:
  273. - header_name: name of the header that keeps labels;
  274. - header_value: value of the said header, can be None
  275. Returns: set of labels parsed from the header (or empty set).
  276. """
  277. if header_value:
  278. labels = parse_labels_string(header_name, header_value)
  279. else:
  280. labels = set()
  281. return labels
  282. def decode_mailbox_name(name):
  283. """Decodes a modified UTF-7 mailbox name.
  284. If the string cannot be decoded, it is returned unmodified.
  285. See RFC 3501, sec. 5.1.3.
  286. Arguments:
  287. - name: string, possibly encoded with modified UTF-7
  288. Returns: decoded UTF-8 string.
  289. """
  290. def demodify(m):
  291. s = m.group()
  292. if s == '+':
  293. return '+-'
  294. return '+' + s[1:-1].replace(',', '/') + '-'
  295. ret = MUTF7_SHIFT_RE.sub(demodify, name)
  296. try:
  297. return ret.decode('utf-7').encode('utf-8')
  298. except (UnicodeDecodeError, UnicodeEncodeError):
  299. return name