PageRenderTime 42ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/email/utils.py

https://bitbucket.org/bwesterb/pypy
Python | 324 lines | 280 code | 17 blank | 27 comment | 27 complexity | 835dc9e07c7157ff10845456c690c8d9 MD5 | raw file
  1. # Copyright (C) 2001-2010 Python Software Foundation
  2. # Author: Barry Warsaw
  3. # Contact: email-sig@python.org
  4. """Miscellaneous utilities."""
  5. __all__ = [
  6. 'collapse_rfc2231_value',
  7. 'decode_params',
  8. 'decode_rfc2231',
  9. 'encode_rfc2231',
  10. 'formataddr',
  11. 'formatdate',
  12. 'getaddresses',
  13. 'make_msgid',
  14. 'mktime_tz',
  15. 'parseaddr',
  16. 'parsedate',
  17. 'parsedate_tz',
  18. 'unquote',
  19. ]
  20. import os
  21. import re
  22. import time
  23. import base64
  24. import random
  25. import socket
  26. import urllib
  27. import warnings
  28. from email._parseaddr import quote
  29. from email._parseaddr import AddressList as _AddressList
  30. from email._parseaddr import mktime_tz
  31. # We need wormarounds for bugs in these methods in older Pythons (see below)
  32. from email._parseaddr import parsedate as _parsedate
  33. from email._parseaddr import parsedate_tz as _parsedate_tz
  34. from quopri import decodestring as _qdecode
  35. # Intrapackage imports
  36. from email.encoders import _bencode, _qencode
  37. COMMASPACE = ', '
  38. EMPTYSTRING = ''
  39. UEMPTYSTRING = u''
  40. CRLF = '\r\n'
  41. TICK = "'"
  42. specialsre = re.compile(r'[][\\()<>@,:;".]')
  43. escapesre = re.compile(r'[][\\()"]')
  44. # Helpers
  45. def _identity(s):
  46. return s
  47. def _bdecode(s):
  48. """Decodes a base64 string.
  49. This function is equivalent to base64.decodestring and it's retained only
  50. for backward compatibility. It used to remove the last \n of the decoded
  51. string, if it had any (see issue 7143).
  52. """
  53. if not s:
  54. return s
  55. return base64.decodestring(s)
  56. def fix_eols(s):
  57. """Replace all line-ending characters with \r\n."""
  58. # Fix newlines with no preceding carriage return
  59. s = re.sub(r'(?<!\r)\n', CRLF, s)
  60. # Fix carriage returns with no following newline
  61. s = re.sub(r'\r(?!\n)', CRLF, s)
  62. return s
  63. def formataddr(pair):
  64. """The inverse of parseaddr(), this takes a 2-tuple of the form
  65. (realname, email_address) and returns the string value suitable
  66. for an RFC 2822 From, To or Cc header.
  67. If the first element of pair is false, then the second element is
  68. returned unmodified.
  69. """
  70. name, address = pair
  71. if name:
  72. quotes = ''
  73. if specialsre.search(name):
  74. quotes = '"'
  75. name = escapesre.sub(r'\\\g<0>', name)
  76. return '%s%s%s <%s>' % (quotes, name, quotes, address)
  77. return address
  78. def getaddresses(fieldvalues):
  79. """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
  80. all = COMMASPACE.join(fieldvalues)
  81. a = _AddressList(all)
  82. return a.addresslist
  83. ecre = re.compile(r'''
  84. =\? # literal =?
  85. (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
  86. \? # literal ?
  87. (?P<encoding>[qb]) # either a "q" or a "b", case insensitive
  88. \? # literal ?
  89. (?P<atom>.*?) # non-greedy up to the next ?= is the atom
  90. \?= # literal ?=
  91. ''', re.VERBOSE | re.IGNORECASE)
  92. def formatdate(timeval=None, localtime=False, usegmt=False):
  93. """Returns a date string as specified by RFC 2822, e.g.:
  94. Fri, 09 Nov 2001 01:08:47 -0000
  95. Optional timeval if given is a floating point time value as accepted by
  96. gmtime() and localtime(), otherwise the current time is used.
  97. Optional localtime is a flag that when True, interprets timeval, and
  98. returns a date relative to the local timezone instead of UTC, properly
  99. taking daylight savings time into account.
  100. Optional argument usegmt means that the timezone is written out as
  101. an ascii string, not numeric one (so "GMT" instead of "+0000"). This
  102. is needed for HTTP, and is only used when localtime==False.
  103. """
  104. # Note: we cannot use strftime() because that honors the locale and RFC
  105. # 2822 requires that day and month names be the English abbreviations.
  106. if timeval is None:
  107. timeval = time.time()
  108. if localtime:
  109. now = time.localtime(timeval)
  110. # Calculate timezone offset, based on whether the local zone has
  111. # daylight savings time, and whether DST is in effect.
  112. if time.daylight and now[-1]:
  113. offset = time.altzone
  114. else:
  115. offset = time.timezone
  116. hours, minutes = divmod(abs(offset), 3600)
  117. # Remember offset is in seconds west of UTC, but the timezone is in
  118. # minutes east of UTC, so the signs differ.
  119. if offset > 0:
  120. sign = '-'
  121. else:
  122. sign = '+'
  123. zone = '%s%02d%02d' % (sign, hours, minutes // 60)
  124. else:
  125. now = time.gmtime(timeval)
  126. # Timezone offset is always -0000
  127. if usegmt:
  128. zone = 'GMT'
  129. else:
  130. zone = '-0000'
  131. return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
  132. ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
  133. now[2],
  134. ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  135. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
  136. now[0], now[3], now[4], now[5],
  137. zone)
  138. def make_msgid(idstring=None):
  139. """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
  140. <20020201195627.33539.96671@nightshade.la.mastaler.com>
  141. Optional idstring if given is a string used to strengthen the
  142. uniqueness of the message id.
  143. """
  144. timeval = time.time()
  145. utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
  146. pid = os.getpid()
  147. randint = random.randrange(100000)
  148. if idstring is None:
  149. idstring = ''
  150. else:
  151. idstring = '.' + idstring
  152. idhost = socket.getfqdn()
  153. msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
  154. return msgid
  155. # These functions are in the standalone mimelib version only because they've
  156. # subsequently been fixed in the latest Python versions. We use this to worm
  157. # around broken older Pythons.
  158. def parsedate(data):
  159. if not data:
  160. return None
  161. return _parsedate(data)
  162. def parsedate_tz(data):
  163. if not data:
  164. return None
  165. return _parsedate_tz(data)
  166. def parseaddr(addr):
  167. addrs = _AddressList(addr).addresslist
  168. if not addrs:
  169. return '', ''
  170. return addrs[0]
  171. # rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
  172. def unquote(str):
  173. """Remove quotes from a string."""
  174. if len(str) > 1:
  175. if str.startswith('"') and str.endswith('"'):
  176. return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
  177. if str.startswith('<') and str.endswith('>'):
  178. return str[1:-1]
  179. return str
  180. # RFC2231-related functions - parameter encoding and decoding
  181. def decode_rfc2231(s):
  182. """Decode string according to RFC 2231"""
  183. parts = s.split(TICK, 2)
  184. if len(parts) <= 2:
  185. return None, None, s
  186. return parts
  187. def encode_rfc2231(s, charset=None, language=None):
  188. """Encode string according to RFC 2231.
  189. If neither charset nor language is given, then s is returned as-is. If
  190. charset is given but not language, the string is encoded using the empty
  191. string for language.
  192. """
  193. import urllib
  194. s = urllib.quote(s, safe='')
  195. if charset is None and language is None:
  196. return s
  197. if language is None:
  198. language = ''
  199. return "%s'%s'%s" % (charset, language, s)
  200. rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$')
  201. def decode_params(params):
  202. """Decode parameters list according to RFC 2231.
  203. params is a sequence of 2-tuples containing (param name, string value).
  204. """
  205. # Copy params so we don't mess with the original
  206. params = params[:]
  207. new_params = []
  208. # Map parameter's name to a list of continuations. The values are a
  209. # 3-tuple of the continuation number, the string value, and a flag
  210. # specifying whether a particular segment is %-encoded.
  211. rfc2231_params = {}
  212. name, value = params.pop(0)
  213. new_params.append((name, value))
  214. while params:
  215. name, value = params.pop(0)
  216. if name.endswith('*'):
  217. encoded = True
  218. else:
  219. encoded = False
  220. value = unquote(value)
  221. mo = rfc2231_continuation.match(name)
  222. if mo:
  223. name, num = mo.group('name', 'num')
  224. if num is not None:
  225. num = int(num)
  226. rfc2231_params.setdefault(name, []).append((num, value, encoded))
  227. else:
  228. new_params.append((name, '"%s"' % quote(value)))
  229. if rfc2231_params:
  230. for name, continuations in rfc2231_params.items():
  231. value = []
  232. extended = False
  233. # Sort by number
  234. continuations.sort()
  235. # And now append all values in numerical order, converting
  236. # %-encodings for the encoded segments. If any of the
  237. # continuation names ends in a *, then the entire string, after
  238. # decoding segments and concatenating, must have the charset and
  239. # language specifiers at the beginning of the string.
  240. for num, s, encoded in continuations:
  241. if encoded:
  242. s = urllib.unquote(s)
  243. extended = True
  244. value.append(s)
  245. value = quote(EMPTYSTRING.join(value))
  246. if extended:
  247. charset, language, value = decode_rfc2231(value)
  248. new_params.append((name, (charset, language, '"%s"' % value)))
  249. else:
  250. new_params.append((name, '"%s"' % value))
  251. return new_params
  252. def collapse_rfc2231_value(value, errors='replace',
  253. fallback_charset='us-ascii'):
  254. if isinstance(value, tuple):
  255. rawval = unquote(value[2])
  256. charset = value[0] or 'us-ascii'
  257. try:
  258. return unicode(rawval, charset, errors)
  259. except LookupError:
  260. # XXX charset is unknown to Python.
  261. return unicode(rawval, fallback_charset, errors)
  262. else:
  263. return unquote(value)