utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. 'format_datetime',
  13. 'getaddresses',
  14. 'make_msgid',
  15. 'mktime_tz',
  16. 'parseaddr',
  17. 'parsedate',
  18. 'parsedate_tz',
  19. 'parsedate_to_datetime',
  20. 'unquote',
  21. ]
  22. import os
  23. import re
  24. import time
  25. import random
  26. import socket
  27. import datetime
  28. import urllib.parse
  29. from email._parseaddr import quote
  30. from email._parseaddr import AddressList as _AddressList
  31. from email._parseaddr import mktime_tz
  32. from email._parseaddr import parsedate, parsedate_tz, _parsedate_tz
  33. # Intrapackage imports
  34. from email.charset import Charset
  35. COMMASPACE = ', '
  36. EMPTYSTRING = ''
  37. UEMPTYSTRING = ''
  38. CRLF = '\r\n'
  39. TICK = "'"
  40. specialsre = re.compile(r'[][\\()<>@,:;".]')
  41. escapesre = re.compile(r'[\\"]')
  42. def _has_surrogates(s):
  43. """Return True if s may contain surrogate-escaped binary data."""
  44. # This check is based on the fact that unless there are surrogates, utf8
  45. # (Python's default encoding) can encode any string. This is the fastest
  46. # way to check for surrogates, see bpo-11454 (moved to gh-55663) for timings.
  47. try:
  48. s.encode()
  49. return False
  50. except UnicodeEncodeError:
  51. return True
  52. # How to deal with a string containing bytes before handing it to the
  53. # application through the 'normal' interface.
  54. def _sanitize(string):
  55. # Turn any escaped bytes into unicode 'unknown' char. If the escaped
  56. # bytes happen to be utf-8 they will instead get decoded, even if they
  57. # were invalid in the charset the source was supposed to be in. This
  58. # seems like it is not a bad thing; a defect was still registered.
  59. original_bytes = string.encode('utf-8', 'surrogateescape')
  60. return original_bytes.decode('utf-8', 'replace')
  61. # Helpers
  62. def formataddr(pair, charset='utf-8'):
  63. """The inverse of parseaddr(), this takes a 2-tuple of the form
  64. (realname, email_address) and returns the string value suitable
  65. for an RFC 2822 From, To or Cc header.
  66. If the first element of pair is false, then the second element is
  67. returned unmodified.
  68. The optional charset is the character set that is used to encode
  69. realname in case realname is not ASCII safe. Can be an instance of str or
  70. a Charset-like object which has a header_encode method. Default is
  71. 'utf-8'.
  72. """
  73. name, address = pair
  74. # The address MUST (per RFC) be ascii, so raise a UnicodeError if it isn't.
  75. address.encode('ascii')
  76. if name:
  77. try:
  78. name.encode('ascii')
  79. except UnicodeEncodeError:
  80. if isinstance(charset, str):
  81. charset = Charset(charset)
  82. encoded_name = charset.header_encode(name)
  83. return "%s <%s>" % (encoded_name, address)
  84. else:
  85. quotes = ''
  86. if specialsre.search(name):
  87. quotes = '"'
  88. name = escapesre.sub(r'\\\g<0>', name)
  89. return '%s%s%s <%s>' % (quotes, name, quotes, address)
  90. return address
  91. def _iter_escaped_chars(addr):
  92. pos = 0
  93. escape = False
  94. for pos, ch in enumerate(addr):
  95. if escape:
  96. yield (pos, '\\' + ch)
  97. escape = False
  98. elif ch == '\\':
  99. escape = True
  100. else:
  101. yield (pos, ch)
  102. if escape:
  103. yield (pos, '\\')
  104. def _strip_quoted_realnames(addr):
  105. """Strip real names between quotes."""
  106. if '"' not in addr:
  107. # Fast path
  108. return addr
  109. start = 0
  110. open_pos = None
  111. result = []
  112. for pos, ch in _iter_escaped_chars(addr):
  113. if ch == '"':
  114. if open_pos is None:
  115. open_pos = pos
  116. else:
  117. if start != open_pos:
  118. result.append(addr[start:open_pos])
  119. start = pos + 1
  120. open_pos = None
  121. if start < len(addr):
  122. result.append(addr[start:])
  123. return ''.join(result)
  124. supports_strict_parsing = True
  125. def getaddresses(fieldvalues, *, strict=True):
  126. """Return a list of (REALNAME, EMAIL) or ('','') for each fieldvalue.
  127. When parsing fails for a fieldvalue, a 2-tuple of ('', '') is returned in
  128. its place.
  129. If strict is true, use a strict parser which rejects malformed inputs.
  130. """
  131. # If strict is true, if the resulting list of parsed addresses is greater
  132. # than the number of fieldvalues in the input list, a parsing error has
  133. # occurred and consequently a list containing a single empty 2-tuple [('',
  134. # '')] is returned in its place. This is done to avoid invalid output.
  135. #
  136. # Malformed input: getaddresses(['alice@example.com <bob@example.com>'])
  137. # Invalid output: [('', 'alice@example.com'), ('', 'bob@example.com')]
  138. # Safe output: [('', '')]
  139. if not strict:
  140. all = COMMASPACE.join(str(v) for v in fieldvalues)
  141. a = _AddressList(all)
  142. return a.addresslist
  143. fieldvalues = [str(v) for v in fieldvalues]
  144. fieldvalues = _pre_parse_validation(fieldvalues)
  145. addr = COMMASPACE.join(fieldvalues)
  146. a = _AddressList(addr)
  147. result = _post_parse_validation(a.addresslist)
  148. # Treat output as invalid if the number of addresses is not equal to the
  149. # expected number of addresses.
  150. n = 0
  151. for v in fieldvalues:
  152. # When a comma is used in the Real Name part it is not a deliminator.
  153. # So strip those out before counting the commas.
  154. v = _strip_quoted_realnames(v)
  155. # Expected number of addresses: 1 + number of commas
  156. n += 1 + v.count(',')
  157. if len(result) != n:
  158. return [('', '')]
  159. return result
  160. def _check_parenthesis(addr):
  161. # Ignore parenthesis in quoted real names.
  162. addr = _strip_quoted_realnames(addr)
  163. opens = 0
  164. for pos, ch in _iter_escaped_chars(addr):
  165. if ch == '(':
  166. opens += 1
  167. elif ch == ')':
  168. opens -= 1
  169. if opens < 0:
  170. return False
  171. return (opens == 0)
  172. def _pre_parse_validation(email_header_fields):
  173. accepted_values = []
  174. for v in email_header_fields:
  175. if not _check_parenthesis(v):
  176. v = "('', '')"
  177. accepted_values.append(v)
  178. return accepted_values
  179. def _post_parse_validation(parsed_email_header_tuples):
  180. accepted_values = []
  181. # The parser would have parsed a correctly formatted domain-literal
  182. # The existence of an [ after parsing indicates a parsing failure
  183. for v in parsed_email_header_tuples:
  184. if '[' in v[1]:
  185. v = ('', '')
  186. accepted_values.append(v)
  187. return accepted_values
  188. def _format_timetuple_and_zone(timetuple, zone):
  189. return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
  190. ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timetuple[6]],
  191. timetuple[2],
  192. ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  193. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timetuple[1] - 1],
  194. timetuple[0], timetuple[3], timetuple[4], timetuple[5],
  195. zone)
  196. def formatdate(timeval=None, localtime=False, usegmt=False):
  197. """Returns a date string as specified by RFC 2822, e.g.:
  198. Fri, 09 Nov 2001 01:08:47 -0000
  199. Optional timeval if given is a floating-point time value as accepted by
  200. gmtime() and localtime(), otherwise the current time is used.
  201. Optional localtime is a flag that when True, interprets timeval, and
  202. returns a date relative to the local timezone instead of UTC, properly
  203. taking daylight savings time into account.
  204. Optional argument usegmt means that the timezone is written out as
  205. an ascii string, not numeric one (so "GMT" instead of "+0000"). This
  206. is needed for HTTP, and is only used when localtime==False.
  207. """
  208. # Note: we cannot use strftime() because that honors the locale and RFC
  209. # 2822 requires that day and month names be the English abbreviations.
  210. if timeval is None:
  211. timeval = time.time()
  212. dt = datetime.datetime.fromtimestamp(timeval, datetime.timezone.utc)
  213. if localtime:
  214. dt = dt.astimezone()
  215. usegmt = False
  216. elif not usegmt:
  217. dt = dt.replace(tzinfo=None)
  218. return format_datetime(dt, usegmt)
  219. def format_datetime(dt, usegmt=False):
  220. """Turn a datetime into a date string as specified in RFC 2822.
  221. If usegmt is True, dt must be an aware datetime with an offset of zero. In
  222. this case 'GMT' will be rendered instead of the normal +0000 required by
  223. RFC2822. This is to support HTTP headers involving date stamps.
  224. """
  225. now = dt.timetuple()
  226. if usegmt:
  227. if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
  228. raise ValueError("usegmt option requires a UTC datetime")
  229. zone = 'GMT'
  230. elif dt.tzinfo is None:
  231. zone = '-0000'
  232. else:
  233. zone = dt.strftime("%z")
  234. return _format_timetuple_and_zone(now, zone)
  235. def make_msgid(idstring=None, domain=None):
  236. """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
  237. <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>
  238. Optional idstring if given is a string used to strengthen the
  239. uniqueness of the message id. Optional domain if given provides the
  240. portion of the message id after the '@'. It defaults to the locally
  241. defined hostname.
  242. """
  243. timeval = int(time.time()*100)
  244. pid = os.getpid()
  245. randint = random.getrandbits(64)
  246. if idstring is None:
  247. idstring = ''
  248. else:
  249. idstring = '.' + idstring
  250. if domain is None:
  251. domain = socket.getfqdn()
  252. msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, domain)
  253. return msgid
  254. def parsedate_to_datetime(data):
  255. parsed_date_tz = _parsedate_tz(data)
  256. if parsed_date_tz is None:
  257. raise ValueError('Invalid date value or format "%s"' % str(data))
  258. *dtuple, tz = parsed_date_tz
  259. if tz is None:
  260. return datetime.datetime(*dtuple[:6])
  261. return datetime.datetime(*dtuple[:6],
  262. tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))
  263. def parseaddr(addr, *, strict=True):
  264. """
  265. Parse addr into its constituent realname and email address parts.
  266. Return a tuple of realname and email address, unless the parse fails, in
  267. which case return a 2-tuple of ('', '').
  268. If strict is True, use a strict parser which rejects malformed inputs.
  269. """
  270. if not strict:
  271. addrs = _AddressList(addr).addresslist
  272. if not addrs:
  273. return ('', '')
  274. return addrs[0]
  275. if isinstance(addr, list):
  276. addr = addr[0]
  277. if not isinstance(addr, str):
  278. return ('', '')
  279. addr = _pre_parse_validation([addr])[0]
  280. addrs = _post_parse_validation(_AddressList(addr).addresslist)
  281. if not addrs or len(addrs) > 1:
  282. return ('', '')
  283. return addrs[0]
  284. # rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
  285. def unquote(str):
  286. """Remove quotes from a string."""
  287. if len(str) > 1:
  288. if str.startswith('"') and str.endswith('"'):
  289. return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
  290. if str.startswith('<') and str.endswith('>'):
  291. return str[1:-1]
  292. return str
  293. # RFC2231-related functions - parameter encoding and decoding
  294. def decode_rfc2231(s):
  295. """Decode string according to RFC 2231"""
  296. parts = s.split(TICK, 2)
  297. if len(parts) <= 2:
  298. return None, None, s
  299. return parts
  300. def encode_rfc2231(s, charset=None, language=None):
  301. """Encode string according to RFC 2231.
  302. If neither charset nor language is given, then s is returned as-is. If
  303. charset is given but not language, the string is encoded using the empty
  304. string for language.
  305. """
  306. s = urllib.parse.quote(s, safe='', encoding=charset or 'ascii')
  307. if charset is None and language is None:
  308. return s
  309. if language is None:
  310. language = ''
  311. return "%s'%s'%s" % (charset, language, s)
  312. rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$',
  313. re.ASCII)
  314. def decode_params(params):
  315. """Decode parameters list according to RFC 2231.
  316. params is a sequence of 2-tuples containing (param name, string value).
  317. """
  318. new_params = [params[0]]
  319. # Map parameter's name to a list of continuations. The values are a
  320. # 3-tuple of the continuation number, the string value, and a flag
  321. # specifying whether a particular segment is %-encoded.
  322. rfc2231_params = {}
  323. for name, value in params[1:]:
  324. encoded = name.endswith('*')
  325. value = unquote(value)
  326. mo = rfc2231_continuation.match(name)
  327. if mo:
  328. name, num = mo.group('name', 'num')
  329. if num is not None:
  330. num = int(num)
  331. rfc2231_params.setdefault(name, []).append((num, value, encoded))
  332. else:
  333. new_params.append((name, '"%s"' % quote(value)))
  334. if rfc2231_params:
  335. for name, continuations in rfc2231_params.items():
  336. value = []
  337. extended = False
  338. # Sort by number
  339. continuations.sort()
  340. # And now append all values in numerical order, converting
  341. # %-encodings for the encoded segments. If any of the
  342. # continuation names ends in a *, then the entire string, after
  343. # decoding segments and concatenating, must have the charset and
  344. # language specifiers at the beginning of the string.
  345. for num, s, encoded in continuations:
  346. if encoded:
  347. # Decode as "latin-1", so the characters in s directly
  348. # represent the percent-encoded octet values.
  349. # collapse_rfc2231_value treats this as an octet sequence.
  350. s = urllib.parse.unquote(s, encoding="latin-1")
  351. extended = True
  352. value.append(s)
  353. value = quote(EMPTYSTRING.join(value))
  354. if extended:
  355. charset, language, value = decode_rfc2231(value)
  356. new_params.append((name, (charset, language, '"%s"' % value)))
  357. else:
  358. new_params.append((name, '"%s"' % value))
  359. return new_params
  360. def collapse_rfc2231_value(value, errors='replace',
  361. fallback_charset='us-ascii'):
  362. if not isinstance(value, tuple) or len(value) != 3:
  363. return unquote(value)
  364. # While value comes to us as a unicode string, we need it to be a bytes
  365. # object. We do not want bytes() normal utf-8 decoder, we want a straight
  366. # interpretation of the string as character bytes.
  367. charset, language, text = value
  368. if charset is None:
  369. # Issue 17369: if charset/lang is None, decode_rfc2231 couldn't parse
  370. # the value, so use the fallback_charset.
  371. charset = fallback_charset
  372. rawbytes = bytes(text, 'raw-unicode-escape')
  373. try:
  374. return str(rawbytes, charset, errors)
  375. except LookupError:
  376. # charset is not a known codec.
  377. return unquote(text)
  378. #
  379. # datetime doesn't provide a localtime function yet, so provide one. Code
  380. # adapted from the patch in issue 9527. This may not be perfect, but it is
  381. # better than not having it.
  382. #
  383. def localtime(dt=None, isdst=None):
  384. """Return local time as an aware datetime object.
  385. If called without arguments, return current time. Otherwise *dt*
  386. argument should be a datetime instance, and it is converted to the
  387. local time zone according to the system time zone database. If *dt* is
  388. naive (that is, dt.tzinfo is None), it is assumed to be in local time.
  389. The isdst parameter is ignored.
  390. """
  391. if isdst is not None:
  392. import warnings
  393. warnings._deprecated(
  394. "The 'isdst' parameter to 'localtime'",
  395. message='{name} is deprecated and slated for removal in Python {remove}',
  396. remove=(3, 14),
  397. )
  398. if dt is None:
  399. dt = datetime.datetime.now()
  400. return dt.astimezone()