PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/Windows/Python3.8/WPy64-3830/WPy64-3830/python-3.8.3.amd64/Lib/email/utils.py

https://gitlab.com/abhi1tb/build
Python | 376 lines | 296 code | 16 blank | 64 comment | 34 complexity | c53cb7a850c0b98701b3dc65c38502b6 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. '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 contains 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 issue 11454 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. Optional charset if given 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 getaddresses(fieldvalues):
  92. """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
  93. all = COMMASPACE.join(fieldvalues)
  94. a = _AddressList(all)
  95. return a.addresslist
  96. def _format_timetuple_and_zone(timetuple, zone):
  97. return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
  98. ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timetuple[6]],
  99. timetuple[2],
  100. ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  101. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timetuple[1] - 1],
  102. timetuple[0], timetuple[3], timetuple[4], timetuple[5],
  103. zone)
  104. def formatdate(timeval=None, localtime=False, usegmt=False):
  105. """Returns a date string as specified by RFC 2822, e.g.:
  106. Fri, 09 Nov 2001 01:08:47 -0000
  107. Optional timeval if given is a floating point time value as accepted by
  108. gmtime() and localtime(), otherwise the current time is used.
  109. Optional localtime is a flag that when True, interprets timeval, and
  110. returns a date relative to the local timezone instead of UTC, properly
  111. taking daylight savings time into account.
  112. Optional argument usegmt means that the timezone is written out as
  113. an ascii string, not numeric one (so "GMT" instead of "+0000"). This
  114. is needed for HTTP, and is only used when localtime==False.
  115. """
  116. # Note: we cannot use strftime() because that honors the locale and RFC
  117. # 2822 requires that day and month names be the English abbreviations.
  118. if timeval is None:
  119. timeval = time.time()
  120. if localtime or usegmt:
  121. dt = datetime.datetime.fromtimestamp(timeval, datetime.timezone.utc)
  122. else:
  123. dt = datetime.datetime.utcfromtimestamp(timeval)
  124. if localtime:
  125. dt = dt.astimezone()
  126. usegmt = False
  127. return format_datetime(dt, usegmt)
  128. def format_datetime(dt, usegmt=False):
  129. """Turn a datetime into a date string as specified in RFC 2822.
  130. If usegmt is True, dt must be an aware datetime with an offset of zero. In
  131. this case 'GMT' will be rendered instead of the normal +0000 required by
  132. RFC2822. This is to support HTTP headers involving date stamps.
  133. """
  134. now = dt.timetuple()
  135. if usegmt:
  136. if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
  137. raise ValueError("usegmt option requires a UTC datetime")
  138. zone = 'GMT'
  139. elif dt.tzinfo is None:
  140. zone = '-0000'
  141. else:
  142. zone = dt.strftime("%z")
  143. return _format_timetuple_and_zone(now, zone)
  144. def make_msgid(idstring=None, domain=None):
  145. """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
  146. <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>
  147. Optional idstring if given is a string used to strengthen the
  148. uniqueness of the message id. Optional domain if given provides the
  149. portion of the message id after the '@'. It defaults to the locally
  150. defined hostname.
  151. """
  152. timeval = int(time.time()*100)
  153. pid = os.getpid()
  154. randint = random.getrandbits(64)
  155. if idstring is None:
  156. idstring = ''
  157. else:
  158. idstring = '.' + idstring
  159. if domain is None:
  160. domain = socket.getfqdn()
  161. msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, domain)
  162. return msgid
  163. def parsedate_to_datetime(data):
  164. *dtuple, tz = _parsedate_tz(data)
  165. if tz is None:
  166. return datetime.datetime(*dtuple[:6])
  167. return datetime.datetime(*dtuple[:6],
  168. tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))
  169. def parseaddr(addr):
  170. """
  171. Parse addr into its constituent realname and email address parts.
  172. Return a tuple of realname and email address, unless the parse fails, in
  173. which case return a 2-tuple of ('', '').
  174. """
  175. addrs = _AddressList(addr).addresslist
  176. if not addrs:
  177. return '', ''
  178. return addrs[0]
  179. # rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
  180. def unquote(str):
  181. """Remove quotes from a string."""
  182. if len(str) > 1:
  183. if str.startswith('"') and str.endswith('"'):
  184. return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
  185. if str.startswith('<') and str.endswith('>'):
  186. return str[1:-1]
  187. return str
  188. # RFC2231-related functions - parameter encoding and decoding
  189. def decode_rfc2231(s):
  190. """Decode string according to RFC 2231"""
  191. parts = s.split(TICK, 2)
  192. if len(parts) <= 2:
  193. return None, None, s
  194. return parts
  195. def encode_rfc2231(s, charset=None, language=None):
  196. """Encode string according to RFC 2231.
  197. If neither charset nor language is given, then s is returned as-is. If
  198. charset is given but not language, the string is encoded using the empty
  199. string for language.
  200. """
  201. s = urllib.parse.quote(s, safe='', encoding=charset or 'ascii')
  202. if charset is None and language is None:
  203. return s
  204. if language is None:
  205. language = ''
  206. return "%s'%s'%s" % (charset, language, s)
  207. rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$',
  208. re.ASCII)
  209. def decode_params(params):
  210. """Decode parameters list according to RFC 2231.
  211. params is a sequence of 2-tuples containing (param name, string value).
  212. """
  213. # Copy params so we don't mess with the original
  214. params = params[:]
  215. new_params = []
  216. # Map parameter's name to a list of continuations. The values are a
  217. # 3-tuple of the continuation number, the string value, and a flag
  218. # specifying whether a particular segment is %-encoded.
  219. rfc2231_params = {}
  220. name, value = params.pop(0)
  221. new_params.append((name, value))
  222. while params:
  223. name, value = params.pop(0)
  224. if name.endswith('*'):
  225. encoded = True
  226. else:
  227. encoded = False
  228. value = unquote(value)
  229. mo = rfc2231_continuation.match(name)
  230. if mo:
  231. name, num = mo.group('name', 'num')
  232. if num is not None:
  233. num = int(num)
  234. rfc2231_params.setdefault(name, []).append((num, value, encoded))
  235. else:
  236. new_params.append((name, '"%s"' % quote(value)))
  237. if rfc2231_params:
  238. for name, continuations in rfc2231_params.items():
  239. value = []
  240. extended = False
  241. # Sort by number
  242. continuations.sort()
  243. # And now append all values in numerical order, converting
  244. # %-encodings for the encoded segments. If any of the
  245. # continuation names ends in a *, then the entire string, after
  246. # decoding segments and concatenating, must have the charset and
  247. # language specifiers at the beginning of the string.
  248. for num, s, encoded in continuations:
  249. if encoded:
  250. # Decode as "latin-1", so the characters in s directly
  251. # represent the percent-encoded octet values.
  252. # collapse_rfc2231_value treats this as an octet sequence.
  253. s = urllib.parse.unquote(s, encoding="latin-1")
  254. extended = True
  255. value.append(s)
  256. value = quote(EMPTYSTRING.join(value))
  257. if extended:
  258. charset, language, value = decode_rfc2231(value)
  259. new_params.append((name, (charset, language, '"%s"' % value)))
  260. else:
  261. new_params.append((name, '"%s"' % value))
  262. return new_params
  263. def collapse_rfc2231_value(value, errors='replace',
  264. fallback_charset='us-ascii'):
  265. if not isinstance(value, tuple) or len(value) != 3:
  266. return unquote(value)
  267. # While value comes to us as a unicode string, we need it to be a bytes
  268. # object. We do not want bytes() normal utf-8 decoder, we want a straight
  269. # interpretation of the string as character bytes.
  270. charset, language, text = value
  271. if charset is None:
  272. # Issue 17369: if charset/lang is None, decode_rfc2231 couldn't parse
  273. # the value, so use the fallback_charset.
  274. charset = fallback_charset
  275. rawbytes = bytes(text, 'raw-unicode-escape')
  276. try:
  277. return str(rawbytes, charset, errors)
  278. except LookupError:
  279. # charset is not a known codec.
  280. return unquote(text)
  281. #
  282. # datetime doesn't provide a localtime function yet, so provide one. Code
  283. # adapted from the patch in issue 9527. This may not be perfect, but it is
  284. # better than not having it.
  285. #
  286. def localtime(dt=None, isdst=-1):
  287. """Return local time as an aware datetime object.
  288. If called without arguments, return current time. Otherwise *dt*
  289. argument should be a datetime instance, and it is converted to the
  290. local time zone according to the system time zone database. If *dt* is
  291. naive (that is, dt.tzinfo is None), it is assumed to be in local time.
  292. In this case, a positive or zero value for *isdst* causes localtime to
  293. presume initially that summer time (for example, Daylight Saving Time)
  294. is or is not (respectively) in effect for the specified time. A
  295. negative value for *isdst* causes the localtime() function to attempt
  296. to divine whether summer time is in effect for the specified time.
  297. """
  298. if dt is None:
  299. return datetime.datetime.now(datetime.timezone.utc).astimezone()
  300. if dt.tzinfo is not None:
  301. return dt.astimezone()
  302. # We have a naive datetime. Convert to a (localtime) timetuple and pass to
  303. # system mktime together with the isdst hint. System mktime will return
  304. # seconds since epoch.
  305. tm = dt.timetuple()[:-1] + (isdst,)
  306. seconds = time.mktime(tm)
  307. localtm = time.localtime(seconds)
  308. try:
  309. delta = datetime.timedelta(seconds=localtm.tm_gmtoff)
  310. tz = datetime.timezone(delta, localtm.tm_zone)
  311. except AttributeError:
  312. # Compute UTC offset and compare with the value implied by tm_isdst.
  313. # If the values match, use the zone name implied by tm_isdst.
  314. delta = dt - datetime.datetime(*time.gmtime(seconds)[:6])
  315. dst = time.daylight and localtm.tm_isdst > 0
  316. gmtoff = -(time.altzone if dst else time.timezone)
  317. if delta == datetime.timedelta(seconds=gmtoff):
  318. tz = datetime.timezone(delta, time.tzname[dst])
  319. else:
  320. tz = datetime.timezone(delta)
  321. return dt.replace(tzinfo=tz)