Debian Codegraph @

lib-python/3/email/_header_value_parser.py

raw symbols SCIP
1 """Header value parser implementing various email-related RFC parsing rules.
2
3 The parsing methods defined in this module implement various email related
4 parsing rules. Principal among them is RFC 5322, which is the followon
5 to RFC 2822 and primarily a clarification of the former. It also implements
6 RFC 2047 encoded word decoding.
7
8 RFC 5322 goes to considerable trouble to maintain backward compatibility with
9 RFC 822 in the parse phase, while cleaning up the structure on the generation
10 phase. This parser supports correct RFC 5322 generation by tagging white space
11 as folding white space only when folding is allowed in the non-obsolete rule
12 sets. Actually, the parser is even more generous when accepting input than RFC
13 5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages.
14 Where possible deviations from the standard are annotated on the 'defects'
15 attribute of tokens that deviate.
16
17 The general structure of the parser follows RFC 5322, and uses its terminology
18 where there is a direct correspondence. Where the implementation requires a
19 somewhat different structure than that used by the formal grammar, new terms
20 that mimic the closest existing terms are used. Thus, it really helps to have
21 a copy of RFC 5322 handy when studying this code.
22
23 Input to the parser is a string that has already been unfolded according to
24 RFC 5322 rules. According to the RFC this unfolding is the very first step, and
25 this parser leaves the unfolding step to a higher level message parser, which
26 will have already detected the line breaks that need unfolding while
27 determining the beginning and end of each header.
28
29 The output of the parser is a TokenList object, which is a list subclass. A
30 TokenList is a recursive data structure. The terminal nodes of the structure
31 are Terminal objects, which are subclasses of str. These do not correspond
32 directly to terminal objects in the formal grammar, but are instead more
33 practical higher level combinations of true terminals.
34
35 All TokenList and Terminal objects have a 'value' attribute, which produces the
36 semantically meaningful value of that part of the parse subtree. The value of
37 all whitespace tokens (no matter how many sub-tokens they may contain) is a
38 single space, as per the RFC rules. This includes 'CFWS', which is herein
39 included in the general class of whitespace tokens. There is one exception to
40 the rule that whitespace tokens are collapsed into single spaces in values: in
41 the value of a 'bare-quoted-string' (a quoted-string with no leading or
42 trailing whitespace), any whitespace that appeared between the quotation marks
43 is preserved in the returned value. Note that in all Terminal strings quoted
44 pairs are turned into their unquoted values.
45
46 All TokenList and Terminal objects also have a string value, which attempts to
47 be a "canonical" representation of the RFC-compliant form of the substring that
48 produced the parsed subtree, including minimal use of quoted pair quoting.
49 Whitespace runs are not collapsed.
50
51 Comment tokens also have a 'content' attribute providing the string found
52 between the parens (including any nested comments) with whitespace preserved.
53
54 All TokenList and Terminal objects have a 'defects' attribute which is a
55 possibly empty list all of the defects found while creating the token. Defects
56 may appear on any token in the tree, and a composite list of all defects in the
57 subtree is available through the 'all_defects' attribute of any node. (For
58 Terminal notes x.defects == x.all_defects.)
59
60 Each object in a parse tree is called a 'token', and each has a 'token_type'
61 attribute that gives the name from the RFC 5322 grammar that it represents.
62 Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that
63 may be produced: 'ptext'. A 'ptext' is a string of printable ascii characters.
64 It is returned in place of lists of (ctext/quoted-pair) and
65 (qtext/quoted-pair).
66
67 XXX: provide complete list of token types.
68 """
69
70 import re
71 import sys
72 import urllib # For urllib.parse.unquote
73 from string import hexdigits
74 from operator import itemgetter
75 from email import _encoded_words as _ew
76 from email import errors
77 from email import utils
78
79 #
80 # Useful constants and functions
81 #
82
83 WSP = set(' \t')
84 CFWS_LEADER = WSP | set('(')
85 SPECIALS = set(r'()<>@,:;.\"[]')
86 ATOM_ENDS = SPECIALS | WSP
87 DOT_ATOM_ENDS = ATOM_ENDS - set('.')
88 # '.', '"', and '(' do not end phrases in order to support obs-phrase
89 PHRASE_ENDS = SPECIALS - set('."(')
90 TSPECIALS = (SPECIALS | set('/?=')) - set('.')
91 TOKEN_ENDS = TSPECIALS | WSP
92 ASPECIALS = TSPECIALS | set("*'%")
93 ATTRIBUTE_ENDS = ASPECIALS | WSP
94 EXTENDED_ATTRIBUTE_ENDS = ATTRIBUTE_ENDS - set('%')
95 NLSET = {'\n', '\r'}
96 SPECIALSNL = SPECIALS | NLSET
97
98
99 def make_quoted_pairs(value):
100 """Escape dquote and backslash for use within a quoted-string."""
101 return str(value).replace('\\', '\\\\').replace('"', '\\"')
102
103
104 def make_parenthesis_pairs(value):
105 """Escape parenthesis and backslash for use within a comment."""
106 return str(value).replace('\\', '\\\\') \
107 .replace('(', '\\(').replace(')', '\\)')
108
109
110 def quote_string(value):
111 escaped = make_quoted_pairs(value)
112 return f'"{escaped}"'
113
114
115 # Match a RFC 2047 word, looks like =?utf-8?q?someword?=
116 rfc2047_matcher = re.compile(r'''
117 =\? # literal =?
118 [^?]* # charset
119 \? # literal ?
120 [qQbB] # literal 'q' or 'b', case insensitive
121 \? # literal ?
122 .*? # encoded word
123 \?= # literal ?=
124 ''', re.VERBOSE | re.MULTILINE)
125
126
127 #
128 # TokenList and its subclasses
129 #
130
131 class TokenList(list):
132
133 token_type = None
134 syntactic_break = True
135 ew_combine_allowed = True
136
137 def __init__(self, *args, **kw):
138 super().__init__(*args, **kw)
139 self.defects = []
140
141 def __str__(self):
142 return ''.join(str(x) for x in self)
143
144 def __repr__(self):
145 return '{}({})'.format(self.__class__.__name__,
146 super().__repr__())
147
148 @property
149 def value(self):
150 return ''.join(x.value for x in self if x.value)
151
152 @property
153 def all_defects(self):
154 return sum((x.all_defects for x in self), self.defects)
155
156 def startswith_fws(self):
157 return self[0].startswith_fws()
158
159 @property
160 def as_ew_allowed(self):
161 """True if all top level tokens of this part may be RFC2047 encoded."""
162 return all(part.as_ew_allowed for part in self)
163
164 @property
165 def comments(self):
166 comments = []
167 for token in self:
168 comments.extend(token.comments)
169 return comments
170
171 def fold(self, *, policy):
172 return _refold_parse_tree(self, policy=policy)
173
174 def pprint(self, indent=''):
175 print(self.ppstr(indent=indent))
176
177 def ppstr(self, indent=''):
178 return '\n'.join(self._pp(indent=indent))
179
180 def _pp(self, indent=''):
181 yield '{}{}/{}('.format(
182 indent,
183 self.__class__.__name__,
184 self.token_type)
185 for token in self:
186 if not hasattr(token, '_pp'):
187 yield (indent + ' !! invalid element in token '
188 'list: {!r}'.format(token))
189 else:
190 yield from token._pp(indent+' ')
191 if self.defects:
192 extra = ' Defects: {}'.format(self.defects)
193 else:
194 extra = ''
195 yield '{}){}'.format(indent, extra)
196
197
198 class WhiteSpaceTokenList(TokenList):
199
200 @property
201 def value(self):
202 return ' '
203
204 @property
205 def comments(self):
206 return [x.content for x in self if x.token_type=='comment']
207
208
209 class UnstructuredTokenList(TokenList):
210 token_type = 'unstructured'
211
212
213 class Phrase(TokenList):
214 token_type = 'phrase'
215
216 class Word(TokenList):
217 token_type = 'word'
218
219
220 class CFWSList(WhiteSpaceTokenList):
221 token_type = 'cfws'
222
223
224 class Atom(TokenList):
225 token_type = 'atom'
226
227
228 class Token(TokenList):
229 token_type = 'token'
230 encode_as_ew = False
231
232
233 class EncodedWord(TokenList):
234 token_type = 'encoded-word'
235 cte = None
236 charset = None
237 lang = None
238
239
240 class QuotedString(TokenList):
241
242 token_type = 'quoted-string'
243
244 @property
245 def content(self):
246 for x in self:
247 if x.token_type == 'bare-quoted-string':
248 return x.value
249
250 @property
251 def quoted_value(self):
252 res = []
253 for x in self:
254 if x.token_type == 'bare-quoted-string':
255 res.append(str(x))
256 else:
257 res.append(x.value)
258 return ''.join(res)
259
260 @property
261 def stripped_value(self):
262 for token in self:
263 if token.token_type == 'bare-quoted-string':
264 return token.value
265
266
267 class BareQuotedString(QuotedString):
268
269 token_type = 'bare-quoted-string'
270
271 def __str__(self):
272 return quote_string(''.join(str(x) for x in self))
273
274 @property
275 def value(self):
276 return ''.join(str(x) for x in self)
277
278
279 class Comment(WhiteSpaceTokenList):
280
281 token_type = 'comment'
282
283 def __str__(self):
284 return ''.join(sum([
285 ["("],
286 [self.quote(x) for x in self],
287 [")"],
288 ], []))
289
290 def quote(self, value):
291 if value.token_type == 'comment':
292 return str(value)
293 return str(value).replace('\\', '\\\\').replace(
294 '(', r'\(').replace(
295 ')', r'\)')
296
297 @property
298 def content(self):
299 return ''.join(str(x) for x in self)
300
301 @property
302 def comments(self):
303 return [self.content]
304
305 class AddressList(TokenList):
306
307 token_type = 'address-list'
308
309 @property
310 def addresses(self):
311 return [x for x in self if x.token_type=='address']
312
313 @property
314 def mailboxes(self):
315 return sum((x.mailboxes
316 for x in self if x.token_type=='address'), [])
317
318 @property
319 def all_mailboxes(self):
320 return sum((x.all_mailboxes
321 for x in self if x.token_type=='address'), [])
322
323
324 class Address(TokenList):
325
326 token_type = 'address'
327
328 @property
329 def display_name(self):
330 if self[0].token_type == 'group':
331 return self[0].display_name
332
333 @property
334 def mailboxes(self):
335 if self[0].token_type == 'mailbox':
336 return [self[0]]
337 elif self[0].token_type == 'invalid-mailbox':
338 return []
339 return self[0].mailboxes
340
341 @property
342 def all_mailboxes(self):
343 if self[0].token_type == 'mailbox':
344 return [self[0]]
345 elif self[0].token_type == 'invalid-mailbox':
346 return [self[0]]
347 return self[0].all_mailboxes
348
349 class MailboxList(TokenList):
350
351 token_type = 'mailbox-list'
352
353 @property
354 def mailboxes(self):
355 return [x for x in self if x.token_type=='mailbox']
356
357 @property
358 def all_mailboxes(self):
359 return [x for x in self
360 if x.token_type in ('mailbox', 'invalid-mailbox')]
361
362
363 class GroupList(TokenList):
364
365 token_type = 'group-list'
366
367 @property
368 def mailboxes(self):
369 if not self or self[0].token_type != 'mailbox-list':
370 return []
371 return self[0].mailboxes
372
373 @property
374 def all_mailboxes(self):
375 if not self or self[0].token_type != 'mailbox-list':
376 return []
377 return self[0].all_mailboxes
378
379
380 class Group(TokenList):
381
382 token_type = "group"
383
384 @property
385 def mailboxes(self):
386 if self[2].token_type != 'group-list':
387 return []
388 return self[2].mailboxes
389
390 @property
391 def all_mailboxes(self):
392 if self[2].token_type != 'group-list':
393 return []
394 return self[2].all_mailboxes
395
396 @property
397 def display_name(self):
398 return self[0].display_name
399
400
401 class NameAddr(TokenList):
402
403 token_type = 'name-addr'
404
405 @property
406 def display_name(self):
407 if len(self) == 1:
408 return None
409 return self[0].display_name
410
411 @property
412 def local_part(self):
413 return self[-1].local_part
414
415 @property
416 def domain(self):
417 return self[-1].domain
418
419 @property
420 def route(self):
421 return self[-1].route
422
423 @property
424 def addr_spec(self):
425 return self[-1].addr_spec
426
427
428 class AngleAddr(TokenList):
429
430 token_type = 'angle-addr'
431
432 @property
433 def local_part(self):
434 for x in self:
435 if x.token_type == 'addr-spec':
436 return x.local_part
437
438 @property
439 def domain(self):
440 for x in self:
441 if x.token_type == 'addr-spec':
442 return x.domain
443
444 @property
445 def route(self):
446 for x in self:
447 if x.token_type == 'obs-route':
448 return x.domains
449
450 @property
451 def addr_spec(self):
452 for x in self:
453 if x.token_type == 'addr-spec':
454 if x.local_part:
455 return x.addr_spec
456 else:
457 return quote_string(x.local_part) + x.addr_spec
458 else:
459 return '<>'
460
461
462 class ObsRoute(TokenList):
463
464 token_type = 'obs-route'
465
466 @property
467 def domains(self):
468 return [x.domain for x in self if x.token_type == 'domain']
469
470
471 class Mailbox(TokenList):
472
473 token_type = 'mailbox'
474
475 @property
476 def display_name(self):
477 if self[0].token_type == 'name-addr':
478 return self[0].display_name
479
480 @property
481 def local_part(self):
482 return self[0].local_part
483
484 @property
485 def domain(self):
486 return self[0].domain
487
488 @property
489 def route(self):
490 if self[0].token_type == 'name-addr':
491 return self[0].route
492
493 @property
494 def addr_spec(self):
495 return self[0].addr_spec
496
497
498 class InvalidMailbox(TokenList):
499
500 token_type = 'invalid-mailbox'
501
502 @property
503 def display_name(self):
504 return None
505
506 local_part = domain = route = addr_spec = display_name
507
508
509 class Domain(TokenList):
510
511 token_type = 'domain'
512 as_ew_allowed = False
513
514 @property
515 def domain(self):
516 return ''.join(super().value.split())
517
518
519 class DotAtom(TokenList):
520 token_type = 'dot-atom'
521
522
523 class DotAtomText(TokenList):
524 token_type = 'dot-atom-text'
525 as_ew_allowed = True
526
527
528 class NoFoldLiteral(TokenList):
529 token_type = 'no-fold-literal'
530 as_ew_allowed = False
531
532
533 class AddrSpec(TokenList):
534
535 token_type = 'addr-spec'
536 as_ew_allowed = False
537
538 @property
539 def local_part(self):
540 return self[0].local_part
541
542 @property
543 def domain(self):
544 if len(self) < 3:
545 return None
546 return self[-1].domain
547
548 @property
549 def value(self):
550 if len(self) < 3:
551 return self[0].value
552 return self[0].value.rstrip()+self[1].value+self[2].value.lstrip()
553
554 @property
555 def addr_spec(self):
556 nameset = set(self.local_part)
557 if len(nameset) > len(nameset-DOT_ATOM_ENDS):
558 lp = quote_string(self.local_part)
559 else:
560 lp = self.local_part
561 if self.domain is not None:
562 return lp + '@' + self.domain
563 return lp
564
565
566 class ObsLocalPart(TokenList):
567
568 token_type = 'obs-local-part'
569 as_ew_allowed = False
570
571
572 class DisplayName(Phrase):
573
574 token_type = 'display-name'
575 ew_combine_allowed = False
576
577 @property
578 def display_name(self):
579 res = TokenList(self)
580 if len(res) == 0:
581 return res.value
582 if res[0].token_type == 'cfws':
583 res.pop(0)
584 else:
585 if res[0][0].token_type == 'cfws':
586 res[0] = TokenList(res[0][1:])
587 if res[-1].token_type == 'cfws':
588 res.pop()
589 else:
590 if res[-1][-1].token_type == 'cfws':
591 res[-1] = TokenList(res[-1][:-1])
592 return res.value
593
594 @property
595 def value(self):
596 quote = False
597 if self.defects:
598 quote = True
599 else:
600 for x in self:
601 if x.token_type == 'quoted-string':
602 quote = True
603 if len(self) != 0 and quote:
604 pre = post = ''
605 if self[0].token_type=='cfws' or self[0][0].token_type=='cfws':
606 pre = ' '
607 if self[-1].token_type=='cfws' or self[-1][-1].token_type=='cfws':
608 post = ' '
609 return pre+quote_string(self.display_name)+post
610 else:
611 return super().value
612
613
614 class LocalPart(TokenList):
615
616 token_type = 'local-part'
617 as_ew_allowed = False
618
619 @property
620 def value(self):
621 if self[0].token_type == "quoted-string":
622 return self[0].quoted_value
623 else:
624 return self[0].value
625
626 @property
627 def local_part(self):
628 # Strip whitespace from front, back, and around dots.
629 res = [DOT]
630 last = DOT
631 last_is_tl = False
632 for tok in self[0] + [DOT]:
633 if tok.token_type == 'cfws':
634 continue
635 if (last_is_tl and tok.token_type == 'dot' and
636 last[-1].token_type == 'cfws'):
637 res[-1] = TokenList(last[:-1])
638 is_tl = isinstance(tok, TokenList)
639 if (is_tl and last.token_type == 'dot' and
640 tok[0].token_type == 'cfws'):
641 res.append(TokenList(tok[1:]))
642 else:
643 res.append(tok)
644 last = res[-1]
645 last_is_tl = is_tl
646 res = TokenList(res[1:-1])
647 return res.value
648
649
650 class DomainLiteral(TokenList):
651
652 token_type = 'domain-literal'
653 as_ew_allowed = False
654
655 @property
656 def domain(self):
657 return ''.join(super().value.split())
658
659 @property
660 def ip(self):
661 for x in self:
662 if x.token_type == 'ptext':
663 return x.value
664
665
666 class MIMEVersion(TokenList):
667
668 token_type = 'mime-version'
669 major = None
670 minor = None
671
672
673 class Parameter(TokenList):
674
675 token_type = 'parameter'
676 sectioned = False
677 extended = False
678 charset = 'us-ascii'
679
680 @property
681 def section_number(self):
682 # Because the first token, the attribute (name) eats CFWS, the second
683 # token is always the section if there is one.
684 return self[1].number if self.sectioned else 0
685
686 @property
687 def param_value(self):
688 # This is part of the "handle quoted extended parameters" hack.
689 for token in self:
690 if token.token_type == 'value':
691 return token.stripped_value
692 if token.token_type == 'quoted-string':
693 for token in token:
694 if token.token_type == 'bare-quoted-string':
695 for token in token:
696 if token.token_type == 'value':
697 return token.stripped_value
698 return ''
699
700
701 class InvalidParameter(Parameter):
702
703 token_type = 'invalid-parameter'
704
705
706 class Attribute(TokenList):
707
708 token_type = 'attribute'
709
710 @property
711 def stripped_value(self):
712 for token in self:
713 if token.token_type.endswith('attrtext'):
714 return token.value
715
716 class Section(TokenList):
717
718 token_type = 'section'
719 number = None
720
721
722 class Value(TokenList):
723
724 token_type = 'value'
725
726 @property
727 def stripped_value(self):
728 token = self[0]
729 if token.token_type == 'cfws':
730 token = self[1]
731 if token.token_type.endswith(
732 ('quoted-string', 'attribute', 'extended-attribute')):
733 return token.stripped_value
734 return self.value
735
736
737 class MimeParameters(TokenList):
738
739 token_type = 'mime-parameters'
740 syntactic_break = False
741
742 @property
743 def params(self):
744 # The RFC specifically states that the ordering of parameters is not
745 # guaranteed and may be reordered by the transport layer. So we have
746 # to assume the RFC 2231 pieces can come in any order. However, we
747 # output them in the order that we first see a given name, which gives
748 # us a stable __str__.
749 params = {} # Using order preserving dict from Python 3.7+
750 for token in self:
751 if not token.token_type.endswith('parameter'):
752 continue
753 if token[0].token_type != 'attribute':
754 continue
755 name = token[0].value.strip()
756 if name not in params:
757 params[name] = []
758 params[name].append((token.section_number, token))
759 for name, parts in params.items():
760 parts = sorted(parts, key=itemgetter(0))
761 first_param = parts[0][1]
762 charset = first_param.charset
763 # Our arbitrary error recovery is to ignore duplicate parameters,
764 # to use appearance order if there are duplicate rfc 2231 parts,
765 # and to ignore gaps. This mimics the error recovery of get_param.
766 if not first_param.extended and len(parts) > 1:
767 if parts[1][0] == 0:
768 parts[1][1].defects.append(errors.InvalidHeaderDefect(
769 'duplicate parameter name; duplicate(s) ignored'))
770 parts = parts[:1]
771 # Else assume the *0* was missing...note that this is different
772 # from get_param, but we registered a defect for this earlier.
773 value_parts = []
774 i = 0
775 for section_number, param in parts:
776 if section_number != i:
777 # We could get fancier here and look for a complete
778 # duplicate extended parameter and ignore the second one
779 # seen. But we're not doing that. The old code didn't.
780 if not param.extended:
781 param.defects.append(errors.InvalidHeaderDefect(
782 'duplicate parameter name; duplicate ignored'))
783 continue
784 else:
785 param.defects.append(errors.InvalidHeaderDefect(
786 "inconsistent RFC2231 parameter numbering"))
787 i += 1
788 value = param.param_value
789 if param.extended:
790 try:
791 value = urllib.parse.unquote_to_bytes(value)
792 except UnicodeEncodeError:
793 # source had surrogate escaped bytes. What we do now
794 # is a bit of an open question. I'm not sure this is
795 # the best choice, but it is what the old algorithm did
796 value = urllib.parse.unquote(value, encoding='latin-1')
797 else:
798 try:
799 value = value.decode(charset, 'surrogateescape')
800 except (LookupError, UnicodeEncodeError):
801 # XXX: there should really be a custom defect for
802 # unknown character set to make it easy to find,
803 # because otherwise unknown charset is a silent
804 # failure.
805 value = value.decode('us-ascii', 'surrogateescape')
806 if utils._has_surrogates(value):
807 param.defects.append(errors.UndecodableBytesDefect())
808 value_parts.append(value)
809 value = ''.join(value_parts)
810 yield name, value
811
812 def __str__(self):
813 params = []
814 for name, value in self.params:
815 if value:
816 params.append('{}={}'.format(name, quote_string(value)))
817 else:
818 params.append(name)
819 params = '; '.join(params)
820 return ' ' + params if params else ''
821
822
823 class ParameterizedHeaderValue(TokenList):
824
825 # Set this false so that the value doesn't wind up on a new line even
826 # if it and the parameters would fit there but not on the first line.
827 syntactic_break = False
828
829 @property
830 def params(self):
831 for token in reversed(self):
832 if token.token_type == 'mime-parameters':
833 return token.params
834 return {}
835
836
837 class ContentType(ParameterizedHeaderValue):
838 token_type = 'content-type'
839 as_ew_allowed = False
840 maintype = 'text'
841 subtype = 'plain'
842
843
844 class ContentDisposition(ParameterizedHeaderValue):
845 token_type = 'content-disposition'
846 as_ew_allowed = False
847 content_disposition = None
848
849
850 class ContentTransferEncoding(TokenList):
851 token_type = 'content-transfer-encoding'
852 as_ew_allowed = False
853 cte = '7bit'
854
855
856 class HeaderLabel(TokenList):
857 token_type = 'header-label'
858 as_ew_allowed = False
859
860
861 class MsgID(TokenList):
862 token_type = 'msg-id'
863 as_ew_allowed = False
864
865 def fold(self, policy):
866 # message-id tokens may not be folded.
867 return str(self) + policy.linesep
868
869
870 class MessageID(MsgID):
871 token_type = 'message-id'
872
873
874 class InvalidMessageID(MessageID):
875 token_type = 'invalid-message-id'
876
877
878 class Header(TokenList):
879 token_type = 'header'
880
881
882 #
883 # Terminal classes and instances
884 #
885
886 class Terminal(str):
887
888 as_ew_allowed = True
889 ew_combine_allowed = True
890 syntactic_break = True
891
892 def __new__(cls, value, token_type):
893 self = super().__new__(cls, value)
894 self.token_type = token_type
895 self.defects = []
896 return self
897
898 def __repr__(self):
899 return "{}({})".format(self.__class__.__name__, super().__repr__())
900
901 def pprint(self):
902 print(self.__class__.__name__ + '/' + self.token_type)
903
904 @property
905 def all_defects(self):
906 return list(self.defects)
907
908 def _pp(self, indent=''):
909 return ["{}{}/{}({}){}".format(
910 indent,
911 self.__class__.__name__,
912 self.token_type,
913 super().__repr__(),
914 '' if not self.defects else ' {}'.format(self.defects),
915 )]
916
917 def pop_trailing_ws(self):
918 # This terminates the recursion.
919 return None
920
921 @property
922 def comments(self):
923 return []
924
925 def __getnewargs__(self):
926 return(str(self), self.token_type)
927
928
929 class WhiteSpaceTerminal(Terminal):
930
931 @property
932 def value(self):
933 return ' '
934
935 def startswith_fws(self):
936 return self and self[0] in WSP
937
938
939 class ValueTerminal(Terminal):
940
941 @property
942 def value(self):
943 return self
944
945 def startswith_fws(self):
946 return False
947
948
949 class EWWhiteSpaceTerminal(WhiteSpaceTerminal):
950
951 @property
952 def value(self):
953 return ''
954
955 def __str__(self):
956 return ''
957
958
959 class _InvalidEwError(errors.HeaderParseError):
960 """Invalid encoded word found while parsing headers."""
961
962
963 # XXX these need to become classes and used as instances so
964 # that a program can't change them in a parse tree and screw
965 # up other parse trees. Maybe should have tests for that, too.
966 DOT = ValueTerminal('.', 'dot')
967 ListSeparator = ValueTerminal(',', 'list-separator')
968 ListSeparator.as_ew_allowed = False
969 ListSeparator.syntactic_break = False
970 RouteComponentMarker = ValueTerminal('@', 'route-component-marker')
971
972 #
973 # Parser
974 #
975
976 # Parse strings according to RFC822/2047/2822/5322 rules.
977 #
978 # This is a stateless parser. Each get_XXX function accepts a string and
979 # returns either a Terminal or a TokenList representing the RFC object named
980 # by the method and a string containing the remaining unparsed characters
981 # from the input. Thus a parser method consumes the next syntactic construct
982 # of a given type and returns a token representing the construct plus the
983 # unparsed remainder of the input string.
984 #
985 # For example, if the first element of a structured header is a 'phrase',
986 # then:
987 #
988 # phrase, value = get_phrase(value)
989 #
990 # returns the complete phrase from the start of the string value, plus any
991 # characters left in the string after the phrase is removed.
992
993 _wsp_splitter = re.compile(r'([{}]+)'.format(''.join(WSP))).split
994 _non_atom_end_matcher = re.compile(r"[^{}]+".format(
995 re.escape(''.join(ATOM_ENDS)))).match
996 _non_printable_finder = re.compile(r"[\x00-\x20\x7F]").findall
997 _non_token_end_matcher = re.compile(r"[^{}]+".format(
998 re.escape(''.join(TOKEN_ENDS)))).match
999 _non_attribute_end_matcher = re.compile(r"[^{}]+".format(
1000 re.escape(''.join(ATTRIBUTE_ENDS)))).match
1001 _non_extended_attribute_end_matcher = re.compile(r"[^{}]+".format(
1002 re.escape(''.join(EXTENDED_ATTRIBUTE_ENDS)))).match
1003
1004 def _validate_xtext(xtext):
1005 """If input token contains ASCII non-printables, register a defect."""
1006
1007 non_printables = _non_printable_finder(xtext)
1008 if non_printables:
1009 xtext.defects.append(errors.NonPrintableDefect(non_printables))
1010 if utils._has_surrogates(xtext):
1011 xtext.defects.append(errors.UndecodableBytesDefect(
1012 "Non-ASCII characters found in header token"))
1013
1014 def _get_ptext_to_endchars(value, endchars):
1015 """Scan printables/quoted-pairs until endchars and return unquoted ptext.
1016
1017 This function turns a run of qcontent, ccontent-without-comments, or
1018 dtext-with-quoted-printables into a single string by unquoting any
1019 quoted printables. It returns the string, the remaining value, and
1020 a flag that is True iff there were any quoted printables decoded.
1021
1022 """
1023 fragment, *remainder = _wsp_splitter(value, 1)
1024 vchars = []
1025 escape = False
1026 had_qp = False
1027 for pos in range(len(fragment)):
1028 if fragment[pos] == '\\':
1029 if escape:
1030 escape = False
1031 had_qp = True
1032 else:
1033 escape = True
1034 continue
1035 if escape:
1036 escape = False
1037 elif fragment[pos] in endchars:
1038 break
1039 vchars.append(fragment[pos])
1040 else:
1041 pos = pos + 1
1042 return ''.join(vchars), ''.join([fragment[pos:]] + remainder), had_qp
1043
1044 def get_fws(value):
1045 """FWS = 1*WSP
1046
1047 This isn't the RFC definition. We're using fws to represent tokens where
1048 folding can be done, but when we are parsing the *un*folding has already
1049 been done so we don't need to watch out for CRLF.
1050
1051 """
1052 newvalue = value.lstrip()
1053 fws = WhiteSpaceTerminal(value[:len(value)-len(newvalue)], 'fws')
1054 return fws, newvalue
1055
1056 def get_encoded_word(value, terminal_type='vtext'):
1057 """ encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
1058
1059 """
1060 ew = EncodedWord()
1061 if not value.startswith('=?'):
1062 raise errors.HeaderParseError(
1063 "expected encoded word but found {}".format(value))
1064 tok, *remainder = value[2:].split('?=', 1)
1065 if tok == value[2:]:
1066 raise errors.HeaderParseError(
1067 "expected encoded word but found {}".format(value))
1068 remstr = ''.join(remainder)
1069 if (len(remstr) > 1 and
1070 remstr[0] in hexdigits and
1071 remstr[1] in hexdigits and
1072 tok.count('?') < 2):
1073 # The ? after the CTE was followed by an encoded word escape (=XX).
1074 rest, *remainder = remstr.split('?=', 1)
1075 tok = tok + '?=' + rest
1076 if len(tok.split()) > 1:
1077 ew.defects.append(errors.InvalidHeaderDefect(
1078 "whitespace inside encoded word"))
1079 ew.cte = value
1080 value = ''.join(remainder)
1081 try:
1082 text, charset, lang, defects = _ew.decode('=?' + tok + '?=')
1083 except (ValueError, KeyError):
1084 raise _InvalidEwError(
1085 "encoded word format invalid: '{}'".format(ew.cte))
1086 ew.charset = charset
1087 ew.lang = lang
1088 ew.defects.extend(defects)
1089 while text:
1090 if text[0] in WSP:
1091 token, text = get_fws(text)
1092 ew.append(token)
1093 continue
1094 chars, *remainder = _wsp_splitter(text, 1)
1095 vtext = ValueTerminal(chars, terminal_type)
1096 _validate_xtext(vtext)
1097 ew.append(vtext)
1098 text = ''.join(remainder)
1099 # Encoded words should be followed by a WS
1100 if value and value[0] not in WSP:
1101 ew.defects.append(errors.InvalidHeaderDefect(
1102 "missing trailing whitespace after encoded-word"))
1103 return ew, value
1104
1105 def get_unstructured(value):
1106 """unstructured = (*([FWS] vchar) *WSP) / obs-unstruct
1107 obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS)
1108 obs-utext = %d0 / obs-NO-WS-CTL / LF / CR
1109
1110 obs-NO-WS-CTL is control characters except WSP/CR/LF.
1111
1112 So, basically, we have printable runs, plus control characters or nulls in
1113 the obsolete syntax, separated by whitespace. Since RFC 2047 uses the
1114 obsolete syntax in its specification, but requires whitespace on either
1115 side of the encoded words, I can see no reason to need to separate the
1116 non-printable-non-whitespace from the printable runs if they occur, so we
1117 parse this into xtext tokens separated by WSP tokens.
1118
1119 Because an 'unstructured' value must by definition constitute the entire
1120 value, this 'get' routine does not return a remaining value, only the
1121 parsed TokenList.
1122
1123 """
1124 # XXX: but what about bare CR and LF? They might signal the start or
1125 # end of an encoded word. YAGNI for now, since our current parsers
1126 # will never send us strings with bare CR or LF.
1127
1128 unstructured = UnstructuredTokenList()
1129 while value:
1130 if value[0] in WSP:
1131 token, value = get_fws(value)
1132 unstructured.append(token)
1133 continue
1134 valid_ew = True
1135 if value.startswith('=?'):
1136 try:
1137 token, value = get_encoded_word(value, 'utext')
1138 except _InvalidEwError:
1139 valid_ew = False
1140 except errors.HeaderParseError:
1141 # XXX: Need to figure out how to register defects when
1142 # appropriate here.
1143 pass
1144 else:
1145 have_ws = True
1146 if len(unstructured) > 0:
1147 if unstructured[-1].token_type != 'fws':
1148 unstructured.defects.append(errors.InvalidHeaderDefect(
1149 "missing whitespace before encoded word"))
1150 have_ws = False
1151 if have_ws and len(unstructured) > 1:
1152 if unstructured[-2].token_type == 'encoded-word':
1153 unstructured[-1] = EWWhiteSpaceTerminal(
1154 unstructured[-1], 'fws')
1155 unstructured.append(token)
1156 continue
1157 tok, *remainder = _wsp_splitter(value, 1)
1158 # Split in the middle of an atom if there is a rfc2047 encoded word
1159 # which does not have WSP on both sides. The defect will be registered
1160 # the next time through the loop.
1161 # This needs to only be performed when the encoded word is valid;
1162 # otherwise, performing it on an invalid encoded word can cause
1163 # the parser to go in an infinite loop.
1164 if valid_ew and rfc2047_matcher.search(tok):
1165 tok, *remainder = value.partition('=?')
1166 vtext = ValueTerminal(tok, 'utext')
1167 _validate_xtext(vtext)
1168 unstructured.append(vtext)
1169 value = ''.join(remainder)
1170 return unstructured
1171
1172 def get_qp_ctext(value):
1173 r"""ctext = <printable ascii except \ ( )>
1174
1175 This is not the RFC ctext, since we are handling nested comments in comment
1176 and unquoting quoted-pairs here. We allow anything except the '()'
1177 characters, but if we find any ASCII other than the RFC defined printable
1178 ASCII, a NonPrintableDefect is added to the token's defects list. Since
1179 quoted pairs are converted to their unquoted values, what is returned is
1180 a 'ptext' token. In this case it is a WhiteSpaceTerminal, so it's value
1181 is ' '.
1182
1183 """
1184 ptext, value, _ = _get_ptext_to_endchars(value, '()')
1185 ptext = WhiteSpaceTerminal(ptext, 'ptext')
1186 _validate_xtext(ptext)
1187 return ptext, value
1188
1189 def get_qcontent(value):
1190 """qcontent = qtext / quoted-pair
1191
1192 We allow anything except the DQUOTE character, but if we find any ASCII
1193 other than the RFC defined printable ASCII, a NonPrintableDefect is
1194 added to the token's defects list. Any quoted pairs are converted to their
1195 unquoted values, so what is returned is a 'ptext' token. In this case it
1196 is a ValueTerminal.
1197
1198 """
1199 ptext, value, _ = _get_ptext_to_endchars(value, '"')
1200 ptext = ValueTerminal(ptext, 'ptext')
1201 _validate_xtext(ptext)
1202 return ptext, value
1203
1204 def get_atext(value):
1205 """atext = <matches _atext_matcher>
1206
1207 We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to
1208 the token's defects list if we find non-atext characters.
1209 """
1210 m = _non_atom_end_matcher(value)
1211 if not m:
1212 raise errors.HeaderParseError(
1213 "expected atext but found '{}'".format(value))
1214 atext = m.group()
1215 value = value[len(atext):]
1216 atext = ValueTerminal(atext, 'atext')
1217 _validate_xtext(atext)
1218 return atext, value
1219
1220 def get_bare_quoted_string(value):
1221 """bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE
1222
1223 A quoted-string without the leading or trailing white space. Its
1224 value is the text between the quote marks, with whitespace
1225 preserved and quoted pairs decoded.
1226 """
1227 if value[0] != '"':
1228 raise errors.HeaderParseError(
1229 "expected '\"' but found '{}'".format(value))
1230 bare_quoted_string = BareQuotedString()
1231 value = value[1:]
1232 if value and value[0] == '"':
1233 token, value = get_qcontent(value)
1234 bare_quoted_string.append(token)
1235 while value and value[0] != '"':
1236 if value[0] in WSP:
1237 token, value = get_fws(value)
1238 elif value[:2] == '=?':
1239 valid_ew = False
1240 try:
1241 token, value = get_encoded_word(value)
1242 bare_quoted_string.defects.append(errors.InvalidHeaderDefect(
1243 "encoded word inside quoted string"))
1244 valid_ew = True
1245 except errors.HeaderParseError:
1246 token, value = get_qcontent(value)
1247 # Collapse the whitespace between two encoded words that occur in a
1248 # bare-quoted-string.
1249 if valid_ew and len(bare_quoted_string) > 1:
1250 if (bare_quoted_string[-1].token_type == 'fws' and
1251 bare_quoted_string[-2].token_type == 'encoded-word'):
1252 bare_quoted_string[-1] = EWWhiteSpaceTerminal(
1253 bare_quoted_string[-1], 'fws')
1254 else:
1255 token, value = get_qcontent(value)
1256 bare_quoted_string.append(token)
1257 if not value:
1258 bare_quoted_string.defects.append(errors.InvalidHeaderDefect(
1259 "end of header inside quoted string"))
1260 return bare_quoted_string, value
1261 return bare_quoted_string, value[1:]
1262
1263 def get_comment(value):
1264 """comment = "(" *([FWS] ccontent) [FWS] ")"
1265 ccontent = ctext / quoted-pair / comment
1266
1267 We handle nested comments here, and quoted-pair in our qp-ctext routine.
1268 """
1269 if value and value[0] != '(':
1270 raise errors.HeaderParseError(
1271 "expected '(' but found '{}'".format(value))
1272 comment = Comment()
1273 value = value[1:]
1274 while value and value[0] != ")":
1275 if value[0] in WSP:
1276 token, value = get_fws(value)
1277 elif value[0] == '(':
1278 token, value = get_comment(value)
1279 else:
1280 token, value = get_qp_ctext(value)
1281 comment.append(token)
1282 if not value:
1283 comment.defects.append(errors.InvalidHeaderDefect(
1284 "end of header inside comment"))
1285 return comment, value
1286 return comment, value[1:]
1287
1288 def get_cfws(value):
1289 """CFWS = (1*([FWS] comment) [FWS]) / FWS
1290
1291 """
1292 cfws = CFWSList()
1293 while value and value[0] in CFWS_LEADER:
1294 if value[0] in WSP:
1295 token, value = get_fws(value)
1296 else:
1297 token, value = get_comment(value)
1298 cfws.append(token)
1299 return cfws, value
1300
1301 def get_quoted_string(value):
1302 """quoted-string = [CFWS] <bare-quoted-string> [CFWS]
1303
1304 'bare-quoted-string' is an intermediate class defined by this
1305 parser and not by the RFC grammar. It is the quoted string
1306 without any attached CFWS.
1307 """
1308 quoted_string = QuotedString()
1309 if value and value[0] in CFWS_LEADER:
1310 token, value = get_cfws(value)
1311 quoted_string.append(token)
1312 token, value = get_bare_quoted_string(value)
1313 quoted_string.append(token)
1314 if value and value[0] in CFWS_LEADER:
1315 token, value = get_cfws(value)
1316 quoted_string.append(token)
1317 return quoted_string, value
1318
1319 def get_atom(value):
1320 """atom = [CFWS] 1*atext [CFWS]
1321
1322 An atom could be an rfc2047 encoded word.
1323 """
1324 atom = Atom()
1325 if value and value[0] in CFWS_LEADER:
1326 token, value = get_cfws(value)
1327 atom.append(token)
1328 if value and value[0] in ATOM_ENDS:
1329 raise errors.HeaderParseError(
1330 "expected atom but found '{}'".format(value))
1331 if value.startswith('=?'):
1332 try:
1333 token, value = get_encoded_word(value)
1334 except errors.HeaderParseError:
1335 # XXX: need to figure out how to register defects when
1336 # appropriate here.
1337 token, value = get_atext(value)
1338 else:
1339 token, value = get_atext(value)
1340 atom.append(token)
1341 if value and value[0] in CFWS_LEADER:
1342 token, value = get_cfws(value)
1343 atom.append(token)
1344 return atom, value
1345
1346 def get_dot_atom_text(value):
1347 """ dot-text = 1*atext *("." 1*atext)
1348
1349 """
1350 dot_atom_text = DotAtomText()
1351 if not value or value[0] in ATOM_ENDS:
1352 raise errors.HeaderParseError("expected atom at a start of "
1353 "dot-atom-text but found '{}'".format(value))
1354 while value and value[0] not in ATOM_ENDS:
1355 token, value = get_atext(value)
1356 dot_atom_text.append(token)
1357 if value and value[0] == '.':
1358 dot_atom_text.append(DOT)
1359 value = value[1:]
1360 if dot_atom_text[-1] is DOT:
1361 raise errors.HeaderParseError("expected atom at end of dot-atom-text "
1362 "but found '{}'".format('.'+value))
1363 return dot_atom_text, value
1364
1365 def get_dot_atom(value):
1366 """ dot-atom = [CFWS] dot-atom-text [CFWS]
1367
1368 Any place we can have a dot atom, we could instead have an rfc2047 encoded
1369 word.
1370 """
1371 dot_atom = DotAtom()
1372 if value[0] in CFWS_LEADER:
1373 token, value = get_cfws(value)
1374 dot_atom.append(token)
1375 if value.startswith('=?'):
1376 try:
1377 token, value = get_encoded_word(value)
1378 except errors.HeaderParseError:
1379 # XXX: need to figure out how to register defects when
1380 # appropriate here.
1381 token, value = get_dot_atom_text(value)
1382 else:
1383 token, value = get_dot_atom_text(value)
1384 dot_atom.append(token)
1385 if value and value[0] in CFWS_LEADER:
1386 token, value = get_cfws(value)
1387 dot_atom.append(token)
1388 return dot_atom, value
1389
1390 def get_word(value):
1391 """word = atom / quoted-string
1392
1393 Either atom or quoted-string may start with CFWS. We have to peel off this
1394 CFWS first to determine which type of word to parse. Afterward we splice
1395 the leading CFWS, if any, into the parsed sub-token.
1396
1397 If neither an atom or a quoted-string is found before the next special, a
1398 HeaderParseError is raised.
1399
1400 The token returned is either an Atom or a QuotedString, as appropriate.
1401 This means the 'word' level of the formal grammar is not represented in the
1402 parse tree; this is because having that extra layer when manipulating the
1403 parse tree is more confusing than it is helpful.
1404
1405 """
1406 if value[0] in CFWS_LEADER:
1407 leader, value = get_cfws(value)
1408 else:
1409 leader = None
1410 if not value:
1411 raise errors.HeaderParseError(
1412 "Expected 'atom' or 'quoted-string' but found nothing.")
1413 if value[0]=='"':
1414 token, value = get_quoted_string(value)
1415 elif value[0] in SPECIALS:
1416 raise errors.HeaderParseError("Expected 'atom' or 'quoted-string' "
1417 "but found '{}'".format(value))
1418 else:
1419 token, value = get_atom(value)
1420 if leader is not None:
1421 token[:0] = [leader]
1422 return token, value
1423
1424 def get_phrase(value):
1425 """ phrase = 1*word / obs-phrase
1426 obs-phrase = word *(word / "." / CFWS)
1427
1428 This means a phrase can be a sequence of words, periods, and CFWS in any
1429 order as long as it starts with at least one word. If anything other than
1430 words is detected, an ObsoleteHeaderDefect is added to the token's defect
1431 list. We also accept a phrase that starts with CFWS followed by a dot;
1432 this is registered as an InvalidHeaderDefect, since it is not supported by
1433 even the obsolete grammar.
1434
1435 """
1436 phrase = Phrase()
1437 try:
1438 token, value = get_word(value)
1439 phrase.append(token)
1440 except errors.HeaderParseError:
1441 phrase.defects.append(errors.InvalidHeaderDefect(
1442 "phrase does not start with word"))
1443 while value and value[0] not in PHRASE_ENDS:
1444 if value[0]=='.':
1445 phrase.append(DOT)
1446 phrase.defects.append(errors.ObsoleteHeaderDefect(
1447 "period in 'phrase'"))
1448 value = value[1:]
1449 else:
1450 try:
1451 token, value = get_word(value)
1452 except errors.HeaderParseError:
1453 if value[0] in CFWS_LEADER:
1454 token, value = get_cfws(value)
1455 phrase.defects.append(errors.ObsoleteHeaderDefect(
1456 "comment found without atom"))
1457 else:
1458 raise
1459 phrase.append(token)
1460 return phrase, value
1461
1462 def get_local_part(value):
1463 """ local-part = dot-atom / quoted-string / obs-local-part
1464
1465 """
1466 local_part = LocalPart()
1467 leader = None
1468 if value[0] in CFWS_LEADER:
1469 leader, value = get_cfws(value)
1470 if not value:
1471 raise errors.HeaderParseError(
1472 "expected local-part but found '{}'".format(value))
1473 try:
1474 token, value = get_dot_atom(value)
1475 except errors.HeaderParseError:
1476 try:
1477 token, value = get_word(value)
1478 except errors.HeaderParseError:
1479 if value[0] != '\\' and value[0] in PHRASE_ENDS:
1480 raise
1481 token = TokenList()
1482 if leader is not None:
1483 token[:0] = [leader]
1484 local_part.append(token)
1485 if value and (value[0]=='\\' or value[0] not in PHRASE_ENDS):
1486 obs_local_part, value = get_obs_local_part(str(local_part) + value)
1487 if obs_local_part.token_type == 'invalid-obs-local-part':
1488 local_part.defects.append(errors.InvalidHeaderDefect(
1489 "local-part is not dot-atom, quoted-string, or obs-local-part"))
1490 else:
1491 local_part.defects.append(errors.ObsoleteHeaderDefect(
1492 "local-part is not a dot-atom (contains CFWS)"))
1493 local_part[0] = obs_local_part
1494 try:
1495 local_part.value.encode('ascii')
1496 except UnicodeEncodeError:
1497 local_part.defects.append(errors.NonASCIILocalPartDefect(
1498 "local-part contains non-ASCII characters)"))
1499 return local_part, value
1500
1501 def get_obs_local_part(value):
1502 """ obs-local-part = word *("." word)
1503 """
1504 obs_local_part = ObsLocalPart()
1505 last_non_ws_was_dot = False
1506 while value and (value[0]=='\\' or value[0] not in PHRASE_ENDS):
1507 if value[0] == '.':
1508 if last_non_ws_was_dot:
1509 obs_local_part.defects.append(errors.InvalidHeaderDefect(
1510 "invalid repeated '.'"))
1511 obs_local_part.append(DOT)
1512 last_non_ws_was_dot = True
1513 value = value[1:]
1514 continue
1515 elif value[0]=='\\':
1516 obs_local_part.append(ValueTerminal(value[0],
1517 'misplaced-special'))
1518 value = value[1:]
1519 obs_local_part.defects.append(errors.InvalidHeaderDefect(
1520 "'\\' character outside of quoted-string/ccontent"))
1521 last_non_ws_was_dot = False
1522 continue
1523 if obs_local_part and obs_local_part[-1].token_type != 'dot':
1524 obs_local_part.defects.append(errors.InvalidHeaderDefect(
1525 "missing '.' between words"))
1526 try:
1527 token, value = get_word(value)
1528 last_non_ws_was_dot = False
1529 except errors.HeaderParseError:
1530 if value[0] not in CFWS_LEADER:
1531 raise
1532 token, value = get_cfws(value)
1533 obs_local_part.append(token)
1534 if (obs_local_part[0].token_type == 'dot' or
1535 obs_local_part[0].token_type=='cfws' and
1536 obs_local_part[1].token_type=='dot'):
1537 obs_local_part.defects.append(errors.InvalidHeaderDefect(
1538 "Invalid leading '.' in local part"))
1539 if (obs_local_part[-1].token_type == 'dot' or
1540 obs_local_part[-1].token_type=='cfws' and
1541 obs_local_part[-2].token_type=='dot'):
1542 obs_local_part.defects.append(errors.InvalidHeaderDefect(
1543 "Invalid trailing '.' in local part"))
1544 if obs_local_part.defects:
1545 obs_local_part.token_type = 'invalid-obs-local-part'
1546 return obs_local_part, value
1547
1548 def get_dtext(value):
1549 r""" dtext = <printable ascii except \ [ ]> / obs-dtext
1550 obs-dtext = obs-NO-WS-CTL / quoted-pair
1551
1552 We allow anything except the excluded characters, but if we find any
1553 ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is
1554 added to the token's defects list. Quoted pairs are converted to their
1555 unquoted values, so what is returned is a ptext token, in this case a
1556 ValueTerminal. If there were quoted-printables, an ObsoleteHeaderDefect is
1557 added to the returned token's defect list.
1558
1559 """
1560 ptext, value, had_qp = _get_ptext_to_endchars(value, '[]')
1561 ptext = ValueTerminal(ptext, 'ptext')
1562 if had_qp:
1563 ptext.defects.append(errors.ObsoleteHeaderDefect(
1564 "quoted printable found in domain-literal"))
1565 _validate_xtext(ptext)
1566 return ptext, value
1567
1568 def _check_for_early_dl_end(value, domain_literal):
1569 if value:
1570 return False
1571 domain_literal.append(errors.InvalidHeaderDefect(
1572 "end of input inside domain-literal"))
1573 domain_literal.append(ValueTerminal(']', 'domain-literal-end'))
1574 return True
1575
1576 def get_domain_literal(value):
1577 """ domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
1578
1579 """
1580 domain_literal = DomainLiteral()
1581 if value[0] in CFWS_LEADER:
1582 token, value = get_cfws(value)
1583 domain_literal.append(token)
1584 if not value:
1585 raise errors.HeaderParseError("expected domain-literal")
1586 if value[0] != '[':
1587 raise errors.HeaderParseError("expected '[' at start of domain-literal "
1588 "but found '{}'".format(value))
1589 value = value[1:]
1590 if _check_for_early_dl_end(value, domain_literal):
1591 return domain_literal, value
1592 domain_literal.append(ValueTerminal('[', 'domain-literal-start'))
1593 if value[0] in WSP:
1594 token, value = get_fws(value)
1595 domain_literal.append(token)
1596 token, value = get_dtext(value)
1597 domain_literal.append(token)
1598 if _check_for_early_dl_end(value, domain_literal):
1599 return domain_literal, value
1600 if value[0] in WSP:
1601 token, value = get_fws(value)
1602 domain_literal.append(token)
1603 if _check_for_early_dl_end(value, domain_literal):
1604 return domain_literal, value
1605 if value[0] != ']':
1606 raise errors.HeaderParseError("expected ']' at end of domain-literal "
1607 "but found '{}'".format(value))
1608 domain_literal.append(ValueTerminal(']', 'domain-literal-end'))
1609 value = value[1:]
1610 if value and value[0] in CFWS_LEADER:
1611 token, value = get_cfws(value)
1612 domain_literal.append(token)
1613 return domain_literal, value
1614
1615 def get_domain(value):
1616 """ domain = dot-atom / domain-literal / obs-domain
1617 obs-domain = atom *("." atom))
1618
1619 """
1620 domain = Domain()
1621 leader = None
1622 if value[0] in CFWS_LEADER:
1623 leader, value = get_cfws(value)
1624 if not value:
1625 raise errors.HeaderParseError(
1626 "expected domain but found '{}'".format(value))
1627 if value[0] == '[':
1628 token, value = get_domain_literal(value)
1629 if leader is not None:
1630 token[:0] = [leader]
1631 domain.append(token)
1632 return domain, value
1633 try:
1634 token, value = get_dot_atom(value)
1635 except errors.HeaderParseError:
1636 token, value = get_atom(value)
1637 if value and value[0] == '@':
1638 raise errors.HeaderParseError('Invalid Domain')
1639 if leader is not None:
1640 token[:0] = [leader]
1641 domain.append(token)
1642 if value and value[0] == '.':
1643 domain.defects.append(errors.ObsoleteHeaderDefect(
1644 "domain is not a dot-atom (contains CFWS)"))
1645 if domain[0].token_type == 'dot-atom':
1646 domain[:] = domain[0]
1647 while value and value[0] == '.':
1648 domain.append(DOT)
1649 token, value = get_atom(value[1:])
1650 domain.append(token)
1651 return domain, value
1652
1653 def get_addr_spec(value):
1654 """ addr-spec = local-part "@" domain
1655
1656 """
1657 addr_spec = AddrSpec()
1658 token, value = get_local_part(value)
1659 addr_spec.append(token)
1660 if not value or value[0] != '@':
1661 addr_spec.defects.append(errors.InvalidHeaderDefect(
1662 "addr-spec local part with no domain"))
1663 return addr_spec, value
1664 addr_spec.append(ValueTerminal('@', 'address-at-symbol'))
1665 token, value = get_domain(value[1:])
1666 addr_spec.append(token)
1667 return addr_spec, value
1668
1669 def get_obs_route(value):
1670 """ obs-route = obs-domain-list ":"
1671 obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain])
1672
1673 Returns an obs-route token with the appropriate sub-tokens (that is,
1674 there is no obs-domain-list in the parse tree).
1675 """
1676 obs_route = ObsRoute()
1677 while value and (value[0]==',' or value[0] in CFWS_LEADER):
1678 if value[0] in CFWS_LEADER:
1679 token, value = get_cfws(value)
1680 obs_route.append(token)
1681 elif value[0] == ',':
1682 obs_route.append(ListSeparator)
1683 value = value[1:]
1684 if not value or value[0] != '@':
1685 raise errors.HeaderParseError(
1686 "expected obs-route domain but found '{}'".format(value))
1687 obs_route.append(RouteComponentMarker)
1688 token, value = get_domain(value[1:])
1689 obs_route.append(token)
1690 while value and value[0]==',':
1691 obs_route.append(ListSeparator)
1692 value = value[1:]
1693 if not value:
1694 break
1695 if value[0] in CFWS_LEADER:
1696 token, value = get_cfws(value)
1697 obs_route.append(token)
1698 if value[0] == '@':
1699 obs_route.append(RouteComponentMarker)
1700 token, value = get_domain(value[1:])
1701 obs_route.append(token)
1702 if not value:
1703 raise errors.HeaderParseError("end of header while parsing obs-route")
1704 if value[0] != ':':
1705 raise errors.HeaderParseError( "expected ':' marking end of "
1706 "obs-route but found '{}'".format(value))
1707 obs_route.append(ValueTerminal(':', 'end-of-obs-route-marker'))
1708 return obs_route, value[1:]
1709
1710 def get_angle_addr(value):
1711 """ angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
1712 obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
1713
1714 """
1715 angle_addr = AngleAddr()
1716 if value[0] in CFWS_LEADER:
1717 token, value = get_cfws(value)
1718 angle_addr.append(token)
1719 if not value or value[0] != '<':
1720 raise errors.HeaderParseError(
1721 "expected angle-addr but found '{}'".format(value))
1722 angle_addr.append(ValueTerminal('<', 'angle-addr-start'))
1723 value = value[1:]
1724 # Although it is not legal per RFC5322, SMTP uses '<>' in certain
1725 # circumstances.
1726 if value[0] == '>':
1727 angle_addr.append(ValueTerminal('>', 'angle-addr-end'))
1728 angle_addr.defects.append(errors.InvalidHeaderDefect(
1729 "null addr-spec in angle-addr"))
1730 value = value[1:]
1731 return angle_addr, value
1732 try:
1733 token, value = get_addr_spec(value)
1734 except errors.HeaderParseError:
1735 try:
1736 token, value = get_obs_route(value)
1737 angle_addr.defects.append(errors.ObsoleteHeaderDefect(
1738 "obsolete route specification in angle-addr"))
1739 except errors.HeaderParseError:
1740 raise errors.HeaderParseError(
1741 "expected addr-spec or obs-route but found '{}'".format(value))
1742 angle_addr.append(token)
1743 token, value = get_addr_spec(value)
1744 angle_addr.append(token)
1745 if value and value[0] == '>':
1746 value = value[1:]
1747 else:
1748 angle_addr.defects.append(errors.InvalidHeaderDefect(
1749 "missing trailing '>' on angle-addr"))
1750 angle_addr.append(ValueTerminal('>', 'angle-addr-end'))
1751 if value and value[0] in CFWS_LEADER:
1752 token, value = get_cfws(value)
1753 angle_addr.append(token)
1754 return angle_addr, value
1755
1756 def get_display_name(value):
1757 """ display-name = phrase
1758
1759 Because this is simply a name-rule, we don't return a display-name
1760 token containing a phrase, but rather a display-name token with
1761 the content of the phrase.
1762
1763 """
1764 display_name = DisplayName()
1765 token, value = get_phrase(value)
1766 display_name.extend(token[:])
1767 display_name.defects = token.defects[:]
1768 return display_name, value
1769
1770
1771 def get_name_addr(value):
1772 """ name-addr = [display-name] angle-addr
1773
1774 """
1775 name_addr = NameAddr()
1776 # Both the optional display name and the angle-addr can start with cfws.
1777 leader = None
1778 if value[0] in CFWS_LEADER:
1779 leader, value = get_cfws(value)
1780 if not value:
1781 raise errors.HeaderParseError(
1782 "expected name-addr but found '{}'".format(leader))
1783 if value[0] != '<':
1784 if value[0] in PHRASE_ENDS:
1785 raise errors.HeaderParseError(
1786 "expected name-addr but found '{}'".format(value))
1787 token, value = get_display_name(value)
1788 if not value:
1789 raise errors.HeaderParseError(
1790 "expected name-addr but found '{}'".format(token))
1791 if leader is not None:
1792 token[0][:0] = [leader]
1793 leader = None
1794 name_addr.append(token)
1795 token, value = get_angle_addr(value)
1796 if leader is not None:
1797 token[:0] = [leader]
1798 name_addr.append(token)
1799 return name_addr, value
1800
1801 def get_mailbox(value):
1802 """ mailbox = name-addr / addr-spec
1803
1804 """
1805 # The only way to figure out if we are dealing with a name-addr or an
1806 # addr-spec is to try parsing each one.
1807 mailbox = Mailbox()
1808 try:
1809 token, value = get_name_addr(value)
1810 except errors.HeaderParseError:
1811 try:
1812 token, value = get_addr_spec(value)
1813 except errors.HeaderParseError:
1814 raise errors.HeaderParseError(
1815 "expected mailbox but found '{}'".format(value))
1816 if any(isinstance(x, errors.InvalidHeaderDefect)
1817 for x in token.all_defects):
1818 mailbox.token_type = 'invalid-mailbox'
1819 mailbox.append(token)
1820 return mailbox, value
1821
1822 def get_invalid_mailbox(value, endchars):
1823 """ Read everything up to one of the chars in endchars.
1824
1825 This is outside the formal grammar. The InvalidMailbox TokenList that is
1826 returned acts like a Mailbox, but the data attributes are None.
1827
1828 """
1829 invalid_mailbox = InvalidMailbox()
1830 while value and value[0] not in endchars:
1831 if value[0] in PHRASE_ENDS:
1832 invalid_mailbox.append(ValueTerminal(value[0],
1833 'misplaced-special'))
1834 value = value[1:]
1835 else:
1836 token, value = get_phrase(value)
1837 invalid_mailbox.append(token)
1838 return invalid_mailbox, value
1839
1840 def get_mailbox_list(value):
1841 """ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
1842 obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
1843
1844 For this routine we go outside the formal grammar in order to improve error
1845 handling. We recognize the end of the mailbox list only at the end of the
1846 value or at a ';' (the group terminator). This is so that we can turn
1847 invalid mailboxes into InvalidMailbox tokens and continue parsing any
1848 remaining valid mailboxes. We also allow all mailbox entries to be null,
1849 and this condition is handled appropriately at a higher level.
1850
1851 """
1852 mailbox_list = MailboxList()
1853 while value and value[0] != ';':
1854 try:
1855 token, value = get_mailbox(value)
1856 mailbox_list.append(token)
1857 except errors.HeaderParseError:
1858 leader = None
1859 if value[0] in CFWS_LEADER:
1860 leader, value = get_cfws(value)
1861 if not value or value[0] in ',;':
1862 mailbox_list.append(leader)
1863 mailbox_list.defects.append(errors.ObsoleteHeaderDefect(
1864 "empty element in mailbox-list"))
1865 else:
1866 token, value = get_invalid_mailbox(value, ',;')
1867 if leader is not None:
1868 token[:0] = [leader]
1869 mailbox_list.append(token)
1870 mailbox_list.defects.append(errors.InvalidHeaderDefect(
1871 "invalid mailbox in mailbox-list"))
1872 elif value[0] == ',':
1873 mailbox_list.defects.append(errors.ObsoleteHeaderDefect(
1874 "empty element in mailbox-list"))
1875 else:
1876 token, value = get_invalid_mailbox(value, ',;')
1877 if leader is not None:
1878 token[:0] = [leader]
1879 mailbox_list.append(token)
1880 mailbox_list.defects.append(errors.InvalidHeaderDefect(
1881 "invalid mailbox in mailbox-list"))
1882 if value and value[0] not in ',;':
1883 # Crap after mailbox; treat it as an invalid mailbox.
1884 # The mailbox info will still be available.
1885 mailbox = mailbox_list[-1]
1886 mailbox.token_type = 'invalid-mailbox'
1887 token, value = get_invalid_mailbox(value, ',;')
1888 mailbox.extend(token)
1889 mailbox_list.defects.append(errors.InvalidHeaderDefect(
1890 "invalid mailbox in mailbox-list"))
1891 if value and value[0] == ',':
1892 mailbox_list.append(ListSeparator)
1893 value = value[1:]
1894 return mailbox_list, value
1895
1896
1897 def get_group_list(value):
1898 """ group-list = mailbox-list / CFWS / obs-group-list
1899 obs-group-list = 1*([CFWS] ",") [CFWS]
1900
1901 """
1902 group_list = GroupList()
1903 if not value:
1904 group_list.defects.append(errors.InvalidHeaderDefect(
1905 "end of header before group-list"))
1906 return group_list, value
1907 leader = None
1908 if value and value[0] in CFWS_LEADER:
1909 leader, value = get_cfws(value)
1910 if not value:
1911 # This should never happen in email parsing, since CFWS-only is a
1912 # legal alternative to group-list in a group, which is the only
1913 # place group-list appears.
1914 group_list.defects.append(errors.InvalidHeaderDefect(
1915 "end of header in group-list"))
1916 group_list.append(leader)
1917 return group_list, value
1918 if value[0] == ';':
1919 group_list.append(leader)
1920 return group_list, value
1921 token, value = get_mailbox_list(value)
1922 if len(token.all_mailboxes)==0:
1923 if leader is not None:
1924 group_list.append(leader)
1925 group_list.extend(token)
1926 group_list.defects.append(errors.ObsoleteHeaderDefect(
1927 "group-list with empty entries"))
1928 return group_list, value
1929 if leader is not None:
1930 token[:0] = [leader]
1931 group_list.append(token)
1932 return group_list, value
1933
1934 def get_group(value):
1935 """ group = display-name ":" [group-list] ";" [CFWS]
1936
1937 """
1938 group = Group()
1939 token, value = get_display_name(value)
1940 if not value or value[0] != ':':
1941 raise errors.HeaderParseError("expected ':' at end of group "
1942 "display name but found '{}'".format(value))
1943 group.append(token)
1944 group.append(ValueTerminal(':', 'group-display-name-terminator'))
1945 value = value[1:]
1946 if value and value[0] == ';':
1947 group.append(ValueTerminal(';', 'group-terminator'))
1948 return group, value[1:]
1949 token, value = get_group_list(value)
1950 group.append(token)
1951 if not value:
1952 group.defects.append(errors.InvalidHeaderDefect(
1953 "end of header in group"))
1954 elif value[0] != ';':
1955 raise errors.HeaderParseError(
1956 "expected ';' at end of group but found {}".format(value))
1957 group.append(ValueTerminal(';', 'group-terminator'))
1958 value = value[1:]
1959 if value and value[0] in CFWS_LEADER:
1960 token, value = get_cfws(value)
1961 group.append(token)
1962 return group, value
1963
1964 def get_address(value):
1965 """ address = mailbox / group
1966
1967 Note that counter-intuitively, an address can be either a single address or
1968 a list of addresses (a group). This is why the returned Address object has
1969 a 'mailboxes' attribute which treats a single address as a list of length
1970 one. When you need to differentiate between to two cases, extract the single
1971 element, which is either a mailbox or a group token.
1972
1973 """
1974 # The formal grammar isn't very helpful when parsing an address. mailbox
1975 # and group, especially when allowing for obsolete forms, start off very
1976 # similarly. It is only when you reach one of @, <, or : that you know
1977 # what you've got. So, we try each one in turn, starting with the more
1978 # likely of the two. We could perhaps make this more efficient by looking
1979 # for a phrase and then branching based on the next character, but that
1980 # would be a premature optimization.
1981 address = Address()
1982 try:
1983 token, value = get_group(value)
1984 except errors.HeaderParseError:
1985 try:
1986 token, value = get_mailbox(value)
1987 except errors.HeaderParseError:
1988 raise errors.HeaderParseError(
1989 "expected address but found '{}'".format(value))
1990 address.append(token)
1991 return address, value
1992
1993 def get_address_list(value):
1994 """ address_list = (address *("," address)) / obs-addr-list
1995 obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
1996
1997 We depart from the formal grammar here by continuing to parse until the end
1998 of the input, assuming the input to be entirely composed of an
1999 address-list. This is always true in email parsing, and allows us
2000 to skip invalid addresses to parse additional valid ones.
2001
2002 """
2003 address_list = AddressList()
2004 while value:
2005 try:
2006 token, value = get_address(value)
2007 address_list.append(token)
2008 except errors.HeaderParseError as err:
2009 leader = None
2010 if value[0] in CFWS_LEADER:
2011 leader, value = get_cfws(value)
2012 if not value or value[0] == ',':
2013 address_list.append(leader)
2014 address_list.defects.append(errors.ObsoleteHeaderDefect(
2015 "address-list entry with no content"))
2016 else:
2017 token, value = get_invalid_mailbox(value, ',')
2018 if leader is not None:
2019 token[:0] = [leader]
2020 address_list.append(Address([token]))
2021 address_list.defects.append(errors.InvalidHeaderDefect(
2022 "invalid address in address-list"))
2023 elif value[0] == ',':
2024 address_list.defects.append(errors.ObsoleteHeaderDefect(
2025 "empty element in address-list"))
2026 else:
2027 token, value = get_invalid_mailbox(value, ',')
2028 if leader is not None:
2029 token[:0] = [leader]
2030 address_list.append(Address([token]))
2031 address_list.defects.append(errors.InvalidHeaderDefect(
2032 "invalid address in address-list"))
2033 if value and value[0] != ',':
2034 # Crap after address; treat it as an invalid mailbox.
2035 # The mailbox info will still be available.
2036 mailbox = address_list[-1][0]
2037 mailbox.token_type = 'invalid-mailbox'
2038 token, value = get_invalid_mailbox(value, ',')
2039 mailbox.extend(token)
2040 address_list.defects.append(errors.InvalidHeaderDefect(
2041 "invalid address in address-list"))
2042 if value: # Must be a , at this point.
2043 address_list.append(ListSeparator)
2044 value = value[1:]
2045 return address_list, value
2046
2047
2048 def get_no_fold_literal(value):
2049 """ no-fold-literal = "[" *dtext "]"
2050 """
2051 no_fold_literal = NoFoldLiteral()
2052 if not value:
2053 raise errors.HeaderParseError(
2054 "expected no-fold-literal but found '{}'".format(value))
2055 if value[0] != '[':
2056 raise errors.HeaderParseError(
2057 "expected '[' at the start of no-fold-literal "
2058 "but found '{}'".format(value))
2059 no_fold_literal.append(ValueTerminal('[', 'no-fold-literal-start'))
2060 value = value[1:]
2061 token, value = get_dtext(value)
2062 no_fold_literal.append(token)
2063 if not value or value[0] != ']':
2064 raise errors.HeaderParseError(
2065 "expected ']' at the end of no-fold-literal "
2066 "but found '{}'".format(value))
2067 no_fold_literal.append(ValueTerminal(']', 'no-fold-literal-end'))
2068 return no_fold_literal, value[1:]
2069
2070 def get_msg_id(value):
2071 """msg-id = [CFWS] "<" id-left '@' id-right ">" [CFWS]
2072 id-left = dot-atom-text / obs-id-left
2073 id-right = dot-atom-text / no-fold-literal / obs-id-right
2074 no-fold-literal = "[" *dtext "]"
2075 """
2076 msg_id = MsgID()
2077 if value and value[0] in CFWS_LEADER:
2078 token, value = get_cfws(value)
2079 msg_id.append(token)
2080 if not value or value[0] != '<':
2081 raise errors.HeaderParseError(
2082 "expected msg-id but found '{}'".format(value))
2083 msg_id.append(ValueTerminal('<', 'msg-id-start'))
2084 value = value[1:]
2085 # Parse id-left.
2086 try:
2087 token, value = get_dot_atom_text(value)
2088 except errors.HeaderParseError:
2089 try:
2090 # obs-id-left is same as local-part of add-spec.
2091 token, value = get_obs_local_part(value)
2092 msg_id.defects.append(errors.ObsoleteHeaderDefect(
2093 "obsolete id-left in msg-id"))
2094 except errors.HeaderParseError:
2095 raise errors.HeaderParseError(
2096 "expected dot-atom-text or obs-id-left"
2097 " but found '{}'".format(value))
2098 msg_id.append(token)
2099 if not value or value[0] != '@':
2100 msg_id.defects.append(errors.InvalidHeaderDefect(
2101 "msg-id with no id-right"))
2102 # Even though there is no id-right, if the local part
2103 # ends with `>` let's just parse it too and return
2104 # along with the defect.
2105 if value and value[0] == '>':
2106 msg_id.append(ValueTerminal('>', 'msg-id-end'))
2107 value = value[1:]
2108 return msg_id, value
2109 msg_id.append(ValueTerminal('@', 'address-at-symbol'))
2110 value = value[1:]
2111 # Parse id-right.
2112 try:
2113 token, value = get_dot_atom_text(value)
2114 except errors.HeaderParseError:
2115 try:
2116 token, value = get_no_fold_literal(value)
2117 except errors.HeaderParseError as e:
2118 try:
2119 token, value = get_domain(value)
2120 msg_id.defects.append(errors.ObsoleteHeaderDefect(
2121 "obsolete id-right in msg-id"))
2122 except errors.HeaderParseError:
2123 raise errors.HeaderParseError(
2124 "expected dot-atom-text, no-fold-literal or obs-id-right"
2125 " but found '{}'".format(value))
2126 msg_id.append(token)
2127 if value and value[0] == '>':
2128 value = value[1:]
2129 else:
2130 msg_id.defects.append(errors.InvalidHeaderDefect(
2131 "missing trailing '>' on msg-id"))
2132 msg_id.append(ValueTerminal('>', 'msg-id-end'))
2133 if value and value[0] in CFWS_LEADER:
2134 token, value = get_cfws(value)
2135 msg_id.append(token)
2136 return msg_id, value
2137
2138
2139 def parse_message_id(value):
2140 """message-id = "Message-ID:" msg-id CRLF
2141 """
2142 message_id = MessageID()
2143 try:
2144 token, value = get_msg_id(value)
2145 message_id.append(token)
2146 except errors.HeaderParseError as ex:
2147 token = get_unstructured(value)
2148 message_id = InvalidMessageID(token)
2149 message_id.defects.append(
2150 errors.InvalidHeaderDefect("Invalid msg-id: {!r}".format(ex)))
2151 else:
2152 # Value after parsing a valid msg_id should be None.
2153 if value:
2154 message_id.defects.append(errors.InvalidHeaderDefect(
2155 "Unexpected {!r}".format(value)))
2156
2157 return message_id
2158
2159 #
2160 # XXX: As I begin to add additional header parsers, I'm realizing we probably
2161 # have two level of parser routines: the get_XXX methods that get a token in
2162 # the grammar, and parse_XXX methods that parse an entire field value. So
2163 # get_address_list above should really be a parse_ method, as probably should
2164 # be get_unstructured.
2165 #
2166
2167 def parse_mime_version(value):
2168 """ mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]
2169
2170 """
2171 # The [CFWS] is implicit in the RFC 2045 BNF.
2172 # XXX: This routine is a bit verbose, should factor out a get_int method.
2173 mime_version = MIMEVersion()
2174 if not value:
2175 mime_version.defects.append(errors.HeaderMissingRequiredValue(
2176 "Missing MIME version number (eg: 1.0)"))
2177 return mime_version
2178 if value[0] in CFWS_LEADER:
2179 token, value = get_cfws(value)
2180 mime_version.append(token)
2181 if not value:
2182 mime_version.defects.append(errors.HeaderMissingRequiredValue(
2183 "Expected MIME version number but found only CFWS"))
2184 digits = ''
2185 while value and value[0] != '.' and value[0] not in CFWS_LEADER:
2186 digits += value[0]
2187 value = value[1:]
2188 if not digits.isdigit():
2189 mime_version.defects.append(errors.InvalidHeaderDefect(
2190 "Expected MIME major version number but found {!r}".format(digits)))
2191 mime_version.append(ValueTerminal(digits, 'xtext'))
2192 else:
2193 mime_version.major = int(digits)
2194 mime_version.append(ValueTerminal(digits, 'digits'))
2195 if value and value[0] in CFWS_LEADER:
2196 token, value = get_cfws(value)
2197 mime_version.append(token)
2198 if not value or value[0] != '.':
2199 if mime_version.major is not None:
2200 mime_version.defects.append(errors.InvalidHeaderDefect(
2201 "Incomplete MIME version; found only major number"))
2202 if value:
2203 mime_version.append(ValueTerminal(value, 'xtext'))
2204 return mime_version
2205 mime_version.append(ValueTerminal('.', 'version-separator'))
2206 value = value[1:]
2207 if value and value[0] in CFWS_LEADER:
2208 token, value = get_cfws(value)
2209 mime_version.append(token)
2210 if not value:
2211 if mime_version.major is not None:
2212 mime_version.defects.append(errors.InvalidHeaderDefect(
2213 "Incomplete MIME version; found only major number"))
2214 return mime_version
2215 digits = ''
2216 while value and value[0] not in CFWS_LEADER:
2217 digits += value[0]
2218 value = value[1:]
2219 if not digits.isdigit():
2220 mime_version.defects.append(errors.InvalidHeaderDefect(
2221 "Expected MIME minor version number but found {!r}".format(digits)))
2222 mime_version.append(ValueTerminal(digits, 'xtext'))
2223 else:
2224 mime_version.minor = int(digits)
2225 mime_version.append(ValueTerminal(digits, 'digits'))
2226 if value and value[0] in CFWS_LEADER:
2227 token, value = get_cfws(value)
2228 mime_version.append(token)
2229 if value:
2230 mime_version.defects.append(errors.InvalidHeaderDefect(
2231 "Excess non-CFWS text after MIME version"))
2232 mime_version.append(ValueTerminal(value, 'xtext'))
2233 return mime_version
2234
2235 def get_invalid_parameter(value):
2236 """ Read everything up to the next ';'.
2237
2238 This is outside the formal grammar. The InvalidParameter TokenList that is
2239 returned acts like a Parameter, but the data attributes are None.
2240
2241 """
2242 invalid_parameter = InvalidParameter()
2243 while value and value[0] != ';':
2244 if value[0] in PHRASE_ENDS:
2245 invalid_parameter.append(ValueTerminal(value[0],
2246 'misplaced-special'))
2247 value = value[1:]
2248 else:
2249 token, value = get_phrase(value)
2250 invalid_parameter.append(token)
2251 return invalid_parameter, value
2252
2253 def get_ttext(value):
2254 """ttext = <matches _ttext_matcher>
2255
2256 We allow any non-TOKEN_ENDS in ttext, but add defects to the token's
2257 defects list if we find non-ttext characters. We also register defects for
2258 *any* non-printables even though the RFC doesn't exclude all of them,
2259 because we follow the spirit of RFC 5322.
2260
2261 """
2262 m = _non_token_end_matcher(value)
2263 if not m:
2264 raise errors.HeaderParseError(
2265 "expected ttext but found '{}'".format(value))
2266 ttext = m.group()
2267 value = value[len(ttext):]
2268 ttext = ValueTerminal(ttext, 'ttext')
2269 _validate_xtext(ttext)
2270 return ttext, value
2271
2272 def get_token(value):
2273 """token = [CFWS] 1*ttext [CFWS]
2274
2275 The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or
2276 tspecials. We also exclude tabs even though the RFC doesn't.
2277
2278 The RFC implies the CFWS but is not explicit about it in the BNF.
2279
2280 """
2281 mtoken = Token()
2282 if value and value[0] in CFWS_LEADER:
2283 token, value = get_cfws(value)
2284 mtoken.append(token)
2285 if value and value[0] in TOKEN_ENDS:
2286 raise errors.HeaderParseError(
2287 "expected token but found '{}'".format(value))
2288 token, value = get_ttext(value)
2289 mtoken.append(token)
2290 if value and value[0] in CFWS_LEADER:
2291 token, value = get_cfws(value)
2292 mtoken.append(token)
2293 return mtoken, value
2294
2295 def get_attrtext(value):
2296 """attrtext = 1*(any non-ATTRIBUTE_ENDS character)
2297
2298 We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the
2299 token's defects list if we find non-attrtext characters. We also register
2300 defects for *any* non-printables even though the RFC doesn't exclude all of
2301 them, because we follow the spirit of RFC 5322.
2302
2303 """
2304 m = _non_attribute_end_matcher(value)
2305 if not m:
2306 raise errors.HeaderParseError(
2307 "expected attrtext but found {!r}".format(value))
2308 attrtext = m.group()
2309 value = value[len(attrtext):]
2310 attrtext = ValueTerminal(attrtext, 'attrtext')
2311 _validate_xtext(attrtext)
2312 return attrtext, value
2313
2314 def get_attribute(value):
2315 """ [CFWS] 1*attrtext [CFWS]
2316
2317 This version of the BNF makes the CFWS explicit, and as usual we use a
2318 value terminal for the actual run of characters. The RFC equivalent of
2319 attrtext is the token characters, with the subtraction of '*', "'", and '%'.
2320 We include tab in the excluded set just as we do for token.
2321
2322 """
2323 attribute = Attribute()
2324 if value and value[0] in CFWS_LEADER:
2325 token, value = get_cfws(value)
2326 attribute.append(token)
2327 if value and value[0] in ATTRIBUTE_ENDS:
2328 raise errors.HeaderParseError(
2329 "expected token but found '{}'".format(value))
2330 token, value = get_attrtext(value)
2331 attribute.append(token)
2332 if value and value[0] in CFWS_LEADER:
2333 token, value = get_cfws(value)
2334 attribute.append(token)
2335 return attribute, value
2336
2337 def get_extended_attrtext(value):
2338 """attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%')
2339
2340 This is a special parsing routine so that we get a value that
2341 includes % escapes as a single string (which we decode as a single
2342 string later).
2343
2344 """
2345 m = _non_extended_attribute_end_matcher(value)
2346 if not m:
2347 raise errors.HeaderParseError(
2348 "expected extended attrtext but found {!r}".format(value))
2349 attrtext = m.group()
2350 value = value[len(attrtext):]
2351 attrtext = ValueTerminal(attrtext, 'extended-attrtext')
2352 _validate_xtext(attrtext)
2353 return attrtext, value
2354
2355 def get_extended_attribute(value):
2356 """ [CFWS] 1*extended_attrtext [CFWS]
2357
2358 This is like the non-extended version except we allow % characters, so that
2359 we can pick up an encoded value as a single string.
2360
2361 """
2362 # XXX: should we have an ExtendedAttribute TokenList?
2363 attribute = Attribute()
2364 if value and value[0] in CFWS_LEADER:
2365 token, value = get_cfws(value)
2366 attribute.append(token)
2367 if value and value[0] in EXTENDED_ATTRIBUTE_ENDS:
2368 raise errors.HeaderParseError(
2369 "expected token but found '{}'".format(value))
2370 token, value = get_extended_attrtext(value)
2371 attribute.append(token)
2372 if value and value[0] in CFWS_LEADER:
2373 token, value = get_cfws(value)
2374 attribute.append(token)
2375 return attribute, value
2376
2377 def get_section(value):
2378 """ '*' digits
2379
2380 The formal BNF is more complicated because leading 0s are not allowed. We
2381 check for that and add a defect. We also assume no CFWS is allowed between
2382 the '*' and the digits, though the RFC is not crystal clear on that.
2383 The caller should already have dealt with leading CFWS.
2384
2385 """
2386 section = Section()
2387 if not value or value[0] != '*':
2388 raise errors.HeaderParseError("Expected section but found {}".format(
2389 value))
2390 section.append(ValueTerminal('*', 'section-marker'))
2391 value = value[1:]
2392 if not value or not value[0].isdigit():
2393 raise errors.HeaderParseError("Expected section number but "
2394 "found {}".format(value))
2395 digits = ''
2396 while value and value[0].isdigit():
2397 digits += value[0]
2398 value = value[1:]
2399 if digits[0] == '0' and digits != '0':
2400 section.defects.append(errors.InvalidHeaderDefect(
2401 "section number has an invalid leading 0"))
2402 section.number = int(digits)
2403 section.append(ValueTerminal(digits, 'digits'))
2404 return section, value
2405
2406
2407 def get_value(value):
2408 """ quoted-string / attribute
2409
2410 """
2411 v = Value()
2412 if not value:
2413 raise errors.HeaderParseError("Expected value but found end of string")
2414 leader = None
2415 if value[0] in CFWS_LEADER:
2416 leader, value = get_cfws(value)
2417 if not value:
2418 raise errors.HeaderParseError("Expected value but found "
2419 "only {}".format(leader))
2420 if value[0] == '"':
2421 token, value = get_quoted_string(value)
2422 else:
2423 token, value = get_extended_attribute(value)
2424 if leader is not None:
2425 token[:0] = [leader]
2426 v.append(token)
2427 return v, value
2428
2429 def get_parameter(value):
2430 """ attribute [section] ["*"] [CFWS] "=" value
2431
2432 The CFWS is implied by the RFC but not made explicit in the BNF. This
2433 simplified form of the BNF from the RFC is made to conform with the RFC BNF
2434 through some extra checks. We do it this way because it makes both error
2435 recovery and working with the resulting parse tree easier.
2436 """
2437 # It is possible CFWS would also be implicitly allowed between the section
2438 # and the 'extended-attribute' marker (the '*') , but we've never seen that
2439 # in the wild and we will therefore ignore the possibility.
2440 param = Parameter()
2441 token, value = get_attribute(value)
2442 param.append(token)
2443 if not value or value[0] == ';':
2444 param.defects.append(errors.InvalidHeaderDefect("Parameter contains "
2445 "name ({}) but no value".format(token)))
2446 return param, value
2447 if value[0] == '*':
2448 try:
2449 token, value = get_section(value)
2450 param.sectioned = True
2451 param.append(token)
2452 except errors.HeaderParseError:
2453 pass
2454 if not value:
2455 raise errors.HeaderParseError("Incomplete parameter")
2456 if value[0] == '*':
2457 param.append(ValueTerminal('*', 'extended-parameter-marker'))
2458 value = value[1:]
2459 param.extended = True
2460 if value[0] != '=':
2461 raise errors.HeaderParseError("Parameter not followed by '='")
2462 param.append(ValueTerminal('=', 'parameter-separator'))
2463 value = value[1:]
2464 leader = None
2465 if value and value[0] in CFWS_LEADER:
2466 token, value = get_cfws(value)
2467 param.append(token)
2468 remainder = None
2469 appendto = param
2470 if param.extended and value and value[0] == '"':
2471 # Now for some serious hackery to handle the common invalid case of
2472 # double quotes around an extended value. We also accept (with defect)
2473 # a value marked as encoded that isn't really.
2474 qstring, remainder = get_quoted_string(value)
2475 inner_value = qstring.stripped_value
2476 semi_valid = False
2477 if param.section_number == 0:
2478 if inner_value and inner_value[0] == "'":
2479 semi_valid = True
2480 else:
2481 token, rest = get_attrtext(inner_value)
2482 if rest and rest[0] == "'":
2483 semi_valid = True
2484 else:
2485 try:
2486 token, rest = get_extended_attrtext(inner_value)
2487 except:
2488 pass
2489 else:
2490 if not rest:
2491 semi_valid = True
2492 if semi_valid:
2493 param.defects.append(errors.InvalidHeaderDefect(
2494 "Quoted string value for extended parameter is invalid"))
2495 param.append(qstring)
2496 for t in qstring:
2497 if t.token_type == 'bare-quoted-string':
2498 t[:] = []
2499 appendto = t
2500 break
2501 value = inner_value
2502 else:
2503 remainder = None
2504 param.defects.append(errors.InvalidHeaderDefect(
2505 "Parameter marked as extended but appears to have a "
2506 "quoted string value that is non-encoded"))
2507 if value and value[0] == "'":
2508 token = None
2509 else:
2510 token, value = get_value(value)
2511 if not param.extended or param.section_number > 0:
2512 if not value or value[0] != "'":
2513 appendto.append(token)
2514 if remainder is not None:
2515 assert not value, value
2516 value = remainder
2517 return param, value
2518 param.defects.append(errors.InvalidHeaderDefect(
2519 "Apparent initial-extended-value but attribute "
2520 "was not marked as extended or was not initial section"))
2521 if not value:
2522 # Assume the charset/lang is missing and the token is the value.
2523 param.defects.append(errors.InvalidHeaderDefect(
2524 "Missing required charset/lang delimiters"))
2525 appendto.append(token)
2526 if remainder is None:
2527 return param, value
2528 else:
2529 if token is not None:
2530 for t in token:
2531 if t.token_type == 'extended-attrtext':
2532 break
2533 t.token_type == 'attrtext'
2534 appendto.append(t)
2535 param.charset = t.value
2536 if value[0] != "'":
2537 raise errors.HeaderParseError("Expected RFC2231 char/lang encoding "
2538 "delimiter, but found {!r}".format(value))
2539 appendto.append(ValueTerminal("'", 'RFC2231-delimiter'))
2540 value = value[1:]
2541 if value and value[0] != "'":
2542 token, value = get_attrtext(value)
2543 appendto.append(token)
2544 param.lang = token.value
2545 if not value or value[0] != "'":
2546 raise errors.HeaderParseError("Expected RFC2231 char/lang encoding "
2547 "delimiter, but found {}".format(value))
2548 appendto.append(ValueTerminal("'", 'RFC2231-delimiter'))
2549 value = value[1:]
2550 if remainder is not None:
2551 # Treat the rest of value as bare quoted string content.
2552 v = Value()
2553 while value:
2554 if value[0] in WSP:
2555 token, value = get_fws(value)
2556 elif value[0] == '"':
2557 token = ValueTerminal('"', 'DQUOTE')
2558 value = value[1:]
2559 else:
2560 token, value = get_qcontent(value)
2561 v.append(token)
2562 token = v
2563 else:
2564 token, value = get_value(value)
2565 appendto.append(token)
2566 if remainder is not None:
2567 assert not value, value
2568 value = remainder
2569 return param, value
2570
2571 def parse_mime_parameters(value):
2572 """ parameter *( ";" parameter )
2573
2574 That BNF is meant to indicate this routine should only be called after
2575 finding and handling the leading ';'. There is no corresponding rule in
2576 the formal RFC grammar, but it is more convenient for us for the set of
2577 parameters to be treated as its own TokenList.
2578
2579 This is 'parse' routine because it consumes the remaining value, but it
2580 would never be called to parse a full header. Instead it is called to
2581 parse everything after the non-parameter value of a specific MIME header.
2582
2583 """
2584 mime_parameters = MimeParameters()
2585 while value:
2586 try:
2587 token, value = get_parameter(value)
2588 mime_parameters.append(token)
2589 except errors.HeaderParseError as err:
2590 leader = None
2591 if value[0] in CFWS_LEADER:
2592 leader, value = get_cfws(value)
2593 if not value:
2594 mime_parameters.append(leader)
2595 return mime_parameters
2596 if value[0] == ';':
2597 if leader is not None:
2598 mime_parameters.append(leader)
2599 mime_parameters.defects.append(errors.InvalidHeaderDefect(
2600 "parameter entry with no content"))
2601 else:
2602 token, value = get_invalid_parameter(value)
2603 if leader:
2604 token[:0] = [leader]
2605 mime_parameters.append(token)
2606 mime_parameters.defects.append(errors.InvalidHeaderDefect(
2607 "invalid parameter {!r}".format(token)))
2608 if value and value[0] != ';':
2609 # Junk after the otherwise valid parameter. Mark it as
2610 # invalid, but it will have a value.
2611 param = mime_parameters[-1]
2612 param.token_type = 'invalid-parameter'
2613 token, value = get_invalid_parameter(value)
2614 param.extend(token)
2615 mime_parameters.defects.append(errors.InvalidHeaderDefect(
2616 "parameter with invalid trailing text {!r}".format(token)))
2617 if value:
2618 # Must be a ';' at this point.
2619 mime_parameters.append(ValueTerminal(';', 'parameter-separator'))
2620 value = value[1:]
2621 return mime_parameters
2622
2623 def _find_mime_parameters(tokenlist, value):
2624 """Do our best to find the parameters in an invalid MIME header
2625
2626 """
2627 while value and value[0] != ';':
2628 if value[0] in PHRASE_ENDS:
2629 tokenlist.append(ValueTerminal(value[0], 'misplaced-special'))
2630 value = value[1:]
2631 else:
2632 token, value = get_phrase(value)
2633 tokenlist.append(token)
2634 if not value:
2635 return
2636 tokenlist.append(ValueTerminal(';', 'parameter-separator'))
2637 tokenlist.append(parse_mime_parameters(value[1:]))
2638
2639 def parse_content_type_header(value):
2640 """ maintype "/" subtype *( ";" parameter )
2641
2642 The maintype and substype are tokens. Theoretically they could
2643 be checked against the official IANA list + x-token, but we
2644 don't do that.
2645 """
2646 ctype = ContentType()
2647 recover = False
2648 if not value:
2649 ctype.defects.append(errors.HeaderMissingRequiredValue(
2650 "Missing content type specification"))
2651 return ctype
2652 try:
2653 token, value = get_token(value)
2654 except errors.HeaderParseError:
2655 ctype.defects.append(errors.InvalidHeaderDefect(
2656 "Expected content maintype but found {!r}".format(value)))
2657 _find_mime_parameters(ctype, value)
2658 return ctype
2659 ctype.append(token)
2660 # XXX: If we really want to follow the formal grammar we should make
2661 # mantype and subtype specialized TokenLists here. Probably not worth it.
2662 if not value or value[0] != '/':
2663 ctype.defects.append(errors.InvalidHeaderDefect(
2664 "Invalid content type"))
2665 if value:
2666 _find_mime_parameters(ctype, value)
2667 return ctype
2668 ctype.maintype = token.value.strip().lower()
2669 ctype.append(ValueTerminal('/', 'content-type-separator'))
2670 value = value[1:]
2671 try:
2672 token, value = get_token(value)
2673 except errors.HeaderParseError:
2674 ctype.defects.append(errors.InvalidHeaderDefect(
2675 "Expected content subtype but found {!r}".format(value)))
2676 _find_mime_parameters(ctype, value)
2677 return ctype
2678 ctype.append(token)
2679 ctype.subtype = token.value.strip().lower()
2680 if not value:
2681 return ctype
2682 if value[0] != ';':
2683 ctype.defects.append(errors.InvalidHeaderDefect(
2684 "Only parameters are valid after content type, but "
2685 "found {!r}".format(value)))
2686 # The RFC requires that a syntactically invalid content-type be treated
2687 # as text/plain. Perhaps we should postel this, but we should probably
2688 # only do that if we were checking the subtype value against IANA.
2689 del ctype.maintype, ctype.subtype
2690 _find_mime_parameters(ctype, value)
2691 return ctype
2692 ctype.append(ValueTerminal(';', 'parameter-separator'))
2693 ctype.append(parse_mime_parameters(value[1:]))
2694 return ctype
2695
2696 def parse_content_disposition_header(value):
2697 """ disposition-type *( ";" parameter )
2698
2699 """
2700 disp_header = ContentDisposition()
2701 if not value:
2702 disp_header.defects.append(errors.HeaderMissingRequiredValue(
2703 "Missing content disposition"))
2704 return disp_header
2705 try:
2706 token, value = get_token(value)
2707 except errors.HeaderParseError:
2708 disp_header.defects.append(errors.InvalidHeaderDefect(
2709 "Expected content disposition but found {!r}".format(value)))
2710 _find_mime_parameters(disp_header, value)
2711 return disp_header
2712 disp_header.append(token)
2713 disp_header.content_disposition = token.value.strip().lower()
2714 if not value:
2715 return disp_header
2716 if value[0] != ';':
2717 disp_header.defects.append(errors.InvalidHeaderDefect(
2718 "Only parameters are valid after content disposition, but "
2719 "found {!r}".format(value)))
2720 _find_mime_parameters(disp_header, value)
2721 return disp_header
2722 disp_header.append(ValueTerminal(';', 'parameter-separator'))
2723 disp_header.append(parse_mime_parameters(value[1:]))
2724 return disp_header
2725
2726 def parse_content_transfer_encoding_header(value):
2727 """ mechanism
2728
2729 """
2730 # We should probably validate the values, since the list is fixed.
2731 cte_header = ContentTransferEncoding()
2732 if not value:
2733 cte_header.defects.append(errors.HeaderMissingRequiredValue(
2734 "Missing content transfer encoding"))
2735 return cte_header
2736 try:
2737 token, value = get_token(value)
2738 except errors.HeaderParseError:
2739 cte_header.defects.append(errors.InvalidHeaderDefect(
2740 "Expected content transfer encoding but found {!r}".format(value)))
2741 else:
2742 cte_header.append(token)
2743 cte_header.cte = token.value.strip().lower()
2744 if not value:
2745 return cte_header
2746 while value:
2747 cte_header.defects.append(errors.InvalidHeaderDefect(
2748 "Extra text after content transfer encoding"))
2749 if value[0] in PHRASE_ENDS:
2750 cte_header.append(ValueTerminal(value[0], 'misplaced-special'))
2751 value = value[1:]
2752 else:
2753 token, value = get_phrase(value)
2754 cte_header.append(token)
2755 return cte_header
2756
2757
2758 #
2759 # Header folding
2760 #
2761 # Header folding is complex, with lots of rules and corner cases. The
2762 # following code does its best to obey the rules and handle the corner
2763 # cases, but you can be sure there are few bugs:)
2764 #
2765 # This folder generally canonicalizes as it goes, preferring the stringified
2766 # version of each token. The tokens contain information that supports the
2767 # folder, including which tokens can be encoded in which ways.
2768 #
2769 # Folded text is accumulated in a simple list of strings ('lines'), each
2770 # one of which should be less than policy.max_line_length ('maxlen').
2771 #
2772
2773 def _steal_trailing_WSP_if_exists(lines):
2774 wsp = ''
2775 if lines and lines[-1] and lines[-1][-1] in WSP:
2776 wsp = lines[-1][-1]
2777 lines[-1] = lines[-1][:-1]
2778 return wsp
2779
2780 def _refold_parse_tree(parse_tree, *, policy):
2781 """Return string of contents of parse_tree folded according to RFC rules.
2782
2783 """
2784 # max_line_length 0/None means no limit, ie: infinitely long.
2785 maxlen = policy.max_line_length or sys.maxsize
2786 encoding = 'utf-8' if policy.utf8 else 'us-ascii'
2787 lines = ['']
2788 last_ew = None
2789 last_charset = None
2790 wrap_as_ew_blocked = 0
2791 want_encoding = False
2792 end_ew_not_allowed = Terminal('', 'wrap_as_ew_blocked')
2793 parts = list(parse_tree)
2794 while parts:
2795 part = parts.pop(0)
2796 if part is end_ew_not_allowed:
2797 wrap_as_ew_blocked -= 1
2798 continue
2799 tstr = str(part)
2800 if not want_encoding:
2801 if part.token_type in ('ptext', 'vtext'):
2802 # Encode if tstr contains special characters.
2803 want_encoding = not SPECIALSNL.isdisjoint(tstr)
2804 else:
2805 # Encode if tstr contains newlines.
2806 want_encoding = not NLSET.isdisjoint(tstr)
2807 try:
2808 tstr.encode(encoding)
2809 charset = encoding
2810 except UnicodeEncodeError:
2811 if any(isinstance(x, errors.UndecodableBytesDefect)
2812 for x in part.all_defects):
2813 charset = 'unknown-8bit'
2814 else:
2815 # If policy.utf8 is false this should really be taken from a
2816 # 'charset' property on the policy.
2817 charset = 'utf-8'
2818 want_encoding = True
2819 if part.token_type == 'mime-parameters':
2820 # Mime parameter folding (using RFC2231) is extra special.
2821 _fold_mime_parameters(part, lines, maxlen, encoding)
2822 continue
2823 if want_encoding and not wrap_as_ew_blocked:
2824 if not part.as_ew_allowed:
2825 want_encoding = False
2826 last_ew = None
2827 if part.syntactic_break:
2828 encoded_part = part.fold(policy=policy)[:-len(policy.linesep)]
2829 if policy.linesep not in encoded_part:
2830 # It fits on a single line
2831 if len(encoded_part) > maxlen - len(lines[-1]):
2832 # But not on this one, so start a new one.
2833 newline = _steal_trailing_WSP_if_exists(lines)
2834 # XXX what if encoded_part has no leading FWS?
2835 lines.append(newline)
2836 lines[-1] += encoded_part
2837 continue
2838 # Either this is not a major syntactic break, so we don't
2839 # want it on a line by itself even if it fits, or it
2840 # doesn't fit on a line by itself. Either way, fall through
2841 # to unpacking the subparts and wrapping them.
2842 if not hasattr(part, 'encode'):
2843 # It's not a Terminal, do each piece individually.
2844 parts = list(part) + parts
2845 want_encoding = False
2846 continue
2847 elif part.as_ew_allowed:
2848 # It's a terminal, wrap it as an encoded word, possibly
2849 # combining it with previously encoded words if allowed.
2850 if (last_ew is not None and
2851 charset != last_charset and
2852 (last_charset == 'unknown-8bit' or
2853 last_charset == 'utf-8' and charset != 'us-ascii')):
2854 last_ew = None
2855 last_ew = _fold_as_ew(tstr, lines, maxlen, last_ew,
2856 part.ew_combine_allowed, charset)
2857 last_charset = charset
2858 want_encoding = False
2859 continue
2860 else:
2861 # It's a terminal which should be kept non-encoded
2862 # (e.g. a ListSeparator).
2863 last_ew = None
2864 want_encoding = False
2865 # fall through
2866
2867 if len(tstr) <= maxlen - len(lines[-1]):
2868 lines[-1] += tstr
2869 continue
2870 # This part is too long to fit. The RFC wants us to break at
2871 # "major syntactic breaks", so unless we don't consider this
2872 # to be one, check if it will fit on the next line by itself.
2873 if (part.syntactic_break and
2874 len(tstr) + 1 <= maxlen):
2875 newline = _steal_trailing_WSP_if_exists(lines)
2876 if newline or part.startswith_fws():
2877 lines.append(newline + tstr)
2878 last_ew = None
2879 continue
2880 if not hasattr(part, 'encode'):
2881 # It's not a terminal, try folding the subparts.
2882 newparts = list(part)
2883 if part.token_type == 'bare-quoted-string':
2884 # To fold a quoted string we need to create a list of terminal
2885 # tokens that will render the leading and trailing quotes
2886 # and use quoted pairs in the value as appropriate.
2887 newparts = (
2888 [ValueTerminal('"', 'ptext')] +
2889 [ValueTerminal(make_quoted_pairs(p), 'ptext')
2890 for p in newparts] +
2891 [ValueTerminal('"', 'ptext')])
2892 if part.token_type == 'comment':
2893 newparts = (
2894 [ValueTerminal('(', 'ptext')] +
2895 [ValueTerminal(make_parenthesis_pairs(p), 'ptext')
2896 if p.token_type == 'ptext' else p
2897 for p in newparts] +
2898 [ValueTerminal(')', 'ptext')])
2899 if not part.as_ew_allowed:
2900 wrap_as_ew_blocked += 1
2901 newparts.append(end_ew_not_allowed)
2902 parts = newparts + parts
2903 continue
2904 if part.as_ew_allowed and not wrap_as_ew_blocked:
2905 # It doesn't need CTE encoding, but encode it anyway so we can
2906 # wrap it.
2907 parts.insert(0, part)
2908 want_encoding = True
2909 continue
2910 # We can't figure out how to wrap, it, so give up.
2911 newline = _steal_trailing_WSP_if_exists(lines)
2912 if newline or part.startswith_fws():
2913 lines.append(newline + tstr)
2914 else:
2915 # We can't fold it onto the next line either...
2916 lines[-1] += tstr
2917 return policy.linesep.join(lines) + policy.linesep
2918
2919 def _fold_as_ew(to_encode, lines, maxlen, last_ew, ew_combine_allowed, charset):
2920 """Fold string to_encode into lines as encoded word, combining if allowed.
2921 Return the new value for last_ew, or None if ew_combine_allowed is False.
2922
2923 If there is already an encoded word in the last line of lines (indicated by
2924 a non-None value for last_ew) and ew_combine_allowed is true, decode the
2925 existing ew, combine it with to_encode, and re-encode. Otherwise, encode
2926 to_encode. In either case, split to_encode as necessary so that the
2927 encoded segments fit within maxlen.
2928
2929 """
2930 if last_ew is not None and ew_combine_allowed:
2931 to_encode = str(
2932 get_unstructured(lines[-1][last_ew:] + to_encode))
2933 lines[-1] = lines[-1][:last_ew]
2934 if to_encode[0] in WSP:
2935 # We're joining this to non-encoded text, so don't encode
2936 # the leading blank.
2937 leading_wsp = to_encode[0]
2938 to_encode = to_encode[1:]
2939 if (len(lines[-1]) == maxlen):
2940 lines.append(_steal_trailing_WSP_if_exists(lines))
2941 lines[-1] += leading_wsp
2942 trailing_wsp = ''
2943 if to_encode[-1] in WSP:
2944 # Likewise for the trailing space.
2945 trailing_wsp = to_encode[-1]
2946 to_encode = to_encode[:-1]
2947 new_last_ew = len(lines[-1]) if last_ew is None else last_ew
2948
2949 encode_as = 'utf-8' if charset == 'us-ascii' else charset
2950
2951 # The RFC2047 chrome takes up 7 characters plus the length
2952 # of the charset name.
2953 chrome_len = len(encode_as) + 7
2954
2955 if (chrome_len + 1) >= maxlen:
2956 raise errors.HeaderParseError(
2957 "max_line_length is too small to fit an encoded word")
2958
2959 while to_encode:
2960 remaining_space = maxlen - len(lines[-1])
2961 text_space = remaining_space - chrome_len
2962 if text_space <= 0:
2963 lines.append(' ')
2964 continue
2965
2966 to_encode_word = to_encode[:text_space]
2967 encoded_word = _ew.encode(to_encode_word, charset=encode_as)
2968 excess = len(encoded_word) - remaining_space
2969 while excess > 0:
2970 # Since the chunk to encode is guaranteed to fit into less than 100 characters,
2971 # shrinking it by one at a time shouldn't take long.
2972 to_encode_word = to_encode_word[:-1]
2973 encoded_word = _ew.encode(to_encode_word, charset=encode_as)
2974 excess = len(encoded_word) - remaining_space
2975 lines[-1] += encoded_word
2976 to_encode = to_encode[len(to_encode_word):]
2977
2978 if to_encode:
2979 lines.append(' ')
2980 new_last_ew = len(lines[-1])
2981 lines[-1] += trailing_wsp
2982 return new_last_ew if ew_combine_allowed else None
2983
2984 def _fold_mime_parameters(part, lines, maxlen, encoding):
2985 """Fold TokenList 'part' into the 'lines' list as mime parameters.
2986
2987 Using the decoded list of parameters and values, format them according to
2988 the RFC rules, including using RFC2231 encoding if the value cannot be
2989 expressed in 'encoding' and/or the parameter+value is too long to fit
2990 within 'maxlen'.
2991
2992 """
2993 # Special case for RFC2231 encoding: start from decoded values and use
2994 # RFC2231 encoding iff needed.
2995 #
2996 # Note that the 1 and 2s being added to the length calculations are
2997 # accounting for the possibly-needed spaces and semicolons we'll be adding.
2998 #
2999 for name, value in part.params:
3000 # XXX What if this ';' puts us over maxlen the first time through the
3001 # loop? We should split the header value onto a newline in that case,
3002 # but to do that we need to recognize the need earlier or reparse the
3003 # header, so I'm going to ignore that bug for now. It'll only put us
3004 # one character over.
3005 if not lines[-1].rstrip().endswith(';'):
3006 lines[-1] += ';'
3007 charset = encoding
3008 error_handler = 'strict'
3009 try:
3010 value.encode(encoding)
3011 encoding_required = False
3012 except UnicodeEncodeError:
3013 encoding_required = True
3014 if utils._has_surrogates(value):
3015 charset = 'unknown-8bit'
3016 error_handler = 'surrogateescape'
3017 else:
3018 charset = 'utf-8'
3019 if encoding_required:
3020 encoded_value = urllib.parse.quote(
3021 value, safe='', errors=error_handler)
3022 tstr = "{}*={}''{}".format(name, charset, encoded_value)
3023 else:
3024 tstr = '{}={}'.format(name, quote_string(value))
3025 if len(lines[-1]) + len(tstr) + 1 < maxlen:
3026 lines[-1] = lines[-1] + ' ' + tstr
3027 continue
3028 elif len(tstr) + 2 <= maxlen:
3029 lines.append(' ' + tstr)
3030 continue
3031 # We need multiple sections. We are allowed to mix encoded and
3032 # non-encoded sections, but we aren't going to. We'll encode them all.
3033 section = 0
3034 extra_chrome = charset + "''"
3035 while value:
3036 chrome_len = len(name) + len(str(section)) + 3 + len(extra_chrome)
3037 if maxlen <= chrome_len + 3:
3038 # We need room for the leading blank, the trailing semicolon,
3039 # and at least one character of the value. If we don't
3040 # have that, we'd be stuck, so in that case fall back to
3041 # the RFC standard width.
3042 maxlen = 78
3043 splitpoint = maxchars = maxlen - chrome_len - 2
3044 while True:
3045 partial = value[:splitpoint]
3046 encoded_value = urllib.parse.quote(
3047 partial, safe='', errors=error_handler)
3048 if len(encoded_value) <= maxchars:
3049 break
3050 splitpoint -= 1
3051 lines.append(" {}*{}*={}{}".format(
3052 name, section, extra_chrome, encoded_value))
3053 extra_chrome = ''
3054 section += 1
3055 value = value[splitpoint:]
3056 if value:
3057 lines[-1] += ';'