blob: de9fbf87a53f009a898a700b4c32ff37dc0625eb [file] [log] [blame]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000028import urllib
Barry Warsaw409a4c02002-04-10 21:01:31 +000029import warnings
30from cStringIO import StringIO
Barry Warsawba925802001-09-23 03:17:28 +000031
Barry Warsaw030ddf72002-11-05 19:54:52 +000032from email._parseaddr import quote
33from email._parseaddr import AddressList as _AddressList
34from email._parseaddr import mktime_tz
Barry Warsaw409a4c02002-04-10 21:01:31 +000035
36# We need wormarounds for bugs in these methods in older Pythons (see below)
Barry Warsaw030ddf72002-11-05 19:54:52 +000037from email._parseaddr import parsedate as _parsedate
38from email._parseaddr import parsedate_tz as _parsedate_tz
Barry Warsawba925802001-09-23 03:17:28 +000039
Barry Warsaw24f79762004-05-09 03:55:11 +000040from quopri import decodestring as _qdecode
Barry Warsawba925802001-09-23 03:17:28 +000041
42# Intrapackage imports
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043from email.encoders import _bencode, _qencode
Barry Warsawba925802001-09-23 03:17:28 +000044
45COMMASPACE = ', '
Barry Warsaw12566a82002-06-29 05:58:04 +000046EMPTYSTRING = ''
Guido van Rossumef87d6e2007-05-02 19:09:54 +000047UEMPTYSTRING = ''
Barry Warsaw409a4c02002-04-10 21:01:31 +000048CRLF = '\r\n'
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049TICK = "'"
Barry Warsaw409a4c02002-04-10 21:01:31 +000050
Barry Warsawa2369922003-03-10 19:20:18 +000051specialsre = re.compile(r'[][\\()<>@,:;".]')
52escapesre = re.compile(r'[][\\()"]')
Barry Warsawba925802001-09-23 03:17:28 +000053
54
Barry Warsawe968ead2001-10-04 17:05:11 +000055
Barry Warsawba925802001-09-23 03:17:28 +000056# Helpers
57
58def _identity(s):
59 return s
60
61
62def _bdecode(s):
Barry Warsawba925802001-09-23 03:17:28 +000063 # We can't quite use base64.encodestring() since it tacks on a "courtesy
64 # newline". Blech!
65 if not s:
66 return s
Barry Warsawba925802001-09-23 03:17:28 +000067 value = base64.decodestring(s)
Barry Warsaw5bdb2be2002-09-28 20:49:57 +000068 if not s.endswith('\n') and value.endswith('\n'):
Barry Warsawba925802001-09-23 03:17:28 +000069 return value[:-1]
70 return value
71
72
Barry Warsawe968ead2001-10-04 17:05:11 +000073
Barry Warsaw409a4c02002-04-10 21:01:31 +000074def fix_eols(s):
75 """Replace all line-ending characters with \r\n."""
76 # Fix newlines with no preceding carriage return
77 s = re.sub(r'(?<!\r)\n', CRLF, s)
78 # Fix carriage returns with no following newline
79 s = re.sub(r'\r(?!\n)', CRLF, s)
80 return s
81
82
83
84def formataddr(pair):
85 """The inverse of parseaddr(), this takes a 2-tuple of the form
86 (realname, email_address) and returns the string value suitable
Barry Warsaw5bdb2be2002-09-28 20:49:57 +000087 for an RFC 2822 From, To or Cc header.
Tim Peters8ac14952002-05-23 15:15:30 +000088
Barry Warsaw409a4c02002-04-10 21:01:31 +000089 If the first element of pair is false, then the second element is
90 returned unmodified.
91 """
92 name, address = pair
93 if name:
94 quotes = ''
95 if specialsre.search(name):
96 quotes = '"'
97 name = escapesre.sub(r'\\\g<0>', name)
98 return '%s%s%s <%s>' % (quotes, name, quotes, address)
99 return address
100
Barry Warsaw409a4c02002-04-10 21:01:31 +0000101
102
Barry Warsawba925802001-09-23 03:17:28 +0000103def getaddresses(fieldvalues):
104 """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
105 all = COMMASPACE.join(fieldvalues)
Barry Warsawe1df15c2002-04-12 20:50:05 +0000106 a = _AddressList(all)
Barry Warsaw4be9ecc2002-05-22 01:52:10 +0000107 return a.addresslist
Barry Warsawba925802001-09-23 03:17:28 +0000108
109
Barry Warsawe968ead2001-10-04 17:05:11 +0000110
Barry Warsawba925802001-09-23 03:17:28 +0000111ecre = re.compile(r'''
112 =\? # literal =?
113 (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
114 \? # literal ?
115 (?P<encoding>[qb]) # either a "q" or a "b", case insensitive
116 \? # literal ?
117 (?P<atom>.*?) # non-greedy up to the next ?= is the atom
118 \?= # literal ?=
119 ''', re.VERBOSE | re.IGNORECASE)
120
121
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000122
Anthony Baxter3dd9e462004-10-11 13:53:08 +0000123def formatdate(timeval=None, localtime=False, usegmt=False):
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000124 """Returns a date string as specified by RFC 2822, e.g.:
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000125
126 Fri, 09 Nov 2001 01:08:47 -0000
127
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000128 Optional timeval if given is a floating point time value as accepted by
129 gmtime() and localtime(), otherwise the current time is used.
130
Barry Warsaw5bdb2be2002-09-28 20:49:57 +0000131 Optional localtime is a flag that when True, interprets timeval, and
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000132 returns a date relative to the local timezone instead of UTC, properly
133 taking daylight savings time into account.
Anthony Baxter3dd9e462004-10-11 13:53:08 +0000134
Tim Peterse718f612004-10-12 21:51:32 +0000135 Optional argument usegmt means that the timezone is written out as
Anthony Baxter3dd9e462004-10-11 13:53:08 +0000136 an ascii string, not numeric one (so "GMT" instead of "+0000"). This
137 is needed for HTTP, and is only used when localtime==False.
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000138 """
139 # Note: we cannot use strftime() because that honors the locale and RFC
140 # 2822 requires that day and month names be the English abbreviations.
141 if timeval is None:
142 timeval = time.time()
143 if localtime:
144 now = time.localtime(timeval)
145 # Calculate timezone offset, based on whether the local zone has
146 # daylight savings time, and whether DST is in effect.
147 if time.daylight and now[-1]:
148 offset = time.altzone
149 else:
150 offset = time.timezone
Barry Warsawe5739a62001-11-19 18:36:43 +0000151 hours, minutes = divmod(abs(offset), 3600)
152 # Remember offset is in seconds west of UTC, but the timezone is in
153 # minutes east of UTC, so the signs differ.
154 if offset > 0:
155 sign = '-'
156 else:
157 sign = '+'
Barry Warsawbb113862004-10-03 03:16:19 +0000158 zone = '%s%02d%02d' % (sign, hours, minutes // 60)
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000159 else:
160 now = time.gmtime(timeval)
161 # Timezone offset is always -0000
Anthony Baxter3dd9e462004-10-11 13:53:08 +0000162 if usegmt:
163 zone = 'GMT'
164 else:
165 zone = '-0000'
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000166 return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
167 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
168 now[2],
169 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
170 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
171 now[0], now[3], now[4], now[5],
172 zone)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000173
174
175
176def make_msgid(idstring=None):
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000177 """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000178
179 <20020201195627.33539.96671@nightshade.la.mastaler.com>
180
181 Optional idstring if given is a string used to strengthen the
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000182 uniqueness of the message id.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000183 """
184 timeval = time.time()
185 utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
186 pid = os.getpid()
187 randint = random.randrange(100000)
188 if idstring is None:
189 idstring = ''
190 else:
191 idstring = '.' + idstring
192 idhost = socket.getfqdn()
193 msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
194 return msgid
195
196
197
198# These functions are in the standalone mimelib version only because they've
199# subsequently been fixed in the latest Python versions. We use this to worm
200# around broken older Pythons.
201def parsedate(data):
202 if not data:
203 return None
204 return _parsedate(data)
205
206
207def parsedate_tz(data):
208 if not data:
209 return None
210 return _parsedate_tz(data)
211
212
213def parseaddr(addr):
Barry Warsaw24fd0252002-04-15 22:00:25 +0000214 addrs = _AddressList(addr).addresslist
215 if not addrs:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000216 return '', ''
Barry Warsaw24fd0252002-04-15 22:00:25 +0000217 return addrs[0]
Barry Warsaw12566a82002-06-29 05:58:04 +0000218
219
Barry Warsaw184d55a2002-09-11 02:22:48 +0000220# rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
221def unquote(str):
222 """Remove quotes from a string."""
223 if len(str) > 1:
224 if str.startswith('"') and str.endswith('"'):
225 return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
226 if str.startswith('<') and str.endswith('>'):
227 return str[1:-1]
228 return str
229
230
Barry Warsaw12566a82002-06-29 05:58:04 +0000231
232# RFC2231-related functions - parameter encoding and decoding
233def decode_rfc2231(s):
234 """Decode string according to RFC 2231"""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000235 parts = s.split(TICK, 2)
236 if len(parts) <= 2:
237 return None, None, s
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000238 return parts
Barry Warsaw12566a82002-06-29 05:58:04 +0000239
240
241def encode_rfc2231(s, charset=None, language=None):
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000242 """Encode string according to RFC 2231.
243
244 If neither charset nor language is given, then s is returned as-is. If
245 charset is given but not language, the string is encoded using the empty
246 string for language.
247 """
Barry Warsaw12566a82002-06-29 05:58:04 +0000248 import urllib
249 s = urllib.quote(s, safe='')
250 if charset is None and language is None:
251 return s
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000252 if language is None:
253 language = ''
254 return "%s'%s'%s" % (charset, language, s)
Barry Warsaw12566a82002-06-29 05:58:04 +0000255
256
257rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$')
258
259def decode_params(params):
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000260 """Decode parameters list according to RFC 2231.
261
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000262 params is a sequence of 2-tuples containing (param name, string value).
Barry Warsaw0ebc5c92002-10-01 00:44:13 +0000263 """
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000264 # Copy params so we don't mess with the original
265 params = params[:]
Barry Warsaw12566a82002-06-29 05:58:04 +0000266 new_params = []
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000267 # Map parameter's name to a list of continuations. The values are a
268 # 3-tuple of the continuation number, the string value, and a flag
269 # specifying whether a particular segment is %-encoded.
Barry Warsaw12566a82002-06-29 05:58:04 +0000270 rfc2231_params = {}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000271 name, value = params.pop(0)
Barry Warsaw12566a82002-06-29 05:58:04 +0000272 new_params.append((name, value))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000273 while params:
274 name, value = params.pop(0)
275 if name.endswith('*'):
276 encoded = True
277 else:
278 encoded = False
Barry Warsaw12566a82002-06-29 05:58:04 +0000279 value = unquote(value)
280 mo = rfc2231_continuation.match(name)
281 if mo:
282 name, num = mo.group('name', 'num')
283 if num is not None:
284 num = int(num)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000285 rfc2231_params.setdefault(name, []).append((num, value, encoded))
Barry Warsaw12566a82002-06-29 05:58:04 +0000286 else:
287 new_params.append((name, '"%s"' % quote(value)))
288 if rfc2231_params:
289 for name, continuations in rfc2231_params.items():
290 value = []
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000291 extended = False
Barry Warsaw12566a82002-06-29 05:58:04 +0000292 # Sort by number
293 continuations.sort()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000294 # And now append all values in numerical order, converting
295 # %-encodings for the encoded segments. If any of the
296 # continuation names ends in a *, then the entire string, after
297 # decoding segments and concatenating, must have the charset and
298 # language specifiers at the beginning of the string.
299 for num, s, encoded in continuations:
300 if encoded:
301 s = urllib.unquote(s)
302 extended = True
303 value.append(s)
304 value = quote(EMPTYSTRING.join(value))
305 if extended:
306 charset, language, value = decode_rfc2231(value)
307 new_params.append((name, (charset, language, '"%s"' % value)))
308 else:
309 new_params.append((name, '"%s"' % value))
Barry Warsaw12566a82002-06-29 05:58:04 +0000310 return new_params
Barry Warsawbb113862004-10-03 03:16:19 +0000311
312def collapse_rfc2231_value(value, errors='replace',
313 fallback_charset='us-ascii'):
314 if isinstance(value, tuple):
315 rawval = unquote(value[2])
316 charset = value[0] or 'us-ascii'
317 try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000318 return str(rawval, charset, errors)
Barry Warsawbb113862004-10-03 03:16:19 +0000319 except LookupError:
320 # XXX charset is unknown to Python.
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000321 return str(rawval, fallback_charset, errors)
Barry Warsawbb113862004-10-03 03:16:19 +0000322 else:
323 return unquote(value)