_policybase.py 15 KB

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