blob: d5e8df99404c050f9d940da7b7b2ece2b3ec6776 [file] [log] [blame]
R David Murrayc27e5222012-05-25 15:01:48 -04001"""Policy framework for the email package.
2
3Allows fine grained feature control of how the package parses and emits data.
4"""
5
6import abc
7from email import header
8from email import charset as _charset
9from email.utils import _has_surrogates
10
11__all__ = [
12 'Policy',
13 'Compat32',
14 'compat32',
15 ]
16
17
18class _PolicyBase:
19
20 """Policy Object basic framework.
21
22 This class is useless unless subclassed. A subclass should define
23 class attributes with defaults for any values that are to be
24 managed by the Policy object. The constructor will then allow
25 non-default values to be set for these attributes at instance
26 creation time. The instance will be callable, taking these same
27 attributes keyword arguments, and returning a new instance
28 identical to the called instance except for those values changed
29 by the keyword arguments. Instances may be added, yielding new
30 instances with any non-default values from the right hand
31 operand overriding those in the left hand operand. That is,
32
33 A + B == A(<non-default values of B>)
34
35 The repr of an instance can be used to reconstruct the object
36 if and only if the repr of the values can be used to reconstruct
37 those values.
38
39 """
40
41 def __init__(self, **kw):
42 """Create new Policy, possibly overriding some defaults.
43
44 See class docstring for a list of overridable attributes.
45
46 """
47 for name, value in kw.items():
48 if hasattr(self, name):
49 super(_PolicyBase,self).__setattr__(name, value)
50 else:
51 raise TypeError(
52 "{!r} is an invalid keyword argument for {}".format(
53 name, self.__class__.__name__))
54
55 def __repr__(self):
56 args = [ "{}={!r}".format(name, value)
57 for name, value in self.__dict__.items() ]
58 return "{}({})".format(self.__class__.__name__, ', '.join(args))
59
60 def clone(self, **kw):
61 """Return a new instance with specified attributes changed.
62
63 The new instance has the same attribute values as the current object,
64 except for the changes passed in as keyword arguments.
65
66 """
R David Murray0b6f6c82012-05-25 18:42:14 -040067 newpolicy = self.__class__.__new__(self.__class__)
R David Murrayc27e5222012-05-25 15:01:48 -040068 for attr, value in self.__dict__.items():
R David Murray0b6f6c82012-05-25 18:42:14 -040069 object.__setattr__(newpolicy, attr, value)
70 for attr, value in kw.items():
71 if not hasattr(self, attr):
72 raise TypeError(
73 "{!r} is an invalid keyword argument for {}".format(
74 attr, self.__class__.__name__))
75 object.__setattr__(newpolicy, attr, value)
76 return newpolicy
R David Murrayc27e5222012-05-25 15:01:48 -040077
78 def __setattr__(self, name, value):
79 if hasattr(self, name):
80 msg = "{!r} object attribute {!r} is read-only"
81 else:
82 msg = "{!r} object has no attribute {!r}"
83 raise AttributeError(msg.format(self.__class__.__name__, name))
84
85 def __add__(self, other):
86 """Non-default values from right operand override those from left.
87
88 The object returned is a new instance of the subclass.
89
90 """
91 return self.clone(**other.__dict__)
92
93
94# Conceptually this isn't a subclass of ABCMeta, but since we want Policy to
95# use ABCMeta as a metaclass *and* we want it to use this one as well, we have
96# to make this one a subclas of ABCMeta.
97class _DocstringExtenderMetaclass(abc.ABCMeta):
98
99 def __new__(meta, classname, bases, classdict):
100 if classdict.get('__doc__') and classdict['__doc__'].startswith('+'):
101 classdict['__doc__'] = meta._append_doc(bases[0].__doc__,
102 classdict['__doc__'])
103 for name, attr in classdict.items():
104 if attr.__doc__ and attr.__doc__.startswith('+'):
105 for cls in (cls for base in bases for cls in base.mro()):
106 doc = getattr(getattr(cls, name), '__doc__')
107 if doc:
108 attr.__doc__ = meta._append_doc(doc, attr.__doc__)
109 break
110 return super().__new__(meta, classname, bases, classdict)
111
112 @staticmethod
113 def _append_doc(doc, added_doc):
114 added_doc = added_doc.split('\n', 1)[1]
115 return doc + '\n' + added_doc
116
117
118class Policy(_PolicyBase, metaclass=_DocstringExtenderMetaclass):
119
120 r"""Controls for how messages are interpreted and formatted.
121
122 Most of the classes and many of the methods in the email package accept
123 Policy objects as parameters. A Policy object contains a set of values and
124 functions that control how input is interpreted and how output is rendered.
125 For example, the parameter 'raise_on_defect' controls whether or not an RFC
126 violation results in an error being raised or not, while 'max_line_length'
127 controls the maximum length of output lines when a Message is serialized.
128
129 Any valid attribute may be overridden when a Policy is created by passing
130 it as a keyword argument to the constructor. Policy objects are immutable,
131 but a new Policy object can be created with only certain values changed by
132 calling the Policy instance with keyword arguments. Policy objects can
133 also be added, producing a new Policy object in which the non-default
134 attributes set in the right hand operand overwrite those specified in the
135 left operand.
136
137 Settable attributes:
138
139 raise_on_defect -- If true, then defects should be raised as errors.
140 Default: False.
141
142 linesep -- string containing the value to use as separation
143 between output lines. Default '\n'.
144
145 cte_type -- Type of allowed content transfer encodings
146
147 7bit -- ASCII only
148 8bit -- Content-Transfer-Encoding: 8bit is allowed
149
150 Default: 8bit. Also controls the disposition of
151 (RFC invalid) binary data in headers; see the
152 documentation of the binary_fold method.
153
154 max_line_length -- maximum length of lines, excluding 'linesep',
155 during serialization. None or 0 means no line
156 wrapping is done. Default is 78.
157
158 """
159
160 raise_on_defect = False
161 linesep = '\n'
162 cte_type = '8bit'
163 max_line_length = 78
164
165 def handle_defect(self, obj, defect):
166 """Based on policy, either raise defect or call register_defect.
167
168 handle_defect(obj, defect)
169
170 defect should be a Defect subclass, but in any case must be an
171 Exception subclass. obj is the object on which the defect should be
172 registered if it is not raised. If the raise_on_defect is True, the
173 defect is raised as an error, otherwise the object and the defect are
174 passed to register_defect.
175
176 This method is intended to be called by parsers that discover defects.
177 The email package parsers always call it with Defect instances.
178
179 """
180 if self.raise_on_defect:
181 raise defect
182 self.register_defect(obj, defect)
183
184 def register_defect(self, obj, defect):
185 """Record 'defect' on 'obj'.
186
187 Called by handle_defect if raise_on_defect is False. This method is
188 part of the Policy API so that Policy subclasses can implement custom
189 defect handling. The default implementation calls the append method of
190 the defects attribute of obj. The objects used by the email package by
191 default that get passed to this method will always have a defects
192 attribute with an append method.
193
194 """
195 obj.defects.append(defect)
196
R David Murrayabfc3742012-05-29 09:14:44 -0400197 def header_max_count(self, name):
198 """Return the maximum allowed number of headers named 'name'.
199
200 Called when a header is added to a Message object. If the returned
201 value is not 0 or None, and there are already a number of headers with
202 the name 'name' equal to the value returned, a ValueError is raised.
203
204 Because the default behavior of Message's __setitem__ is to append the
205 value to the list of headers, it is easy to create duplicate headers
206 without realizing it. This method allows certain headers to be limited
207 in the number of instances of that header that may be added to a
208 Message programmatically. (The limit is not observed by the parser,
209 which will faithfully produce as many headers as exist in the message
210 being parsed.)
211
212 The default implementation returns None for all header names.
213 """
214 return None
215
R David Murrayc27e5222012-05-25 15:01:48 -0400216 @abc.abstractmethod
217 def header_source_parse(self, sourcelines):
218 """Given a list of linesep terminated strings constituting the lines of
219 a single header, return the (name, value) tuple that should be stored
220 in the model. The input lines should retain their terminating linesep
221 characters. The lines passed in by the email package may contain
222 surrogateescaped binary data.
223 """
224 raise NotImplementedError
225
226 @abc.abstractmethod
227 def header_store_parse(self, name, value):
228 """Given the header name and the value provided by the application
229 program, return the (name, value) that should be stored in the model.
230 """
231 raise NotImplementedError
232
233 @abc.abstractmethod
234 def header_fetch_parse(self, name, value):
235 """Given the header name and the value from the model, return the value
236 to be returned to the application program that is requesting that
237 header. The value passed in by the email package may contain
238 surrogateescaped binary data if the lines were parsed by a BytesParser.
239 The returned value should not contain any surrogateescaped data.
240
241 """
242 raise NotImplementedError
243
244 @abc.abstractmethod
245 def fold(self, name, value):
246 """Given the header name and the value from the model, return a string
247 containing linesep characters that implement the folding of the header
248 according to the policy controls. The value passed in by the email
249 package may contain surrogateescaped binary data if the lines were
250 parsed by a BytesParser. The returned value should not contain any
251 surrogateescaped data.
252
253 """
254 raise NotImplementedError
255
256 @abc.abstractmethod
257 def fold_binary(self, name, value):
258 """Given the header name and the value from the model, return binary
259 data containing linesep characters that implement the folding of the
260 header according to the policy controls. The value passed in by the
261 email package may contain surrogateescaped binary data.
262
263 """
264 raise NotImplementedError
265
266
267class Compat32(Policy):
268
269 """+
270 This particular policy is the backward compatibility Policy. It
271 replicates the behavior of the email package version 5.1.
272 """
273
274 def _sanitize_header(self, name, value):
275 # If the header value contains surrogates, return a Header using
276 # the unknown-8bit charset to encode the bytes as encoded words.
277 if not isinstance(value, str):
278 # Assume it is already a header object
279 return value
280 if _has_surrogates(value):
281 return header.Header(value, charset=_charset.UNKNOWN8BIT,
282 header_name=name)
283 else:
284 return value
285
286 def header_source_parse(self, sourcelines):
287 """+
288 The name is parsed as everything up to the ':' and returned unmodified.
289 The value is determined by stripping leading whitespace off the
290 remainder of the first line, joining all subsequent lines together, and
291 stripping any trailing carriage return or linefeed characters.
292
293 """
294 name, value = sourcelines[0].split(':', 1)
295 value = value.lstrip(' \t') + ''.join(sourcelines[1:])
296 return (name, value.rstrip('\r\n'))
297
298 def header_store_parse(self, name, value):
299 """+
300 The name and value are returned unmodified.
301 """
302 return (name, value)
303
304 def header_fetch_parse(self, name, value):
305 """+
306 If the value contains binary data, it is converted into a Header object
307 using the unknown-8bit charset. Otherwise it is returned unmodified.
308 """
309 return self._sanitize_header(name, value)
310
311 def fold(self, name, value):
312 """+
313 Headers are folded using the Header folding algorithm, which preserves
314 existing line breaks in the value, and wraps each resulting line to the
315 max_line_length. Non-ASCII binary data are CTE encoded using the
316 unknown-8bit charset.
317
318 """
319 return self._fold(name, value, sanitize=True)
320
321 def fold_binary(self, name, value):
322 """+
323 Headers are folded using the Header folding algorithm, which preserves
324 existing line breaks in the value, and wraps each resulting line to the
325 max_line_length. If cte_type is 7bit, non-ascii binary data is CTE
326 encoded using the unknown-8bit charset. Otherwise the original source
327 header is used, with its existing line breaks and/or binary data.
328
329 """
330 folded = self._fold(name, value, sanitize=self.cte_type=='7bit')
331 return folded.encode('ascii', 'surrogateescape')
332
333 def _fold(self, name, value, sanitize):
334 parts = []
335 parts.append('%s: ' % name)
336 if isinstance(value, str):
337 if _has_surrogates(value):
338 if sanitize:
339 h = header.Header(value,
340 charset=_charset.UNKNOWN8BIT,
341 header_name=name)
342 else:
343 # If we have raw 8bit data in a byte string, we have no idea
344 # what the encoding is. There is no safe way to split this
345 # string. If it's ascii-subset, then we could do a normal
346 # ascii split, but if it's multibyte then we could break the
347 # string. There's no way to know so the least harm seems to
348 # be to not split the string and risk it being too long.
349 parts.append(value)
350 h = None
351 else:
352 h = header.Header(value, header_name=name)
353 else:
354 # Assume it is a Header-like object.
355 h = value
356 if h is not None:
357 parts.append(h.encode(linesep=self.linesep,
358 maxlinelen=self.max_line_length))
359 parts.append(self.linesep)
360 return ''.join(parts)
361
362
363compat32 = Compat32()