blob: 50010e69b06315c1c001362439756733957eda51 [file] [log] [blame]
Barry Warsaw40ef0062006-03-18 15:41:53 +00001# Copyright (C) 2001-2006 Python Software Foundation
Barry Warsawbb113862004-10-03 03:16:19 +00002# Author: Barry Warsaw
3# Contact: email-sig@python.org
Barry Warsawba925802001-09-23 03:17:28 +00004
Barry Warsaw24f79762004-05-09 03:55:11 +00005"""Miscellaneous utilities."""
Barry Warsawba925802001-09-23 03:17:28 +00006
Barry Warsaw40ef0062006-03-18 15:41:53 +00007__all__ = [
8 'collapse_rfc2231_value',
9 'decode_params',
10 'decode_rfc2231',
11 'encode_rfc2231',
12 'formataddr',
13 'formatdate',
14 'getaddresses',
15 'make_msgid',
16 'parseaddr',
17 'parsedate',
18 'parsedate_tz',
19 'unquote',
20 ]
21
Barry Warsaw409a4c02002-04-10 21:01:31 +000022import os
Barry Warsaw24f79762004-05-09 03:55:11 +000023import re
24import time
25import base64
26import random
27import socket
Barry Warsawb110bad2006-07-21 14:51:07 +000028import urllib
Barry Warsaw409a4c02002-04-10 21:01:31 +000029import warnings
Barry Warsawba925802001-09-23 03:17:28 +000030
Barry Warsaw030ddf72002-11-05 19:54:52 +000031from email._parseaddr import quote
32from email._parseaddr import AddressList as _AddressList
33from email._parseaddr import mktime_tz
Barry Warsaw409a4c02002-04-10 21:01:31 +000034
35# We need wormarounds for bugs in these methods in older Pythons (see below)
Barry Warsaw030ddf72002-11-05 19:54:52 +000036from email._parseaddr import parsedate as _parsedate
37from email._parseaddr import parsedate_tz as _parsedate_tz
Barry Warsawba925802001-09-23 03:17:28 +000038
Barry Warsaw24f79762004-05-09 03:55:11 +000039from quopri import decodestring as _qdecode
Barry Warsawba925802001-09-23 03:17:28 +000040
41# Intrapackage imports
Barry Warsaw40ef0062006-03-18 15:41:53 +000042from email.encoders import _bencode, _qencode
Barry Warsawba925802001-09-23 03:17:28 +000043
44COMMASPACE = ', '
Barry Warsaw12566a82002-06-29 05:58:04 +000045EMPTYSTRING = ''
Barry Warsawba925802001-09-23 03:17:28 +000046UEMPTYSTRING = u''
Barry Warsaw409a4c02002-04-10 21:01:31 +000047CRLF = '\r\n'
Barry Warsaw18d2f392006-07-17 23:07:51 +000048TICK = "'"
Barry Warsaw409a4c02002-04-10 21:01:31 +000049
Barry Warsawa2369922003-03-10 19:20:18 +000050specialsre = re.compile(r'[][\\()<>@,:;".]')
51escapesre = re.compile(r'[][\\()"]')
Barry Warsawba925802001-09-23 03:17:28 +000052
53
Barry Warsawe968ead2001-10-04 17:05:11 +000054
Barry Warsawba925802001-09-23 03:17:28 +000055# Helpers
56
57def _identity(s):
58 return s
59
60
61def _bdecode(s):
Barry Warsawba925802001-09-23 03:17:28 +000062 # We can't quite use base64.encodestring() since it tacks on a "courtesy
63 # newline". Blech!
64 if not s:
65 return s
Barry Warsawba925802001-09-23 03:17:28 +000066 value = base64.decodestring(s)
Barry Warsaw5bdb2be2002-09-28 20:49:57 +000067 if not s.endswith('\n') and value.endswith('\n'):
Barry Warsawba925802001-09-23 03:17:28 +000068 return value[:-1]
69 return value
70
71
Barry Warsawe968ead2001-10-04 17:05:11 +000072
Barry Warsaw409a4c02002-04-10 21:01:31 +000073def fix_eols(s):
74 """Replace all line-ending characters with \r\n."""
75 # Fix newlines with no preceding carriage return
76 s = re.sub(r'(?<!\r)\n', CRLF, s)
77 # Fix carriage returns with no following newline
78 s = re.sub(r'\r(?!\n)', CRLF, s)
79 return s
80
81
82
83def formataddr(pair):
84 """The inverse of parseaddr(), this takes a 2-tuple of the form
85 (realname, email_address) and returns the string value suitable
Barry Warsaw5bdb2be2002-09-28 20:49:57 +000086 for an RFC 2822 From, To or Cc header.
Tim Peters8ac14952002-05-23 15:15:30 +000087
Barry Warsaw409a4c02002-04-10 21:01:31 +000088 If the first element of pair is false, then the second element is
89 returned unmodified.
90 """
91 name, address = pair
92 if name:
93 quotes = ''
94 if specialsre.search(name):
95 quotes = '"'
96 name = escapesre.sub(r'\\\g<0>', name)
97 return '%s%s%s <%s>' % (quotes, name, quotes, address)
98 return address
99
Barry Warsaw409a4c02002-04-10 21:01:31 +0000100
101
Barry Warsawba925802001-09-23 03:17:28 +0000102def getaddresses(fieldvalues):
103 """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
104 all = COMMASPACE.join(fieldvalues)
Barry Warsawe1df15c2002-04-12 20:50:05 +0000105 a = _AddressList(all)
Barry Warsaw4be9ecc2002-05-22 01:52:10 +0000106 return a.addresslist
Barry Warsawba925802001-09-23 03:17:28 +0000107
108
Barry Warsawe968ead2001-10-04 17:05:11 +0000109
Barry Warsawba925802001-09-23 03:17:28 +0000110ecre = re.compile(r'''
111 =\? # literal =?
112 (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
113 \? # literal ?
114 (?P<encoding>[qb]) # either a "q" or a "b", case insensitive
115 \? # literal ?
116 (?P<atom>.*?) # non-greedy up to the next ?= is the atom
117 \?= # literal ?=
118 ''', re.VERBOSE | re.IGNORECASE)
119
120
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000121
Anthony Baxter3dd9e462004-10-11 13:53:08 +0000122def formatdate(timeval=None, localtime=False, usegmt=False):
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000123 """Returns a date string as specified by RFC 2822, e.g.:
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000124
125 Fri, 09 Nov 2001 01:08:47 -0000
126
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000127 Optional timeval if given is a floating point time value as accepted by
128 gmtime() and localtime(), otherwise the current time is used.
129
Barry Warsaw5bdb2be2002-09-28 20:49:57 +0000130 Optional localtime is a flag that when True, interprets timeval, and
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000131 returns a date relative to the local timezone instead of UTC, properly
132 taking daylight savings time into account.
Anthony Baxter3dd9e462004-10-11 13:53:08 +0000133
Tim Peterse718f612004-10-12 21:51:32 +0000134 Optional argument usegmt means that the timezone is written out as
Anthony Baxter3dd9e462004-10-11 13:53:08 +0000135 an ascii string, not numeric one (so "GMT" instead of "+0000"). This
136 is needed for HTTP, and is only used when localtime==False.
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000137 """
138 # Note: we cannot use strftime() because that honors the locale and RFC
139 # 2822 requires that day and month names be the English abbreviations.
140 if timeval is None:
141 timeval = time.time()
142 if localtime:
143 now = time.localtime(timeval)
144 # Calculate timezone offset, based on whether the local zone has
145 # daylight savings time, and whether DST is in effect.
146 if time.daylight and now[-1]:
147 offset = time.altzone
148 else:
149 offset = time.timezone
Barry Warsawe5739a62001-11-19 18:36:43 +0000150 hours, minutes = divmod(abs(offset), 3600)
151 # Remember offset is in seconds west of UTC, but the timezone is in
152 # minutes east of UTC, so the signs differ.
153 if offset > 0:
154 sign = '-'
155 else:
156 sign = '+'
Barry Warsawbb113862004-10-03 03:16:19 +0000157 zone = '%s%02d%02d' % (sign, hours, minutes // 60)
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000158 else:
159 now = time.gmtime(timeval)
160 # Timezone offset is always -0000
Anthony Baxter3dd9e462004-10-11 13:53:08 +0000161 if usegmt:
162 zone = 'GMT'
163 else:
164 zone = '-0000'
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000165 return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
166 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
167 now[2],
168 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
169 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
170 now[0], now[3], now[4], now[5],
171 zone)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000172
173
174
175def make_msgid(idstring=None):
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000176 """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000177
178 <20020201195627.33539.96671@nightshade.la.mastaler.com>
179
180 Optional idstring if given is a string used to strengthen the
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000181 uniqueness of the message id.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000182 """
183 timeval = time.time()
184 utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
185 pid = os.getpid()
186 randint = random.randrange(100000)
187 if idstring is None:
188 idstring = ''
189 else:
190 idstring = '.' + idstring
191 idhost = socket.getfqdn()
192 msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
193 return msgid
194
195
196
197# These functions are in the standalone mimelib version only because they've
198# subsequently been fixed in the latest Python versions. We use this to worm
199# around broken older Pythons.
200def parsedate(data):
201 if not data:
202 return None
203 return _parsedate(data)
204
205
206def parsedate_tz(data):
207 if not data:
208 return None
209 return _parsedate_tz(data)
210
211
212def parseaddr(addr):
Barry Warsaw24fd0252002-04-15 22:00:25 +0000213 addrs = _AddressList(addr).addresslist
214 if not addrs:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000215 return '', ''
Barry Warsaw24fd0252002-04-15 22:00:25 +0000216 return addrs[0]
Barry Warsaw12566a82002-06-29 05:58:04 +0000217
218
Barry Warsaw184d55a2002-09-11 02:22:48 +0000219# rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
220def unquote(str):
221 """Remove quotes from a string."""
222 if len(str) > 1:
223 if str.startswith('"') and str.endswith('"'):
224 return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
225 if str.startswith('<') and str.endswith('>'):
226 return str[1:-1]
227 return str
228
229
Barry Warsaw12566a82002-06-29 05:58:04 +0000230
231# RFC2231-related functions - parameter encoding and decoding
232def decode_rfc2231(s):
233 """Decode string according to RFC 2231"""
Barry Warsaw18d2f392006-07-17 23:07:51 +0000234 parts = s.split(TICK, 2)
235 if len(parts) <= 2:
Barry Warsawb110bad2006-07-21 14:51:07 +0000236 return None, None, s
Barry Warsawb110bad2006-07-21 14:51:07 +0000237 return parts
Barry Warsaw12566a82002-06-29 05:58:04 +0000238
239
240def encode_rfc2231(s, charset=None, language=None):
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000241 """Encode string according to RFC 2231.
242
243 If neither charset nor language is given, then s is returned as-is. If
244 charset is given but not language, the string is encoded using the empty
245 string for language.
246 """
Barry Warsaw12566a82002-06-29 05:58:04 +0000247 import urllib
248 s = urllib.quote(s, safe='')
249 if charset is None and language is None:
250 return s
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000251 if language is None:
252 language = ''
253 return "%s'%s'%s" % (charset, language, s)
Barry Warsaw12566a82002-06-29 05:58:04 +0000254
255
256rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$')
257
258def decode_params(params):
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000259 """Decode parameters list according to RFC 2231.
260
Barry Warsawb110bad2006-07-21 14:51:07 +0000261 params is a sequence of 2-tuples containing (param name, string value).
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000262 """
Barry Warsawb110bad2006-07-21 14:51:07 +0000263 # Copy params so we don't mess with the original
264 params = params[:]
Barry Warsaw12566a82002-06-29 05:58:04 +0000265 new_params = []
Barry Warsawb110bad2006-07-21 14:51:07 +0000266 # Map parameter's name to a list of continuations. The values are a
267 # 3-tuple of the continuation number, the string value, and a flag
268 # specifying whether a particular segment is %-encoded.
Barry Warsaw12566a82002-06-29 05:58:04 +0000269 rfc2231_params = {}
Barry Warsawb110bad2006-07-21 14:51:07 +0000270 name, value = params.pop(0)
Barry Warsaw12566a82002-06-29 05:58:04 +0000271 new_params.append((name, value))
Barry Warsawb110bad2006-07-21 14:51:07 +0000272 while params:
273 name, value = params.pop(0)
274 if name.endswith('*'):
275 encoded = True
276 else:
277 encoded = False
Barry Warsaw12566a82002-06-29 05:58:04 +0000278 value = unquote(value)
279 mo = rfc2231_continuation.match(name)
280 if mo:
281 name, num = mo.group('name', 'num')
282 if num is not None:
283 num = int(num)
Barry Warsawb110bad2006-07-21 14:51:07 +0000284 rfc2231_params.setdefault(name, []).append((num, value, encoded))
Barry Warsaw12566a82002-06-29 05:58:04 +0000285 else:
286 new_params.append((name, '"%s"' % quote(value)))
287 if rfc2231_params:
288 for name, continuations in rfc2231_params.items():
289 value = []
Barry Warsawb110bad2006-07-21 14:51:07 +0000290 extended = False
Barry Warsaw12566a82002-06-29 05:58:04 +0000291 # Sort by number
292 continuations.sort()
Barry Warsawb110bad2006-07-21 14:51:07 +0000293 # And now append all values in numerical order, converting
294 # %-encodings for the encoded segments. If any of the
295 # continuation names ends in a *, then the entire string, after
296 # decoding segments and concatenating, must have the charset and
297 # language specifiers at the beginning of the string.
298 for num, s, encoded in continuations:
299 if encoded:
300 s = urllib.unquote(s)
301 extended = True
302 value.append(s)
303 value = quote(EMPTYSTRING.join(value))
304 if extended:
305 charset, language, value = decode_rfc2231(value)
306 new_params.append((name, (charset, language, '"%s"' % value)))
307 else:
308 new_params.append((name, '"%s"' % value))
Barry Warsaw12566a82002-06-29 05:58:04 +0000309 return new_params
Barry Warsawbb113862004-10-03 03:16:19 +0000310
311def collapse_rfc2231_value(value, errors='replace',
312 fallback_charset='us-ascii'):
313 if isinstance(value, tuple):
314 rawval = unquote(value[2])
315 charset = value[0] or 'us-ascii'
316 try:
317 return unicode(rawval, charset, errors)
318 except LookupError:
319 # XXX charset is unknown to Python.
320 return unicode(rawval, fallback_charset, errors)
321 else:
322 return unquote(value)