blob: a40226dc1462c17b001ebb700847c1969b4e647d [file] [log] [blame]
Barry Warsaw409a4c02002-04-10 21:01:31 +00001# Copyright (C) 2002 Python Software Foundation
Barry Warsaw174aa492002-09-30 15:51:31 +00002# Author: che@debian.org (Ben Gertzfield), barry@zope.com (Barry Warsaw)
Barry Warsaw409a4c02002-04-10 21:01:31 +00003
4"""Header encoding and decoding functionality."""
5
6import re
Barry Warsaw174aa492002-09-30 15:51:31 +00007from types import StringType, UnicodeType
8
Barry Warsaw409a4c02002-04-10 21:01:31 +00009import email.quopriMIME
10import email.base64MIME
11from email.Charset import Charset
12
Barry Warsaw812031b2002-05-19 23:47:53 +000013try:
Barry Warsaw1c30aa22002-06-01 05:49:17 +000014 from email._compat22 import _floordiv
Barry Warsaw812031b2002-05-19 23:47:53 +000015except SyntaxError:
16 # Python 2.1 spells integer division differently
Barry Warsaw1c30aa22002-06-01 05:49:17 +000017 from email._compat21 import _floordiv
Barry Warsaw812031b2002-05-19 23:47:53 +000018
Barry Warsaw174aa492002-09-30 15:51:31 +000019try:
20 True, False
21except NameError:
22 True = 1
23 False = 0
24
Barry Warsaw409a4c02002-04-10 21:01:31 +000025CRLFSPACE = '\r\n '
26CRLF = '\r\n'
Barry Warsaw76612502002-06-28 23:46:53 +000027NL = '\n'
28SPACE8 = ' ' * 8
29EMPTYSTRING = ''
Barry Warsaw409a4c02002-04-10 21:01:31 +000030
31MAXLINELEN = 76
32
33ENCODE = 1
34DECODE = 2
35
Barry Warsaw174aa492002-09-30 15:51:31 +000036USASCII = Charset('us-ascii')
37UTF8 = Charset('utf-8')
38
Barry Warsaw409a4c02002-04-10 21:01:31 +000039# Match encoded-word strings in the form =?charset?q?Hello_World?=
40ecre = re.compile(r'''
41 =\? # literal =?
42 (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
43 \? # literal ?
44 (?P<encoding>[qb]) # either a "q" or a "b", case insensitive
45 \? # literal ?
46 (?P<encoded>.*?) # non-greedy up to the next ?= is the encoded string
47 \?= # literal ?=
48 ''', re.VERBOSE | re.IGNORECASE)
49
50
51
52# Helpers
53_max_append = email.quopriMIME._max_append
54
55
56
57def decode_header(header):
58 """Decode a message header value without converting charset.
59
60 Returns a list of (decoded_string, charset) pairs containing each of the
61 decoded parts of the header. Charset is None for non-encoded parts of the
62 header, otherwise a lower-case string containing the name of the character
63 set specified in the encoded string.
64 """
65 # If no encoding, just return the header
66 header = str(header)
67 if not ecre.search(header):
68 return [(header, None)]
Barry Warsaw409a4c02002-04-10 21:01:31 +000069 decoded = []
70 dec = ''
71 for line in header.splitlines():
72 # This line might not have an encoding in it
73 if not ecre.search(line):
74 decoded.append((line, None))
75 continue
Barry Warsaw409a4c02002-04-10 21:01:31 +000076 parts = ecre.split(line)
77 while parts:
78 unenc = parts.pop(0).strip()
79 if unenc:
80 # Should we continue a long line?
81 if decoded and decoded[-1][1] is None:
82 decoded[-1] = (decoded[-1][0] + dec, None)
83 else:
84 decoded.append((unenc, None))
85 if parts:
86 charset, encoding = [s.lower() for s in parts[0:2]]
87 encoded = parts[2]
88 dec = ''
89 if encoding == 'q':
90 dec = email.quopriMIME.header_decode(encoded)
91 elif encoding == 'b':
92 dec = email.base64MIME.decode(encoded)
93 else:
94 dec = encoded
95
96 if decoded and decoded[-1][1] == charset:
97 decoded[-1] = (decoded[-1][0] + dec, decoded[-1][1])
98 else:
99 decoded.append((dec, charset))
100 del parts[0:3]
101 return decoded
102
103
104
Barry Warsaw8da39aa2002-07-09 16:33:47 +0000105def make_header(decoded_seq, maxlinelen=None, header_name=None,
106 continuation_ws=' '):
107 """Create a Header from a sequence of pairs as returned by decode_header()
108
109 decode_header() takes a header value string and returns a sequence of
110 pairs of the format (decoded_string, charset) where charset is the string
111 name of the character set.
112
113 This function takes one of those sequence of pairs and returns a Header
114 instance. Optional maxlinelen, header_name, and continuation_ws are as in
115 the Header constructor.
116 """
117 h = Header(maxlinelen=maxlinelen, header_name=header_name,
118 continuation_ws=continuation_ws)
119 for s, charset in decoded_seq:
Barry Warsaw15d37392002-07-23 04:29:54 +0000120 # None means us-ascii but we can simply pass it on to h.append()
121 if charset is not None and not isinstance(charset, Charset):
Barry Warsaw8da39aa2002-07-09 16:33:47 +0000122 charset = Charset(charset)
123 h.append(s, charset)
124 return h
125
126
127
Barry Warsaw409a4c02002-04-10 21:01:31 +0000128class Header:
Barry Warsaw8da39aa2002-07-09 16:33:47 +0000129 def __init__(self, s=None, charset=None, maxlinelen=None, header_name=None,
Barry Warsaw76612502002-06-28 23:46:53 +0000130 continuation_ws=' '):
Barry Warsaw174aa492002-09-30 15:51:31 +0000131 """Create a MIME-compliant header that can contain many character sets.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000132
Barry Warsaw174aa492002-09-30 15:51:31 +0000133 Optional s is the initial header value. If None, the initial header
134 value is not set. You can later append to the header with .append()
135 method calls. s may be a byte string or a Unicode string, but see the
136 .append() documentation for semantics.
Barry Warsaw8da39aa2002-07-09 16:33:47 +0000137
Barry Warsaw174aa492002-09-30 15:51:31 +0000138 Optional charset serves two purposes: it has the same meaning as the
139 charset argument to the .append() method. It also sets the default
140 character set for all subsequent .append() calls that omit the charset
141 argument. If charset is not provided in the constructor, the us-ascii
142 charset is used both as s's initial charset and as the default for
143 subsequent .append() calls.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000144
Barry Warsaw76612502002-06-28 23:46:53 +0000145 The maximum line length can be specified explicit via maxlinelen. For
146 splitting the first line to a shorter value (to account for the field
147 header which isn't included in s, e.g. `Subject') pass in the name of
148 the field in header_name. The default maxlinelen is 76.
149
150 continuation_ws must be RFC 2822 compliant folding whitespace (usually
151 either a space or a hard tab) which will be prepended to continuation
152 lines.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000153 """
154 if charset is None:
Barry Warsaw174aa492002-09-30 15:51:31 +0000155 charset = USASCII
Barry Warsaw409a4c02002-04-10 21:01:31 +0000156 self._charset = charset
Barry Warsaw76612502002-06-28 23:46:53 +0000157 self._continuation_ws = continuation_ws
158 cws_expanded_len = len(continuation_ws.replace('\t', SPACE8))
Barry Warsaw409a4c02002-04-10 21:01:31 +0000159 # BAW: I believe `chunks' and `maxlinelen' should be non-public.
160 self._chunks = []
Barry Warsaw8da39aa2002-07-09 16:33:47 +0000161 if s is not None:
162 self.append(s, charset)
Barry Warsaw812031b2002-05-19 23:47:53 +0000163 if maxlinelen is None:
Barry Warsaw76612502002-06-28 23:46:53 +0000164 maxlinelen = MAXLINELEN
165 if header_name is None:
166 # We don't know anything about the field header so the first line
167 # is the same length as subsequent lines.
168 self._firstlinelen = maxlinelen
Barry Warsaw812031b2002-05-19 23:47:53 +0000169 else:
Barry Warsaw76612502002-06-28 23:46:53 +0000170 # The first line should be shorter to take into account the field
171 # header. Also subtract off 2 extra for the colon and space.
172 self._firstlinelen = maxlinelen - len(header_name) - 2
173 # Second and subsequent lines should subtract off the length in
174 # columns of the continuation whitespace prefix.
175 self._maxlinelen = maxlinelen - cws_expanded_len
Barry Warsaw409a4c02002-04-10 21:01:31 +0000176
177 def __str__(self):
178 """A synonym for self.encode()."""
179 return self.encode()
180
Barry Warsaw8e69bda2002-06-29 03:26:58 +0000181 def __unicode__(self):
182 """Helper for the built-in unicode function."""
183 # charset item is a Charset instance so we need to stringify it.
184 uchunks = [unicode(s, str(charset)) for s, charset in self._chunks]
185 return u''.join(uchunks)
186
Barry Warsaw8da39aa2002-07-09 16:33:47 +0000187 # Rich comparison operators for equality only. BAW: does it make sense to
188 # have or explicitly disable <, <=, >, >= operators?
189 def __eq__(self, other):
190 # other may be a Header or a string. Both are fine so coerce
191 # ourselves to a string, swap the args and do another comparison.
192 return other == self.encode()
193
194 def __ne__(self, other):
195 return not self == other
196
Barry Warsaw409a4c02002-04-10 21:01:31 +0000197 def append(self, s, charset=None):
Barry Warsaw174aa492002-09-30 15:51:31 +0000198 """Append a string to the MIME header.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000199
Barry Warsaw174aa492002-09-30 15:51:31 +0000200 Optional charset, if given, should be a Charset instance or the name
201 of a character set (which will be converted to a Charset instance). A
202 value of None (the default) means that the charset given in the
203 constructor is used.
204
205 s may be a byte string or a Unicode string. If it is a byte string
206 (i.e. isinstance(s, StringType) is true), then charset is the encoding
207 of that byte string, and a UnicodeError will be raised if the string
Barry Warsaw48330682002-09-30 23:07:35 +0000208 cannot be decoded with that charset. If s is a Unicode string, then
Barry Warsaw174aa492002-09-30 15:51:31 +0000209 charset is a hint specifying the character set of the characters in
210 the string. In this case, when producing an RFC 2822 compliant header
211 using RFC 2047 rules, the Unicode string will be encoded using the
Barry Warsaw48330682002-09-30 23:07:35 +0000212 following charsets in order: us-ascii, the charset hint, utf-8. The
213 first character set not to provoke a UnicodeError is used.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000214 """
215 if charset is None:
216 charset = self._charset
Barry Warsaw92825a92002-07-23 06:08:10 +0000217 elif not isinstance(charset, Charset):
218 charset = Charset(charset)
Barry Warsaw174aa492002-09-30 15:51:31 +0000219 # Normalize and check the string
220 if isinstance(s, StringType):
221 # Possibly raise UnicodeError if it can't e encoded
222 unicode(s, charset.get_output_charset())
223 elif isinstance(s, UnicodeType):
224 # Convert Unicode to byte string for later concatenation
225 for charset in USASCII, charset, UTF8:
226 try:
227 s = s.encode(charset.get_output_charset())
228 break
229 except UnicodeError:
230 pass
231 else:
232 assert False, 'Could not encode to utf-8'
Barry Warsaw409a4c02002-04-10 21:01:31 +0000233 self._chunks.append((s, charset))
Tim Peters8ac14952002-05-23 15:15:30 +0000234
Barry Warsaw174aa492002-09-30 15:51:31 +0000235 def _split(self, s, charset, firstline=False):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000236 # Split up a header safely for use with encode_chunks. BAW: this
237 # appears to be a private convenience method.
238 splittable = charset.to_splittable(s)
239 encoded = charset.from_splittable(splittable)
Barry Warsaw812031b2002-05-19 23:47:53 +0000240 elen = charset.encoded_header_len(encoded)
Tim Peters8ac14952002-05-23 15:15:30 +0000241
Barry Warsaw812031b2002-05-19 23:47:53 +0000242 if elen <= self._maxlinelen:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000243 return [(encoded, charset)]
Barry Warsaw76612502002-06-28 23:46:53 +0000244 # BAW: I'm not sure what the right test here is. What we're trying to
245 # do is be faithful to RFC 2822's recommendation that ($2.2.3):
246 #
247 # "Note: Though structured field bodies are defined in such a way that
248 # folding can take place between many of the lexical tokens (and even
249 # within some of the lexical tokens), folding SHOULD be limited to
250 # placing the CRLF at higher-level syntactic breaks."
251 #
252 # For now, I can only imagine doing this when the charset is us-ascii,
253 # although it's possible that other charsets may also benefit from the
254 # higher-level syntactic breaks.
255 #
256 elif charset == 'us-ascii':
257 return self._ascii_split(s, charset, firstline)
Barry Warsaw812031b2002-05-19 23:47:53 +0000258 # BAW: should we use encoded?
259 elif elen == len(s):
260 # We can split on _maxlinelen boundaries because we know that the
261 # encoding won't change the size of the string
262 splitpnt = self._maxlinelen
Barry Warsaw174aa492002-09-30 15:51:31 +0000263 first = charset.from_splittable(splittable[:splitpnt], False)
264 last = charset.from_splittable(splittable[splitpnt:], False)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000265 else:
Barry Warsaw1c30aa22002-06-01 05:49:17 +0000266 # Divide and conquer.
267 halfway = _floordiv(len(splittable), 2)
Barry Warsaw174aa492002-09-30 15:51:31 +0000268 first = charset.from_splittable(splittable[:halfway], False)
269 last = charset.from_splittable(splittable[halfway:], False)
Barry Warsaw76612502002-06-28 23:46:53 +0000270 # Do the split
271 return self._split(first, charset, firstline) + \
272 self._split(last, charset)
273
274 def _ascii_split(self, s, charset, firstline):
275 # Attempt to split the line at the highest-level syntactic break
276 # possible. Note that we don't have a lot of smarts about field
277 # syntax; we just try to break on semi-colons, then whitespace.
278 rtn = []
279 lines = s.splitlines()
280 while lines:
281 line = lines.pop(0)
282 if firstline:
283 maxlinelen = self._firstlinelen
Barry Warsaw174aa492002-09-30 15:51:31 +0000284 firstline = False
Barry Warsaw76612502002-06-28 23:46:53 +0000285 else:
Barry Warsaw45d9bde2002-09-10 15:57:29 +0000286 #line = line.lstrip()
Barry Warsaw76612502002-06-28 23:46:53 +0000287 maxlinelen = self._maxlinelen
288 # Short lines can remain unchanged
289 if len(line.replace('\t', SPACE8)) <= maxlinelen:
290 rtn.append(line)
291 else:
292 oldlen = len(line)
293 # Try to break the line on semicolons, but if that doesn't
294 # work, try to split on folding whitespace.
295 while len(line) > maxlinelen:
296 i = line.rfind(';', 0, maxlinelen)
297 if i < 0:
298 break
299 rtn.append(line[:i] + ';')
300 line = line[i+1:]
301 # Is the remaining stuff still longer than maxlinelen?
302 if len(line) <= maxlinelen:
303 # Splitting on semis worked
304 rtn.append(line)
305 continue
306 # Splitting on semis didn't finish the job. If it did any
307 # work at all, stick the remaining junk on the front of the
308 # `lines' sequence and let the next pass do its thing.
309 if len(line) <> oldlen:
310 lines.insert(0, line)
311 continue
312 # Otherwise, splitting on semis didn't help at all.
313 parts = re.split(r'(\s+)', line)
314 if len(parts) == 1 or (len(parts) == 3 and
315 parts[0].endswith(':')):
316 # This line can't be split on whitespace. There's now
317 # little we can do to get this into maxlinelen. BAW:
318 # We're still potentially breaking the RFC by possibly
319 # allowing lines longer than the absolute maximum of 998
320 # characters. For now, let it slide.
321 #
322 # len(parts) will be 1 if this line has no `Field: '
323 # prefix, otherwise it will be len(3).
324 rtn.append(line)
325 continue
326 # There is whitespace we can split on.
327 first = parts.pop(0)
328 sublines = [first]
329 acc = len(first)
330 while parts:
331 len0 = len(parts[0])
332 len1 = len(parts[1])
333 if acc + len0 + len1 <= maxlinelen:
334 sublines.append(parts.pop(0))
335 sublines.append(parts.pop(0))
336 acc += len0 + len1
337 else:
338 # Split it here, but don't forget to ignore the
339 # next whitespace-only part
340 if first <> '':
341 rtn.append(EMPTYSTRING.join(sublines))
342 del parts[0]
343 first = parts.pop(0)
344 sublines = [first]
345 acc = len(first)
346 rtn.append(EMPTYSTRING.join(sublines))
347 return [(chunk, charset) for chunk in rtn]
348
349 def _encode_chunks(self):
350 """MIME-encode a header with many different charsets and/or encodings.
351
352 Given a list of pairs (string, charset), return a MIME-encoded string
353 suitable for use in a header field. Each pair may have different
354 charsets and/or encodings, and the resulting header will accurately
355 reflect each setting.
356
357 Each encoding can be email.Utils.QP (quoted-printable, for ASCII-like
358 character sets like iso-8859-1), email.Utils.BASE64 (Base64, for
359 non-ASCII like character sets like KOI8-R and iso-2022-jp), or None
360 (no encoding).
361
362 Each pair will be represented on a separate line; the resulting string
363 will be in the format:
364
365 "=?charset1?q?Mar=EDa_Gonz=E1lez_Alonso?=\n
366 =?charset2?b?SvxyZ2VuIEL2aW5n?="
367 """
368 chunks = []
369 for header, charset in self._chunks:
370 if charset is None or charset.header_encoding is None:
371 # There's no encoding for this chunk's charsets
372 _max_append(chunks, header, self._maxlinelen)
373 else:
Barry Warsaw174aa492002-09-30 15:51:31 +0000374 _max_append(chunks, charset.header_encode(header),
Barry Warsaw76612502002-06-28 23:46:53 +0000375 self._maxlinelen, ' ')
376 joiner = NL + self._continuation_ws
377 return joiner.join(chunks)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000378
379 def encode(self):
Barry Warsaw48330682002-09-30 23:07:35 +0000380 """Encode a message header into an RFC-compliant format.
Barry Warsaw409a4c02002-04-10 21:01:31 +0000381
382 There are many issues involved in converting a given string for use in
383 an email header. Only certain character sets are readable in most
384 email clients, and as header strings can only contain a subset of
385 7-bit ASCII, care must be taken to properly convert and encode (with
386 Base64 or quoted-printable) header strings. In addition, there is a
387 75-character length limit on any given encoded header field, so
388 line-wrapping must be performed, even with double-byte character sets.
Tim Peters8ac14952002-05-23 15:15:30 +0000389
Barry Warsaw409a4c02002-04-10 21:01:31 +0000390 This method will do its best to convert the string to the correct
391 character set used in email, and encode and line wrap it safely with
392 the appropriate scheme for that character set.
393
394 If the given charset is not known or an error occurs during
395 conversion, this function will return the header untouched.
396 """
397 newchunks = []
398 for s, charset in self._chunks:
Barry Warsaw174aa492002-09-30 15:51:31 +0000399 newchunks += self._split(s, charset, True)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000400 self._chunks = newchunks
Barry Warsaw76612502002-06-28 23:46:53 +0000401 return self._encode_chunks()