Debian Codegraph @

Lib/email/_header_value_parser.py

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