blob: 39c22406078074dd6f03db166924721241c1ad02 [file] [log] [blame]
Benjamin Peterson46a99002010-01-09 18:45:30 +00001# Copyright (C) 2001-2010 Python Software Foundation
Guido van Rossum8b3febe2007-08-30 01:15:14 +00002# Author: Barry Warsaw
3# Contact: email-sig@python.org
4
5"""Miscellaneous utilities."""
6
7__all__ = [
8 'collapse_rfc2231_value',
9 'decode_params',
10 'decode_rfc2231',
11 'encode_rfc2231',
12 'formataddr',
13 'formatdate',
R David Murray875048b2011-07-20 11:41:21 -040014 'format_datetime',
Guido van Rossum8b3febe2007-08-30 01:15:14 +000015 'getaddresses',
16 'make_msgid',
Barry Warsawb742a962009-11-25 18:45:15 +000017 'mktime_tz',
Guido van Rossum8b3febe2007-08-30 01:15:14 +000018 'parseaddr',
19 'parsedate',
20 'parsedate_tz',
R David Murray875048b2011-07-20 11:41:21 -040021 'parsedate_to_datetime',
Guido van Rossum8b3febe2007-08-30 01:15:14 +000022 'unquote',
23 ]
24
25import os
26import re
27import time
Guido van Rossum8b3febe2007-08-30 01:15:14 +000028import random
29import socket
R David Murray875048b2011-07-20 11:41:21 -040030import datetime
Jeremy Hylton1afc1692008-06-18 20:49:58 +000031import urllib.parse
Guido van Rossum8b3febe2007-08-30 01:15:14 +000032
33from email._parseaddr import quote
34from email._parseaddr import AddressList as _AddressList
35from email._parseaddr import mktime_tz
36
Georg Brandl1aca31e2012-09-22 09:03:56 +020037from email._parseaddr import parsedate, parsedate_tz, _parsedate_tz
Guido van Rossum8b3febe2007-08-30 01:15:14 +000038
Guido van Rossum8b3febe2007-08-30 01:15:14 +000039# Intrapackage imports
R David Murray8debacb2011-04-06 09:35:57 -040040from email.charset import Charset
Guido van Rossum8b3febe2007-08-30 01:15:14 +000041
42COMMASPACE = ', '
43EMPTYSTRING = ''
44UEMPTYSTRING = ''
45CRLF = '\r\n'
46TICK = "'"
47
48specialsre = re.compile(r'[][\\()<>@,:;".]')
R David Murrayb53319f2012-03-14 15:31:47 -040049escapesre = re.compile(r'[\\"]')
Guido van Rossum8b3febe2007-08-30 01:15:14 +000050
R David Murrayb83ee302013-06-26 12:06:21 -040051def _has_surrogates(s):
52 """Return True if s contains surrogate-escaped binary data."""
53 # This check is based on the fact that unless there are surrogates, utf8
54 # (Python's default encoding) can encode any string. This is the fastest
55 # way to check for surrogates, see issue 11454 for timings.
56 try:
57 s.encode()
58 return False
59 except UnicodeEncodeError:
60 return True
Guido van Rossum8b3febe2007-08-30 01:15:14 +000061
R David Murray0b6f6c82012-05-25 18:42:14 -040062# How to deal with a string containing bytes before handing it to the
63# application through the 'normal' interface.
64def _sanitize(string):
R David Murray3da240f2013-10-16 22:48:40 -040065 # Turn any escaped bytes into unicode 'unknown' char. If the escaped
66 # bytes happen to be utf-8 they will instead get decoded, even if they
67 # were invalid in the charset the source was supposed to be in. This
68 # seems like it is not a bad thing; a defect was still registered.
69 original_bytes = string.encode('utf-8', 'surrogateescape')
70 return original_bytes.decode('utf-8', 'replace')
71
R David Murray0b6f6c82012-05-25 18:42:14 -040072
Antoine Pitroufd036452008-08-19 17:56:33 +000073
Guido van Rossum8b3febe2007-08-30 01:15:14 +000074# Helpers
75
R David Murray8debacb2011-04-06 09:35:57 -040076def formataddr(pair, charset='utf-8'):
Guido van Rossum8b3febe2007-08-30 01:15:14 +000077 """The inverse of parseaddr(), this takes a 2-tuple of the form
78 (realname, email_address) and returns the string value suitable
79 for an RFC 2822 From, To or Cc header.
80
81 If the first element of pair is false, then the second element is
82 returned unmodified.
R David Murray8debacb2011-04-06 09:35:57 -040083
84 Optional charset if given is the character set that is used to encode
85 realname in case realname is not ASCII safe. Can be an instance of str or
86 a Charset-like object which has a header_encode method. Default is
87 'utf-8'.
Guido van Rossum8b3febe2007-08-30 01:15:14 +000088 """
89 name, address = pair
Martin Panter6245cb32016-04-15 02:14:19 +000090 # The address MUST (per RFC) be ascii, so raise a UnicodeError if it isn't.
R David Murray8debacb2011-04-06 09:35:57 -040091 address.encode('ascii')
Guido van Rossum8b3febe2007-08-30 01:15:14 +000092 if name:
R David Murray8debacb2011-04-06 09:35:57 -040093 try:
94 name.encode('ascii')
95 except UnicodeEncodeError:
96 if isinstance(charset, str):
97 charset = Charset(charset)
98 encoded_name = charset.header_encode(name)
99 return "%s <%s>" % (encoded_name, address)
100 else:
101 quotes = ''
102 if specialsre.search(name):
103 quotes = '"'
104 name = escapesre.sub(r'\\\g<0>', name)
105 return '%s%s%s <%s>' % (quotes, name, quotes, address)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000106 return address
107
108
Antoine Pitroufd036452008-08-19 17:56:33 +0000109
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000110def getaddresses(fieldvalues):
111 """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
112 all = COMMASPACE.join(fieldvalues)
113 a = _AddressList(all)
114 return a.addresslist
115
116
Antoine Pitroufd036452008-08-19 17:56:33 +0000117
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000118ecre = re.compile(r'''
119 =\? # literal =?
120 (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
121 \? # literal ?
122 (?P<encoding>[qb]) # either a "q" or a "b", case insensitive
123 \? # literal ?
124 (?P<atom>.*?) # non-greedy up to the next ?= is the atom
125 \?= # literal ?=
126 ''', re.VERBOSE | re.IGNORECASE)
127
128
R David Murray875048b2011-07-20 11:41:21 -0400129def _format_timetuple_and_zone(timetuple, zone):
130 return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
131 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timetuple[6]],
132 timetuple[2],
133 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
134 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timetuple[1] - 1],
135 timetuple[0], timetuple[3], timetuple[4], timetuple[5],
136 zone)
Antoine Pitroufd036452008-08-19 17:56:33 +0000137
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000138def formatdate(timeval=None, localtime=False, usegmt=False):
139 """Returns a date string as specified by RFC 2822, e.g.:
140
141 Fri, 09 Nov 2001 01:08:47 -0000
142
143 Optional timeval if given is a floating point time value as accepted by
144 gmtime() and localtime(), otherwise the current time is used.
145
146 Optional localtime is a flag that when True, interprets timeval, and
147 returns a date relative to the local timezone instead of UTC, properly
148 taking daylight savings time into account.
149
150 Optional argument usegmt means that the timezone is written out as
151 an ascii string, not numeric one (so "GMT" instead of "+0000"). This
152 is needed for HTTP, and is only used when localtime==False.
153 """
154 # Note: we cannot use strftime() because that honors the locale and RFC
155 # 2822 requires that day and month names be the English abbreviations.
156 if timeval is None:
157 timeval = time.time()
Robert Collins2080dc92015-08-01 08:18:22 +1200158 if localtime or usegmt:
159 dt = datetime.datetime.fromtimestamp(timeval, datetime.timezone.utc)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000160 else:
Robert Collins2080dc92015-08-01 08:18:22 +1200161 dt = datetime.datetime.utcfromtimestamp(timeval)
162 if localtime:
163 dt = dt.astimezone()
164 usegmt = False
165 return format_datetime(dt, usegmt)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000166
R David Murray875048b2011-07-20 11:41:21 -0400167def format_datetime(dt, usegmt=False):
168 """Turn a datetime into a date string as specified in RFC 2822.
169
170 If usegmt is True, dt must be an aware datetime with an offset of zero. In
171 this case 'GMT' will be rendered instead of the normal +0000 required by
172 RFC2822. This is to support HTTP headers involving date stamps.
173 """
174 now = dt.timetuple()
175 if usegmt:
176 if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
177 raise ValueError("usegmt option requires a UTC datetime")
178 zone = 'GMT'
179 elif dt.tzinfo is None:
180 zone = '-0000'
181 else:
182 zone = dt.strftime("%z")
183 return _format_timetuple_and_zone(now, zone)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000184
Antoine Pitroufd036452008-08-19 17:56:33 +0000185
R. David Murraya0b44b52010-12-02 21:47:19 +0000186def make_msgid(idstring=None, domain=None):
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000187 """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
188
Serhiy Storchakaae760c02015-05-19 10:09:42 +0300189 <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000190
191 Optional idstring if given is a string used to strengthen the
R. David Murraya0b44b52010-12-02 21:47:19 +0000192 uniqueness of the message id. Optional domain if given provides the
193 portion of the message id after the '@'. It defaults to the locally
194 defined hostname.
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000195 """
Serhiy Storchakaae760c02015-05-19 10:09:42 +0300196 timeval = int(time.time()*100)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000197 pid = os.getpid()
Serhiy Storchakaae760c02015-05-19 10:09:42 +0300198 randint = random.getrandbits(64)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000199 if idstring is None:
200 idstring = ''
201 else:
202 idstring = '.' + idstring
R. David Murraya0b44b52010-12-02 21:47:19 +0000203 if domain is None:
204 domain = socket.getfqdn()
Serhiy Storchakaae760c02015-05-19 10:09:42 +0300205 msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, domain)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000206 return msgid
207
208
R David Murray875048b2011-07-20 11:41:21 -0400209def parsedate_to_datetime(data):
Georg Brandl1aca31e2012-09-22 09:03:56 +0200210 *dtuple, tz = _parsedate_tz(data)
R David Murray875048b2011-07-20 11:41:21 -0400211 if tz is None:
212 return datetime.datetime(*dtuple[:6])
213 return datetime.datetime(*dtuple[:6],
214 tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))
215
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000216
217def parseaddr(addr):
Rohit Balasubramanian9e7b9b22017-09-20 00:40:49 +0530218 """
219 Parse addr into its constituent realname and email address parts.
220
221 Return a tuple of realname and email address, unless the parse fails, in
222 which case return a 2-tuple of ('', '').
223 """
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000224 addrs = _AddressList(addr).addresslist
225 if not addrs:
226 return '', ''
227 return addrs[0]
228
229
230# rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
231def unquote(str):
232 """Remove quotes from a string."""
233 if len(str) > 1:
234 if str.startswith('"') and str.endswith('"'):
235 return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
236 if str.startswith('<') and str.endswith('>'):
237 return str[1:-1]
238 return str
239
240
Antoine Pitroufd036452008-08-19 17:56:33 +0000241
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000242# RFC2231-related functions - parameter encoding and decoding
243def decode_rfc2231(s):
244 """Decode string according to RFC 2231"""
245 parts = s.split(TICK, 2)
246 if len(parts) <= 2:
247 return None, None, s
248 return parts
249
250
251def encode_rfc2231(s, charset=None, language=None):
252 """Encode string according to RFC 2231.
253
254 If neither charset nor language is given, then s is returned as-is. If
255 charset is given but not language, the string is encoded using the empty
256 string for language.
257 """
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000258 s = urllib.parse.quote(s, safe='', encoding=charset or 'ascii')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000259 if charset is None and language is None:
260 return s
261 if language is None:
262 language = ''
263 return "%s'%s'%s" % (charset, language, s)
264
265
Antoine Pitroufd036452008-08-19 17:56:33 +0000266rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$',
267 re.ASCII)
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000268
269def decode_params(params):
270 """Decode parameters list according to RFC 2231.
271
272 params is a sequence of 2-tuples containing (param name, string value).
273 """
274 # Copy params so we don't mess with the original
275 params = params[:]
276 new_params = []
277 # Map parameter's name to a list of continuations. The values are a
278 # 3-tuple of the continuation number, the string value, and a flag
279 # specifying whether a particular segment is %-encoded.
280 rfc2231_params = {}
281 name, value = params.pop(0)
282 new_params.append((name, value))
283 while params:
284 name, value = params.pop(0)
285 if name.endswith('*'):
286 encoded = True
287 else:
288 encoded = False
289 value = unquote(value)
290 mo = rfc2231_continuation.match(name)
291 if mo:
292 name, num = mo.group('name', 'num')
293 if num is not None:
294 num = int(num)
295 rfc2231_params.setdefault(name, []).append((num, value, encoded))
296 else:
297 new_params.append((name, '"%s"' % quote(value)))
298 if rfc2231_params:
299 for name, continuations in rfc2231_params.items():
300 value = []
301 extended = False
302 # Sort by number
303 continuations.sort()
304 # And now append all values in numerical order, converting
305 # %-encodings for the encoded segments. If any of the
306 # continuation names ends in a *, then the entire string, after
307 # decoding segments and concatenating, must have the charset and
308 # language specifiers at the beginning of the string.
309 for num, s, encoded in continuations:
310 if encoded:
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000311 # Decode as "latin-1", so the characters in s directly
312 # represent the percent-encoded octet values.
313 # collapse_rfc2231_value treats this as an octet sequence.
314 s = urllib.parse.unquote(s, encoding="latin-1")
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000315 extended = True
316 value.append(s)
317 value = quote(EMPTYSTRING.join(value))
318 if extended:
319 charset, language, value = decode_rfc2231(value)
320 new_params.append((name, (charset, language, '"%s"' % value)))
321 else:
322 new_params.append((name, '"%s"' % value))
323 return new_params
324
325def collapse_rfc2231_value(value, errors='replace',
326 fallback_charset='us-ascii'):
327 if not isinstance(value, tuple) or len(value) != 3:
328 return unquote(value)
329 # While value comes to us as a unicode string, we need it to be a bytes
330 # object. We do not want bytes() normal utf-8 decoder, we want a straight
331 # interpretation of the string as character bytes.
332 charset, language, text = value
R David Murray1e949892014-02-07 15:02:19 -0500333 if charset is None:
334 # Issue 17369: if charset/lang is None, decode_rfc2231 couldn't parse
335 # the value, so use the fallback_charset.
336 charset = fallback_charset
Guido van Rossum9604e662007-08-30 03:46:43 +0000337 rawbytes = bytes(text, 'raw-unicode-escape')
Guido van Rossum8b3febe2007-08-30 01:15:14 +0000338 try:
339 return str(rawbytes, charset, errors)
340 except LookupError:
341 # charset is not a known codec.
342 return unquote(text)
R David Murrayd2d521e2012-05-25 23:22:59 -0400343
344
345#
346# datetime doesn't provide a localtime function yet, so provide one. Code
347# adapted from the patch in issue 9527. This may not be perfect, but it is
348# better than not having it.
349#
350
351def localtime(dt=None, isdst=-1):
352 """Return local time as an aware datetime object.
353
354 If called without arguments, return current time. Otherwise *dt*
355 argument should be a datetime instance, and it is converted to the
356 local time zone according to the system time zone database. If *dt* is
357 naive (that is, dt.tzinfo is None), it is assumed to be in local time.
358 In this case, a positive or zero value for *isdst* causes localtime to
359 presume initially that summer time (for example, Daylight Saving Time)
360 is or is not (respectively) in effect for the specified time. A
361 negative value for *isdst* causes the localtime() function to attempt
362 to divine whether summer time is in effect for the specified time.
363
364 """
365 if dt is None:
Alexander Belopolskyf9bd9142012-08-22 23:02:36 -0400366 return datetime.datetime.now(datetime.timezone.utc).astimezone()
R David Murrayb8687df2012-08-22 21:34:00 -0400367 if dt.tzinfo is not None:
368 return dt.astimezone()
369 # We have a naive datetime. Convert to a (localtime) timetuple and pass to
370 # system mktime together with the isdst hint. System mktime will return
371 # seconds since epoch.
372 tm = dt.timetuple()[:-1] + (isdst,)
373 seconds = time.mktime(tm)
374 localtm = time.localtime(seconds)
375 try:
376 delta = datetime.timedelta(seconds=localtm.tm_gmtoff)
377 tz = datetime.timezone(delta, localtm.tm_zone)
378 except AttributeError:
379 # Compute UTC offset and compare with the value implied by tm_isdst.
380 # If the values match, use the zone name implied by tm_isdst.
R David Murray097a1202012-08-22 21:52:31 -0400381 delta = dt - datetime.datetime(*time.gmtime(seconds)[:6])
R David Murrayb8687df2012-08-22 21:34:00 -0400382 dst = time.daylight and localtm.tm_isdst > 0
383 gmtoff = -(time.altzone if dst else time.timezone)
384 if delta == datetime.timedelta(seconds=gmtoff):
385 tz = datetime.timezone(delta, time.tzname[dst])
R David Murrayd2d521e2012-05-25 23:22:59 -0400386 else:
R David Murrayb8687df2012-08-22 21:34:00 -0400387 tz = datetime.timezone(delta)
388 return dt.replace(tzinfo=tz)