• File: _header_value_parser.cpython-38.pyc
  • Full Path: /home3/farmfre2/public_html/ALFA_DATA/alfasymlink/root/proc/self/root/opt/alt/python38/lib64/python3.8/email/__pycache__/_header_value_parser.cpython-38.pyc
  • Date Modified: 10/26/2026 8:15 PM
  • File size: 78.71 KB
  • MIME-type: text/x-bytecode.python
  • Charset: 8 bit
U

jU	@sdZddlZddlZddlZddlmZddlmZddlm	Z
ddlmZddlmZe
dZee
d	BZe
d
ZeeBZee
dZee
dZee
d
Be
dZeeBZee
dBZeeBZee
dZddhZeeBZddZddZedejejBZ Gddde!Z"Gddde"Z#Gddde"Z$Gddde"Z%Gdd d e"Z&Gd!d"d"e#Z'Gd#d$d$e"Z(Gd%d&d&e"Z)Gd'd(d(e"Z*Gd)d*d*e"Z+Gd+d,d,e+Z,Gd-d.d.e#Z-Gd/d0d0e"Z.Gd1d2d2e"Z/Gd3d4d4e"Z0Gd5d6d6e"Z1Gd7d8d8e"Z2Gd9d:d:e"Z3Gd;d<d<e"Z4Gd=d>d>e"Z5Gd?d@d@e"Z6GdAdBdBe"Z7GdCdDdDe"Z8GdEdFdFe"Z9GdGdHdHe"Z:GdIdJdJe"Z;GdKdLdLe"Z<GdMdNdNe"Z=GdOdPdPe%Z>GdQdRdRe"Z?GdSdTdTe"Z@GdUdVdVe"ZAGdWdXdXe"ZBGdYdZdZeBZCGd[d\d\e"ZDGd]d^d^e"ZEGd_d`d`e"ZFGdadbdbe"ZGGdcdddde"ZHGdedfdfeHZIGdgdhdheHZJGdidjdje"ZKGdkdldle"ZLGdmdndne"ZMGdodpdpeMZNGdqdrdreNZOGdsdtdte"ZPGdudvdveQZRGdwdxdxeRZSGdydzdzeRZTGd{d|d|eSZUGd}d~d~ejVZWeTddZXeTddZYdeY_ZdeY_[eTddZ\ed]d^ej_Z`ed]ead^ejbZcedjdZeed]ead^ejbZfed]ead^ejbZged]ead^ejbZhddZiddZjddZkddZlddZmddZnddZoddZpddZqddZrddZsddZtddZuddZvddZwddZxddZyddZzddZ{ddZ|ddZ}ddZ~ddZddZddZddZddZddZdd„ZddĄZddƄZddȄZddʄZdd̄Zdd΄ZddЄZdd҄ZddԄZddքZdd؄ZddڄZdd܄ZddބZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZdS)alHeader value parser implementing various email-related RFC parsing rules.

The parsing methods defined in this module implement various email related
parsing rules.  Principal among them is RFC 5322, which is the followon
to RFC 2822 and primarily a clarification of the former.  It also implements
RFC 2047 encoded word decoding.

RFC 5322 goes to considerable trouble to maintain backward compatibility with
RFC 822 in the parse phase, while cleaning up the structure on the generation
phase.  This parser supports correct RFC 5322 generation by tagging white space
as folding white space only when folding is allowed in the non-obsolete rule
sets.  Actually, the parser is even more generous when accepting input than RFC
5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages.
Where possible deviations from the standard are annotated on the 'defects'
attribute of tokens that deviate.

The general structure of the parser follows RFC 5322, and uses its terminology
where there is a direct correspondence.  Where the implementation requires a
somewhat different structure than that used by the formal grammar, new terms
that mimic the closest existing terms are used.  Thus, it really helps to have
a copy of RFC 5322 handy when studying this code.

Input to the parser is a string that has already been unfolded according to
RFC 5322 rules.  According to the RFC this unfolding is the very first step, and
this parser leaves the unfolding step to a higher level message parser, which
will have already detected the line breaks that need unfolding while
determining the beginning and end of each header.

The output of the parser is a TokenList object, which is a list subclass.  A
TokenList is a recursive data structure.  The terminal nodes of the structure
are Terminal objects, which are subclasses of str.  These do not correspond
directly to terminal objects in the formal grammar, but are instead more
practical higher level combinations of true terminals.

All TokenList and Terminal objects have a 'value' attribute, which produces the
semantically meaningful value of that part of the parse subtree.  The value of
all whitespace tokens (no matter how many sub-tokens they may contain) is a
single space, as per the RFC rules.  This includes 'CFWS', which is herein
included in the general class of whitespace tokens.  There is one exception to
the rule that whitespace tokens are collapsed into single spaces in values: in
the value of a 'bare-quoted-string' (a quoted-string with no leading or
trailing whitespace), any whitespace that appeared between the quotation marks
is preserved in the returned value.  Note that in all Terminal strings quoted
pairs are turned into their unquoted values.

All TokenList and Terminal objects also have a string value, which attempts to
be a "canonical" representation of the RFC-compliant form of the substring that
produced the parsed subtree, including minimal use of quoted pair quoting.
Whitespace runs are not collapsed.

Comment tokens also have a 'content' attribute providing the string found
between the parens (including any nested comments) with whitespace preserved.

All TokenList and Terminal objects have a 'defects' attribute which is a
possibly empty list all of the defects found while creating the token.  Defects
may appear on any token in the tree, and a composite list of all defects in the
subtree is available through the 'all_defects' attribute of any node.  (For
Terminal notes x.defects == x.all_defects.)

Each object in a parse tree is called a 'token', and each has a 'token_type'
attribute that gives the name from the RFC 5322 grammar that it represents.
Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that
may be produced: 'ptext'.  A 'ptext' is a string of printable ascii characters.
It is returned in place of lists of (ctext/quoted-pair) and
(qtext/quoted-pair).

XXX: provide complete list of token types.
N)	hexdigits)
itemgetter)_encoded_words)errors)utilsz 	(z
()<>@,:;.\"[].z."(z/?=z*'%%

cCs t|ddddddS)z:Escape parenthesis and backslash for use within a comment.\\\r\()\)strreplacevaluer?/opt/alt/python38/lib64/python3.8/email/_header_value_parser.pymake_parenthesis_pairsbsrcCs dt|dddddS)N"rr
z\"rrrrrquote_stringhsrz
   =\?            # literal =?
   [^?]*          # charset
   \?             # literal ?
   [qQbB]         # literal 'q' or 'b', case insensitive
   \?             # literal ?
  .*?             # encoded word
  \?=             # literal ?=
cseZdZdZdZdZfddZddZfddZe	d	d
Z
e	ddZd
dZe	ddZ
e	ddZddZdddZdddZdddZZS)	TokenListNTcstj||g|_dSN)super__init__defects)selfargskw	__class__rrrszTokenList.__init__cCsddd|DS)Ncss|]}t|VqdSrr.0xrrr	<genexpr>sz$TokenList.__str__.<locals>.<genexpr>joinr rrr__str__szTokenList.__str__csd|jjtSNz{}({})formatr$__name__r__repr__r-r#rrr3s
zTokenList.__repr__cCsddd|DS)Nr%css|]}|jr|jVqdSrrr'rrrr*sz"TokenList.value.<locals>.<genexpr>r+r-rrrrszTokenList.valuecCstdd|D|jS)Ncss|]}|jVqdSr)all_defectsr'rrrr*sz(TokenList.all_defects.<locals>.<genexpr>)sumrr-rrrr4szTokenList.all_defectscCs|dSNr)startswith_fwsr-rrrr7szTokenList.startswith_fwscCstdd|DS)zATrue if all top level tokens of this part may be RFC2047 encoded.css|]}|jVqdSr)
as_ew_allowed)r(partrrrr*sz*TokenList.as_ew_allowed.<locals>.<genexpr>)allr-rrrr8szTokenList.as_ew_allowedcCsg}|D]}||jq|Sr)extendcomments)r r<tokenrrrr<szTokenList.commentscCst||dS)Npolicy)_refold_parse_treer r?rrrfoldszTokenList.foldr%cCst|j|ddS)Nindent)printppstrr rDrrrpprintszTokenList.pprintcCsd|j|dS)Nr
rC)r,_pprGrrrrFszTokenList.ppstrccszd||jj|jV|D]4}t|ds:|d|Vq||dEdHq|jrdd|j}nd}d||VdS)Nz{}{}/{}(rIz*    !! invalid element in token list: {!r}z    z Defects: {}r%z{}){})r1r$r2
token_typehasattrrIr)r rDr=ZextrarrrrIs

z
TokenList._pp)r%)r%)r%)r2
__module____qualname__rJsyntactic_breakew_combine_allowedrr.r3propertyrr4r7r8r<rBrHrFrI
__classcell__rrr#rr{s&





rc@s$eZdZeddZeddZdS)WhiteSpaceTokenListcCsdSN rr-rrrrszWhiteSpaceTokenList.valuecCsdd|DS)NcSsg|]}|jdkr|jqS)comment)rJcontentr'rrr
<listcomp>s
z0WhiteSpaceTokenList.comments.<locals>.<listcomp>rr-rrrr<szWhiteSpaceTokenList.commentsN)r2rLrMrPrr<rrrrrRs
rRc@seZdZdZdS)UnstructuredTokenListunstructuredNr2rLrMrJrrrrrXsrXc@seZdZdZdS)PhrasephraseNrZrrrrr[sr[c@seZdZdZdS)WordZwordNrZrrrrr]sr]c@seZdZdZdS)CFWSListcfwsNrZrrrrr^sr^c@seZdZdZdS)AtomatomNrZrrrrr`sr`c@seZdZdZdZdS)Tokenr=FN)r2rLrMrJZencode_as_ewrrrrrbsrbc@seZdZdZdZdZdZdS)EncodedWordencoded-wordN)r2rLrMrJctecharsetlangrrrrrcsrcc@s4eZdZdZeddZeddZeddZdS)	QuotedString
quoted-stringcCs"|D]}|jdkr|jSqdSNbare-quoted-stringrJrr r)rrrrVs
zQuotedString.contentcCs>g}|D]*}|jdkr&|t|q||jqd|S)Nrkr%)rJappendrrr,)r resr)rrrquoted_values
zQuotedString.quoted_valuecCs"|D]}|jdkr|jSqdSrjrlr r=rrrstripped_values
zQuotedString.stripped_valueN)r2rLrMrJrPrVrprrrrrrrhs

	rhc@s$eZdZdZddZeddZdS)BareQuotedStringrkcCstddd|DS)Nr%css|]}t|VqdSrr&r'rrrr*sz+BareQuotedString.__str__.<locals>.<genexpr>)rr,r-rrrr.szBareQuotedString.__str__cCsddd|DS)Nr%css|]}t|VqdSrr&r'rrrr*sz)BareQuotedString.value.<locals>.<genexpr>r+r-rrrr
szBareQuotedString.valueN)r2rLrMrJr.rPrrrrrrssrsc@s8eZdZdZddZddZeddZedd	Zd
S)CommentrUcs(dtdgfddDdgggS)Nr%rcsg|]}|qSr)quoter'r-rrrWsz#Comment.__str__.<locals>.<listcomp>r)r,r5r-rr-rr.szComment.__str__cCs2|jdkrt|St|ddddddS)NrUrr
rrrr)rJrr)r rrrrrus
z
Comment.quotecCsddd|DS)Nr%css|]}t|VqdSrr&r'rrrr*#sz"Comment.content.<locals>.<genexpr>r+r-rrrrV!szComment.contentcCs|jgSr)rVr-rrrr<%szComment.commentsN)	r2rLrMrJr.rurPrVr<rrrrrts
rtc@s4eZdZdZeddZeddZeddZdS)	AddressListzaddress-listcCsdd|DS)NcSsg|]}|jdkr|qS)addressrJr'rrrrW/s
z)AddressList.addresses.<locals>.<listcomp>rr-rrr	addresses-szAddressList.addressescCstdd|DgS)Ncss|]}|jdkr|jVqdSrwNrJ	mailboxesr'rrrr*3s
z(AddressList.mailboxes.<locals>.<genexpr>r5r-rrrr|1s
zAddressList.mailboxescCstdd|DgS)Ncss|]}|jdkr|jVqdSrzrJ
all_mailboxesr'rrrr*8s
z,AddressList.all_mailboxes.<locals>.<genexpr>r}r-rrrr6s
zAddressList.all_mailboxesN)r2rLrMrJrPryr|rrrrrrv)s

rvc@s4eZdZdZeddZeddZeddZdS)	AddressrwcCs|djdkr|djSdS)NrgrouprJdisplay_namer-rrrr@szAddress.display_namecCs4|djdkr|dgS|djdkr*gS|djSNrmailboxinvalid-mailboxr{r-rrrr|Es

zAddress.mailboxescCs:|djdkr|dgS|djdkr0|dgS|djSrr~r-rrrrMs


zAddress.all_mailboxesN)r2rLrMrJrPrr|rrrrrr<s

rc@s(eZdZdZeddZeddZdS)MailboxListmailbox-listcCsdd|DS)NcSsg|]}|jdkr|qS)rrxr'rrrrW[s
z)MailboxList.mailboxes.<locals>.<listcomp>rr-rrrr|YszMailboxList.mailboxescCsdd|DS)NcSsg|]}|jdkr|qS))rrrxr'rrrrW_s
z-MailboxList.all_mailboxes.<locals>.<listcomp>rr-rrrr]szMailboxList.all_mailboxesNr2rLrMrJrPr|rrrrrrUs

rc@s(eZdZdZeddZeddZdS)	GroupList
group-listcCs |r|djdkrgS|djSNrrr{r-rrrr|gszGroupList.mailboxescCs |r|djdkrgS|djSrr~r-rrrrmszGroupList.all_mailboxesNrrrrrrcs

rc@s4eZdZdZeddZeddZeddZdS)	GrouprcCs|djdkrgS|djSNrr{r-rrrr|xszGroup.mailboxescCs|djdkrgS|djSrr~r-rrrr~szGroup.all_mailboxescCs
|djSr6)rr-rrrrszGroup.display_nameN)r2rLrMrJrPr|rrrrrrrts

rc@sLeZdZdZeddZeddZeddZedd	Zed
dZ	dS)
NameAddr	name-addrcCst|dkrdS|djSNr)lenrr-rrrrszNameAddr.display_namecCs
|djSN
local_partr-rrrrszNameAddr.local_partcCs
|djSrdomainr-rrrrszNameAddr.domaincCs
|djSr)router-rrrrszNameAddr.routecCs
|djSr	addr_specr-rrrrszNameAddr.addr_specN
r2rLrMrJrPrrrrrrrrrrs



rc@s@eZdZdZeddZeddZeddZedd	Zd
S)	AngleAddrz
angle-addrcCs"|D]}|jdkr|jSqdSN	addr-spec)rJrrmrrrrs
zAngleAddr.local_partcCs"|D]}|jdkr|jSqdSrrJrrmrrrrs
zAngleAddr.domaincCs"|D]}|jdkr|jSqdS)N	obs-route)rJdomainsrmrrrrs
zAngleAddr.routecCs<|D]2}|jdkr|jr"|jSt|j|jSqdS)Nrz<>)rJrrrrmrrrrs

zAngleAddr.addr_specN)	r2rLrMrJrPrrrrrrrrrs


rc@seZdZdZeddZdS)ObsRoutercCsdd|DS)NcSsg|]}|jdkr|jqSrrr'rrrrWs
z$ObsRoute.domains.<locals>.<listcomp>rr-rrrrszObsRoute.domainsN)r2rLrMrJrPrrrrrrsrc@sLeZdZdZeddZeddZeddZedd	Zed
dZ	dS)
MailboxrcCs|djdkr|djSdSNrrrr-rrrrszMailbox.display_namecCs
|djSr6rr-rrrrszMailbox.local_partcCs
|djSr6rr-rrrrszMailbox.domaincCs|djdkr|djSdSr)rJrr-rrrrsz
Mailbox.routecCs
|djSr6rr-rrrrszMailbox.addr_specNrrrrrrs



rc@s,eZdZdZeddZeZZZZ	dS)InvalidMailboxrcCsdSrrr-rrrrszInvalidMailbox.display_nameNrrrrrrs
rcs(eZdZdZdZefddZZS)DomainrFcsdtjSNr%r,rrsplitr-r#rrrsz
Domain.domain)r2rLrMrJr8rPrrQrrr#rrsrc@seZdZdZdS)DotAtomdot-atomNrZrrrrrsrc@seZdZdZdZdS)DotAtomTextz
dot-atom-textTNr2rLrMrJr8rrrrrsrc@seZdZdZdZdS)
NoFoldLiteralzno-fold-literalFNrrrrrrsrc@sDeZdZdZdZeddZeddZeddZed	d
Z	dS)AddrSpecrFcCs
|djSr6rr-rrrrszAddrSpec.local_partcCst|dkrdS|djS)Nr)rrr-rrrrszAddrSpec.domaincCs<t|dkr|djS|dj|dj|djS)Nrrrr)rrrstriplstripr-rrrrs
zAddrSpec.valuecCsLt|j}t|t|tkr*t|j}n|j}|jdk	rH|d|jS|S)N@)setrr
DOT_ATOM_ENDSrr)r ZnamesetZlprrrr"s

zAddrSpec.addr_specN)
r2rLrMrJr8rPrrrrrrrrr
s


rc@seZdZdZdZdS)ObsLocalPartzobs-local-partFNrrrrrr.srcs4eZdZdZdZeddZefddZZS)DisplayNamezdisplay-nameFcCst|}t|dkr|jS|djdkr4|dn*|ddjdkr^t|ddd|d<|djdkrv|n*|ddjdkrt|ddd|d<|jS)Nrr_rr)rrrrJpop)r rorrrr9s
zDisplayName.display_namecsd}|jrd}n|D]}|jdkrd}qt|dkr|rd}}|djdks`|ddjdkrdd}|djdks|ddjdkrd}|t|j|StjSdS)	NFTrirr%r_rTr)rrJrrrrr)r rur)ZpreZpostr#rrrJs
  zDisplayName.value)	r2rLrMrJrOrPrrrQrrr#rr4s
rc@s,eZdZdZdZeddZeddZdS)	LocalPartz
local-partFcCs&|djdkr|djS|djSdS)Nrri)rJrprr-rrrrcs
zLocalPart.valuecCstg}t}d}|dtgD]}|jdkr,q|r\|jdkr\|djdkr\t|dd|d<t|t}|r|jdkr|djdkr|t|ddn
|||d}|}qt|dd}|jS)NFrr_dotrr)DOTrJr
isinstancernr)r roZlastZ
last_is_tltokZis_tlrrrrjs(


zLocalPart.local_partN)r2rLrMrJr8rPrrrrrrr^s
rcs4eZdZdZdZefddZeddZZS)
DomainLiteralzdomain-literalFcsdtjSrrr-r#rrrszDomainLiteral.domaincCs"|D]}|jdkr|jSqdS)Nptextrlrmrrrips
zDomainLiteral.ip)	r2rLrMrJr8rPrrrQrrr#rrsrc@seZdZdZdZdZdS)MIMEVersionzmime-versionN)r2rLrMrJmajorminorrrrrrsrc@s4eZdZdZdZdZdZeddZeddZ	dS)		Parameter	parameterFus-asciicCs|jr|djSdSr)	sectionednumberr-rrrsection_numberszParameter.section_numbercCsf|D]\}|jdkr|jS|jdkr|D]4}|jdkr*|D] }|jdkr<|jSq<q*qdS)Nrrirkr%)rJrrrqrrrparam_values




zParameter.param_valueN)
r2rLrMrJrextendedrfrPrrrrrrrs
rc@seZdZdZdS)InvalidParameterinvalid-parameterNrZrrrrrsrc@seZdZdZeddZdS)	Attribute	attributecCs$|D]}|jdr|jSqdS)Nattrtext)rJendswithrrqrrrrrszAttribute.stripped_valueNr2rLrMrJrPrrrrrrrsrc@seZdZdZdZdS)SectionsectionN)r2rLrMrJrrrrrrsrc@seZdZdZeddZdS)ValuercCs2|d}|jdkr|d}|jdr,|jS|jS)Nrr_r)rirzextended-attribute)rJrrrrrqrrrrrs
zValue.stripped_valueNrrrrrrsrc@s(eZdZdZdZeddZddZdS)MimeParametersmime-parametersFc
csi}|D]T}|jdsq|djdkr*q|dj}||krHg||<|||j|fq|D]~\}}t|tdd}|dd}|j	}|j
st|dkr|dddkr|ddjt
d|dd}g}d}|D]\}	}
|	|kr(|
j
s|
jt
dqn|
jt
d|d7}|
j}|
j
rztj|}Wn&tk
rttjj|d	d
}YnRXz||d}Wn"tk
r|dd}YnXt|r|
jt
||qd
|}||fVqfdS)Nrrr)keyrz.duplicate parameter name; duplicate(s) ignoredz+duplicate parameter name; duplicate ignoredz(inconsistent RFC2231 parameter numberingzlatin-1)encodingsurrogateescaperr%)rJrrstriprnritemssortedrrfrrrrInvalidHeaderDefectrurllibparseZunquote_to_bytesUnicodeEncodeErrorZunquotedecodeLookupErrorr_has_surrogatesUndecodableBytesDefectr,)r paramsr=namepartsZfirst_paramrfZvalue_partsirparamrrrrrs`



zMimeParameters.paramscCsTg}|jD].\}}|r.|d|t|q
||q
d|}|rPd|SdS)N{}={}z; rTr%)rrnr1rr,)r rrrrrrr.$s
zMimeParameters.__str__N)r2rLrMrJrNrPrr.rrrrrs

Erc@seZdZdZeddZdS)ParameterizedHeaderValueFcCs&t|D]}|jdkr|jSqiS)Nr)reversedrJrrqrrrr5s
zParameterizedHeaderValue.paramsN)r2rLrMrNrPrrrrrr/src@seZdZdZdZdZdZdS)ContentTypezcontent-typeFtextZplainN)r2rLrMrJr8maintypesubtyperrrrr=src@seZdZdZdZdZdS)ContentDispositionzcontent-dispositionFN)r2rLrMrJr8content_dispositionrrrrrDsrc@seZdZdZdZdZdS)ContentTransferEncodingzcontent-transfer-encodingFZ7bitN)r2rLrMrJr8rerrrrrJsrc@seZdZdZdZdS)HeaderLabelzheader-labelFNrrrrrrPsrc@seZdZdZdZddZdS)MsgIDzmsg-idFcCst||jSr)rlineseprArrrrBYsz
MsgID.foldN)r2rLrMrJr8rBrrrrrUsrc@seZdZdZdS)	MessageIDz
message-idNrZrrrrr^src@seZdZdZdS)InvalidMessageIDzinvalid-message-idNrZrrrrrbsrc@seZdZdZdS)HeaderheaderNrZrrrrrfsrcsreZdZdZdZdZfddZfddZddZe	dd	Z
dfdd	Zd
dZe	ddZ
ddZZS)TerminalTcst||}||_g|_|Sr)r__new__rJr)clsrrJr r#rrrtszTerminal.__new__csd|jjtSr/r0r-r#rrr3zszTerminal.__repr__cCst|jjd|jdS)N/)rEr$r2rJr-rrrrH}szTerminal.pprintcCs
t|jSr)listrr-rrrr4szTerminal.all_defectsr%c	s2d||jj|jt|js"dn
d|jgS)Nz
{}{}/{}({}){}r%z {})r1r$r2rJrr3rrGr#rrrIszTerminal._ppcCsdSrrr-rrrpop_trailing_wsszTerminal.pop_trailing_wscCsgSrrr-rrrr<szTerminal.commentscCst||jfSr)rrJr-rrr__getnewargs__szTerminal.__getnewargs__)r%)r2rLrMr8rOrNrr3rHrPr4rIrr<rrQrrr#rrns
	
rc@s eZdZeddZddZdS)WhiteSpaceTerminalcCsdSrSrr-rrrrszWhiteSpaceTerminal.valuecCs|o|dtkSr6WSPr-rrrr7sz!WhiteSpaceTerminal.startswith_fwsNr2rLrMrPrr7rrrrrs
rc@s eZdZeddZddZdS)
ValueTerminalcCs|Srrr-rrrrszValueTerminal.valuecCsdS)NFrr-rrrr7szValueTerminal.startswith_fwsNr	rrrrr
s
r
c@s eZdZeddZddZdS)EWWhiteSpaceTerminalcCsdSrrr-rrrrszEWWhiteSpaceTerminal.valuecCsdSrrr-rrrr.szEWWhiteSpaceTerminal.__str__N)r2rLrMrPrr.rrrrrs
rc@seZdZdZdS)_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r2rLrM__doc__rrrrrsrr,zlist-separatorFrzroute-component-markerz([{}]+)r%z[^{}]+z[\x00-\x20\x7F]cCs>t|}|r|jt|t|r:|jtddS)z@If input token contains ASCII non-printables, register a defect.z*Non-ASCII characters found in header tokenN)_non_printable_finderrrnrZNonPrintableDefectrrr)xtextZnon_printablesrrr_validate_xtexts

rcCst|d^}}g}d}d}tt|D]L}||dkrJ|rDd}d}nd}q&|rTd}n|||krdq||||q&|d}d|d||dg||fS)akScan printables/quoted-pairs until endchars and return unquoted ptext.

    This function turns a run of qcontent, ccontent-without-comments, or
    dtext-with-quoted-printables into a single string by unquoting any
    quoted printables.  It returns the string, the remaining value, and
    a flag that is True iff there were any quoted printables decoded.

    rFrTr%N)
_wsp_splitterrangerrnr,)rendcharsZfragment	remainderZvcharsescapehad_qpposrrr_get_ptext_to_endcharss$	rcCs.|}t|dt|t|d}||fS)zFWS = 1*WSP

    This isn't the RFC definition.  We're using fws to represent tokens where
    folding can be done, but when we are parsing the *un*folding has already
    been done so we don't need to watch out for CRLF.

    Nfws)rrr)rZnewvaluerrrrget_fwssrc
	Cst}|ds td||dddd^}}||ddkrXtd|d|}t|dkr|dtkr|dtkr|	d	dkr|dd^}}|d|}t|dkr|j
td
||_
d|}ztd|d\}}}}	Wn*ttfk
r*td|j
YnX||_||_|j
|	|r|dtkrrt|\}
}||
qDt|d^}}t|d}t|||d|}qD|r|dtkr|j
td
||fS)zE encoded-word = "=?" charset "?" encoding "?" encoded-text "?="

    =?z"expected encoded word but found {}rNz?=rr%r?zwhitespace inside encoded wordz!encoded word format invalid: '{}'vtextz.missing trailing whitespace after encoded-word)rc
startswithrHeaderParseErrorr1rr,rrcountrrnrre_ewr
ValueErrorKeyErrorrrfrgr;rrrr
r)
rZewrrZremstrrestrrfrgrr=charsrrrrget_encoded_wordsd











r'cCsFt}|rB|dtkr0t|\}}||qd}|drzt|\}}Wn,tk
rfd}Yntjk
rzYnrXd}t	|dkr|dj
dkr|jtdd}|rt	|dkr|d	j
d
krt
|dd|d<||qt|d^}}|rt|r|d^}}t|d}t|||d|}q|S)
aOunstructured = (*([FWS] vchar) *WSP) / obs-unstruct
       obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS)
       obs-utext = %d0 / obs-NO-WS-CTL / LF / CR

       obs-NO-WS-CTL is control characters except WSP/CR/LF.

    So, basically, we have printable runs, plus control characters or nulls in
    the obsolete syntax, separated by whitespace.  Since RFC 2047 uses the
    obsolete syntax in its specification, but requires whitespace on either
    side of the encoded words, I can see no reason to need to separate the
    non-printable-non-whitespace from the printable runs if they occur, so we
    parse this into xtext tokens separated by WSP tokens.

    Because an 'unstructured' value must by definition constitute the entire
    value, this 'get' routine does not return a remaining value, only the
    parsed TokenList.

    rTrFrrz&missing whitespace before encoded wordrrdrr%)rXrrrnrr'rrr rrJrrrrrfc2047_matchersearch	partitionr
rr,)rrYr=valid_ewZhave_wsrrrrrrget_unstructuredIsJ





r-cCs*t|d\}}}t|d}t|||fS)actext = <printable ascii except \ ( )>

    This is not the RFC ctext, since we are handling nested comments in comment
    and unquoting quoted-pairs here.  We allow anything except the '()'
    characters, but if we find any ASCII other than the RFC defined printable
    ASCII, a NonPrintableDefect is added to the token's defects list.  Since
    quoted pairs are converted to their unquoted values, what is returned is
    a 'ptext' token.  In this case it is a WhiteSpaceTerminal, so it's value
    is ' '.

    z()r)rrrrr_rrrget_qp_ctexts
r0cCs*t|d\}}}t|d}t|||fS)aoqcontent = qtext / quoted-pair

    We allow anything except the DQUOTE character, but if we find any ASCII
    other than the RFC defined printable ASCII, a NonPrintableDefect is
    added to the token's defects list.  Any quoted pairs are converted to their
    unquoted values, so what is returned is a 'ptext' token.  In this case it
    is a ValueTerminal.

    rr)rr
rr.rrrget_qcontents

r1cCsNt|}|std||}|t|d}t|d}t|||fS)zatext = <matches _atext_matcher>

    We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to
    the token's defects list if we find non-atext characters.
    zexpected atext but found '{}'Natext)_non_atom_end_matcherrr r1rrr
r)rmr2rrr	get_atexts
r5cCsr|ddkrtd|t}|dd}|rT|ddkrTt|\}}|||rB|ddkrB|dtkrt|\}}n|dddkr*d}z&t|\}}|j	t
d	d
}Wn"tjk
rt|\}}YnX|r6t|dkr6|djdkr6|d
jdkr6t
|dd|d<nt|\}}||qT|sb|j	t
d||fS||ddfS)zbare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE

    A quoted-string without the leading or trailing white space.  Its
    value is the text between the quote marks, with whitespace
    preserved and quoted pairs decoded.
    rrzexpected '"' but found '{}'rNrrFz!encoded word inside quoted stringTrrr(rdz"end of header inside quoted string)rr r1rsr1rnrrr'rrrrJr)rZbare_quoted_stringr=r,rrrget_bare_quoted_stringsL



r6cCs|r |ddkr td|t}|dd}|r|ddkr|dtkr\t|\}}n&|ddkrvt|\}}nt|\}}||q2|s|j	t
d||fS||ddfS)zcomment = "(" *([FWS] ccontent) [FWS] ")"
       ccontent = ctext / quoted-pair / comment

    We handle nested comments here, and quoted-pair in our qp-ctext routine.
    rrzexpected '(' but found '{}'rNrzend of header inside comment)rr r1rtrrget_commentr0rnrr)rrUr=rrrr7s&
r7cCsPt}|rH|dtkrH|dtkr0t|\}}nt|\}}||q||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS

    r)r^CFWS_LEADERrrr7rn)rr_r=rrrget_cfwssr9cCspt}|r,|dtkr,t|\}}||t|\}}|||rh|dtkrht|\}}||||fS)zquoted-string = [CFWS] <bare-quoted-string> [CFWS]

    'bare-quoted-string' is an intermediate class defined by this
    parser and not by the RFC grammar.  It is the quoted string
    without any attached CFWS.
    r)rhr8r9rnr6)rZ
quoted_stringr=rrrget_quoted_string
s


r:cCst}|r,|dtkr,t|\}}|||rL|dtkrLtd||drzt	|\}}Wqtjk
rt
|\}}YqXnt
|\}}|||r|dtkrt|\}}||||fS)zPatom = [CFWS] 1*atext [CFWS]

    An atom could be an rfc2047 encoded word.
    rzexpected atom but found '{}'r)r`r8r9rn	ATOM_ENDSrr r1rr'r5)rrar=rrrget_atoms&



r<cCst}|r|dtkr&td||rt|dtkrtt|\}}|||r&|ddkr&|t|dd}q&|dtkrtdd|||fS)z( dot-text = 1*atext *("." 1*atext)

    rz8expected atom at a start of dot-atom-text but found '{}'rrNrz4expected atom at end of dot-atom-text but found '{}')rr;rr r1r5rnr)rZ
dot_atom_textr=rrrget_dot_atom_text:s 

r=cCst}|dtkr(t|\}}|||drhzt|\}}Wqttjk
rdt|\}}YqtXnt|\}}|||r|dtkrt|\}}||||fS)z dot-atom = [CFWS] dot-atom-text [CFWS]

    Any place we can have a dot atom, we could instead have an rfc2047 encoded
    word.
    rr)	rr8r9rnrr'rr r=)rZdot_atomr=rrrget_dot_atomMs



r>cCs|dtkrt|\}}nd}|s,td|ddkrFt|\}}n*|dtkrdtd|nt|\}}|dk	r|g|dd<||fS)aword = atom / quoted-string

    Either atom or quoted-string may start with CFWS.  We have to peel off this
    CFWS first to determine which type of word to parse.  Afterward we splice
    the leading CFWS, if any, into the parsed sub-token.

    If neither an atom or a quoted-string is found before the next special, a
    HeaderParseError is raised.

    The token returned is either an Atom or a QuotedString, as appropriate.
    This means the 'word' level of the formal grammar is not represented in the
    parse tree; this is because having that extra layer when manipulating the
    parse tree is more confusing than it is helpful.

    rNz5Expected 'atom' or 'quoted-string' but found nothing.rz1Expected 'atom' or 'quoted-string' but found '{}')r8r9rr r:SPECIALSr1r<)rleaderr=rrrget_wordfs"rAcCst}zt|\}}||Wn(tjk
rH|jtdYnX|r|dtkr|ddkr|t|jt	d|dd}qJzt|\}}WnDtjk
r|dt
krt|\}}|jt	dnYnX||qJ||fS)a phrase = 1*word / obs-phrase
        obs-phrase = word *(word / "." / CFWS)

    This means a phrase can be a sequence of words, periods, and CFWS in any
    order as long as it starts with at least one word.  If anything other than
    words is detected, an ObsoleteHeaderDefect is added to the token's defect
    list.  We also accept a phrase that starts with CFWS followed by a dot;
    this is registered as an InvalidHeaderDefect, since it is not supported by
    even the obsolete grammar.

    zphrase does not start with wordrrzperiod in 'phrase'rNzcomment found without atom)r[rArnrr rrPHRASE_ENDSrObsoleteHeaderDefectr8r9)rr\r=rrr
get_phrases4



rDcCsvt}d}|dtkr"t|\}}|s6td|zt|\}}Wn^tjk
rzt|\}}Wn6tjk
r|ddkr|dtkrt	}YnXYnX|dk	r|g|dd<|
||r4|ddks|dtkr4tt||\}}|j
dkr|j
tdn|j
td||d<z|jdWn(tk
rl|j
td	YnX||fS)
z= local-part = dot-atom / quoted-string / obs-local-part

    Nrz"expected local-part but found '{}'rinvalid-obs-local-partz<local-part is not dot-atom, quoted-string, or obs-local-partz,local-part is not a dot-atom (contains CFWS)asciiz)local-part contains non-ASCII characters))rr8r9rr r1r>rArBrrnget_obs_local_partrrJrrrCrencoderZNonASCIILocalPartDefect)rrr@r=obs_local_partrrrget_local_partsJ
 


rJcCst}d}|r(|ddks*|dtkr(|ddkrj|rL|jtd|td}|dd}q
nD|ddkr|t|dd	|dd}|jtd
d}q
|r|djdkr|jtd
zt	|\}}d}Wn4tj
k
r|dtkr
t|\}}YnX||q
|djdksX|djdkrj|djdkrj|jtd|djdks|djdkr|djdkr|jtd|jrd|_||fS)z' obs-local-part = word *("." word)
    Frrrzinvalid repeated '.'TrNmisplaced-specialz/'\' character outside of quoted-string/ccontentrrzmissing '.' between wordsr_z!Invalid leading '.' in local partr(z"Invalid trailing '.' in local partrE)
rrBrrnrrrr
rJrAr r8r9)rrIZlast_non_ws_was_dotr=rrrrGsj 





rGcCs@t|d\}}}t|d}|r0|jtdt|||fS)a dtext = <printable ascii except \ [ ]> / obs-dtext
        obs-dtext = obs-NO-WS-CTL / quoted-pair

    We allow anything except the excluded characters, but if we find any
    ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is
    added to the token's defects list.  Quoted pairs are converted to their
    unquoted values, so what is returned is a ptext token, in this case a
    ValueTerminal.  If there were quoted-printables, an ObsoleteHeaderDefect is
    added to the returned token's defect list.

    z[]rz(quoted printable found in domain-literal)rr
rrnrrCr)rrrrrr	get_dtexts

rLcCs,|rdS|td|tdddS)NFz"end of input inside domain-literal]domain-literal-endT)rnrrr
)rdomain_literalrrr_check_for_early_dl_endsrPcCsjt}|dtkr(t|\}}|||s6td|ddkrRtd||dd}t||rp||fS|tdd|dt	krt
|\}}||t|\}}||t||r||fS|dt	krt
|\}}||t||r||fS|ddkrtd	||tdd
|dd}|rb|dtkrbt|\}}||||fS)zB domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]

    rzexpected domain-literal[z6expected '[' at start of domain-literal but found '{}'rNzdomain-literal-startrMz4expected ']' at end of domain-literal but found '{}'rN)rr8r9rnrr r1rPr
rrrL)rrOr=rrrget_domain_literal sH








rRcCsrt}d}|dtkr"t|\}}|s6td||ddkrvt|\}}|dk	rd|g|dd<||||fSzt|\}}Wn"tjk
rt	|\}}YnX|r|ddkrtd|dk	r|g|dd<|||rj|ddkrj|j
td|djd	kr*|d|dd<|rj|ddkrj|t
t	|d
d\}}||q*||fS)z] domain = dot-atom / domain-literal / obs-domain
        obs-domain = atom *("." atom))

    Nrzexpected domain but found '{}'rQrzInvalid Domainrz(domain is not a dot-atom (contains CFWS)rr)rr8r9rr r1rRrnr>r<rrCrJr)rrr@r=rrr
get_domainGsD




rScCs|t}t|\}}|||r,|ddkrF|jtd||fS|tddt|dd\}}||||fS)z( addr-spec = local-part "@" domain

    rrz#addr-spec local part with no domainaddress-at-symbolrN)rrJrnrrrr
rS)rrr=rrr
get_addr_specms


rUcCst}|rj|ddks"|dtkrj|dtkrFt|\}}||q|ddkr|t|dd}q|rz|ddkrtd||tt	|dd\}}|||r>|ddkr>|t|dd}|sq>|dtkrt|\}}|||ddkr|tt	|dd\}}||q|sNtd|ddkrltd	||t
dd
||ddfS)z obs-route = obs-domain-list ":"
        obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain])

        Returns an obs-route token with the appropriate sub-tokens (that is,
        there is no obs-domain-list in the parse tree).
    rrrNrz(expected obs-route domain but found '{}'z%end of header while parsing obs-route:z4expected ':' marking end of obs-route but found '{}'zend-of-obs-route-marker)rr8r9rn
ListSeparatorrr r1RouteComponentMarkerrSr
)rZ	obs_router=rrr
get_obs_route}sF






rYcCst}|dtkr(t|\}}|||r8|ddkrHtd||tdd|dd}|ddkr|tdd|jt	d	|dd}||fSzt
|\}}Wnztjk
r0z"t|\}}|jtd
Wn(tjk
rtd|YnX||t
|\}}YnX|||r^|ddkr^|dd}n|jt	d|tdd|r|dtkrt|\}}||||fS)
z angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
        obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]

    r<z"expected angle-addr but found '{}'zangle-addr-startrN>zangle-addr-endznull addr-spec in angle-addrz*obsolete route specification in angle-addrz.expected addr-spec or obs-route but found '{}'z"missing trailing '>' on angle-addr)
rr8r9rnrr r1r
rrrUrYrC)rZ
angle_addrr=rrrget_angle_addrsT








r\cCs<t}t|\}}||dd|jdd|_||fS)z display-name = phrase

    Because this is simply a name-rule, we don't return a display-name
    token containing a phrase, but rather a display-name token with
    the content of the phrase.

    N)rrDr;r)rrr=rrrget_display_names
r]cCst}d}|dtkr6t|\}}|s6td||ddkr|dtkr^td|t|\}}|s~td||dk	r|g|ddd<d}||t	|\}}|dk	r|g|dd<||||fS)z, name-addr = [display-name] angle-addr

    Nrz!expected name-addr but found '{}'rZ)
rr8r9rr r1rBr]rnr\)rZ	name_addrr@r=rrr
get_name_addrs6

r^cCst}zt|\}}WnNtjk
rdzt|\}}Wn&tjk
r^td|YnXYnXtdd|jDrd|_|	|||fS)z& mailbox = name-addr / addr-spec

    zexpected mailbox but found '{}'css|]}t|tjVqdSr)rrrr'rrrr*szget_mailbox.<locals>.<genexpr>r)
rr^rr rUr1anyr4rJrn)rrr=rrrget_mailboxs 
r`cCsdt}|r\|d|kr\|dtkrD|t|dd|dd}qt|\}}||q||fS)z Read everything up to one of the chars in endchars.

    This is outside the formal grammar.  The InvalidMailbox TokenList that is
    returned acts like a Mailbox, but the data attributes are None.

    rrKrN)rrBrnr
rD)rrZinvalid_mailboxr=rrrget_invalid_mailboxsracCst}|r|ddkrzt|\}}||Wntjk
r<d}|dtkrt|\}}|rv|ddkr|||jtdn@t	|d\}}|dk	r|g|dd<|||jt
dnb|ddkr|jtdnBt	|d\}}|dk	r|g|dd<|||jt
dYnX|r|ddkr|d}d	|_t	|d\}}|||jt
d|r|ddkr|t
|d
d}q||fS)aJ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
        obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])

    For this routine we go outside the formal grammar in order to improve error
    handling.  We recognize the end of the mailbox list only at the end of the
    value or at a ';' (the group terminator).  This is so that we can turn
    invalid mailboxes into InvalidMailbox tokens and continue parsing any
    remaining valid mailboxes.  We also allow all mailbox entries to be null,
    and this condition is handled appropriately at a higher level.

    r;Nz,;zempty element in mailbox-listzinvalid mailbox in mailbox-listrrrr)rr`rnrr r8r9rrCrarrJr;rW)rZmailbox_listr=r@rrrrget_mailbox_list(sX










rccCst}|s$|jtd||fSd}|r|dtkrt|\}}|sl|jtd||||fS|ddkr||||fSt|\}}t|j	dkr|dk	r|||
||jtd||fS|dk	r|g|dd<||||fS)zg group-list = mailbox-list / CFWS / obs-group-list
        obs-group-list = 1*([CFWS] ",") [CFWS]

    zend of header before group-listNrzend of header in group-listrbzgroup-list with empty entries)rrrnrrr8r9rcrrr;rC)rZ
group_listr@r=rrrget_group_listas>







rdcCs t}t|\}}|r"|ddkr2td||||tdd|dd}|r|ddkr|tdd||ddfSt|\}}|||s|jt	d	n|ddkrtd
||tdd|dd}|r|dt
krt|\}}||||fS)z7 group = display-name ":" [group-list] ";" [CFWS]

    rrVz8expected ':' at end of group display name but found '{}'zgroup-display-name-terminatorrNrbzgroup-terminatorzend of header in groupz)expected ';' at end of group but found {})rr]rr r1rnr
rdrrr8r9)rrr=rrr	get_groups8



recCsxt}zt|\}}WnNtjk
rdzt|\}}Wn&tjk
r^td|YnXYnX||||fS)a address = mailbox / group

    Note that counter-intuitively, an address can be either a single address or
    a list of addresses (a group).  This is why the returned Address object has
    a 'mailboxes' attribute which treats a single address as a list of length
    one.  When you need to differentiate between to two cases, extract the single
    element, which is either a mailbox or a group token.

    zexpected address but found '{}')rrerr r`r1rn)rrwr=rrrget_addresss
rfc
Cst}|rzt|\}}||Wn tjk
rH}zd}|dtkrt|\}}|rj|ddkr|||jtdnFt	|d\}}|dk	r|g|dd<|t
|g|jtdnh|ddkr|jtdnHt	|d\}}|dk	r|g|dd<|t
|g|jtdW5d}~XYnX|r|ddkr|dd}d|_t	|d\}}|
||jtd|r|t|d	d}q||fS)
a address_list = (address *("," address)) / obs-addr-list
        obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])

    We depart from the formal grammar here by continuing to parse until the end
    of the input, assuming the input to be entirely composed of an
    address-list.  This is always true in email parsing, and allows us
    to skip invalid addresses to parse additional valid ones.

    Nrrz"address-list entry with no contentzinvalid address in address-listzempty element in address-listrrr)rvrfrnrr r8r9rrCrarrrJr;rW)rZaddress_listr=errr@rrrrget_address_listsX









rhcCst}|std||ddkr6td||tdd|dd}t|\}}|||rx|ddkrtd	||tdd
||ddfS)z& no-fold-literal = "[" *dtext "]"
    z'expected no-fold-literal but found '{}'rrQz;expected '[' at the start of no-fold-literal but found '{}'zno-fold-literal-startrNrMz9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)rrr r1rnr
rL)rZno_fold_literalr=rrrget_no_fold_literals.
ricCst}|r,|dtkr,t|\}}|||r<|ddkrLtd||tdd|dd}zt|\}}Wn`tjk
rz"t	|\}}|j
tdWn&tjk
rtd|YnXYnX|||r|dd	kr@|j
td
|r8|ddkr8|tdd|dd}||fS|td	d
|dd}zt|\}}Wntjk
rzt
|\}}Wnrtjk
r}zPz"t|\}}|j
tdWn(tjk
rtd|YnXW5d}~XYnXYnX|||r6|ddkr6|dd}n|j
td|tdd|r|dtkrt|\}}||||fS)zmsg-id = [CFWS] "<" id-left '@' id-right  ">" [CFWS]
       id-left = dot-atom-text / obs-id-left
       id-right = dot-atom-text / no-fold-literal / obs-id-right
       no-fold-literal = "[" *dtext "]"
    rrZzexpected msg-id but found '{}'zmsg-id-startrNzobsolete id-left in msg-idz4expected dot-atom-text or obs-id-left but found '{}'rzmsg-id with no id-rightr[z
msg-id-endrTzobsolete id-right in msg-idzFexpected dot-atom-text, no-fold-literal or obs-id-right but found '{}'zmissing trailing '>' on msg-id)rr8r9rnrr r1r
r=rGrrCrrirS)rZmsg_idr=errr
get_msg_ids~






"


rkc
Cst}zt|\}}||WnLtjk
rl}z,t|}t|}|jtd	|W5d}~XYnX|r|jtd	||S)z2message-id      =   "Message-ID:" msg-id CRLF
    zInvalid msg-id: {!r}NzUnexpected {!r})
rrkrnrr r-rrrr1)rZ
message_idr=Zexrrrparse_message_idSs
rlcCst}|s |jtd|S|dtkrXt|\}}|||sX|jtdd}|r|ddkr|dtkr||d7}|dd}q\|s|jtd	||t
|d	nt||_|t
|d
|r|dtkrt|\}}|||r|ddkrT|jdk	r:|jtd|rP|t
|d	|S|t
dd|dd}|r|dtkrt|\}}|||s|jdk	r|jtd|Sd}|r|dtkr||d7}|dd}q|s*|jtd
	||t
|d	nt||_
|t
|d
|rn|dtkrnt|\}}|||r|jtd|t
|d	|S)zE mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]

    z%Missing MIME version number (eg: 1.0)rz0Expected MIME version number but found only CFWSr%rrNz1Expected MIME major version number but found {!r}rdigitsz0Incomplete MIME version; found only major numberzversion-separatorz1Expected MIME minor version number but found {!r}z'Excess non-CFWS text after MIME version)rrrnrHeaderMissingRequiredValuer8r9isdigitrr1r
intrr)rZmime_versionr=rmrrrparse_mime_versionos













rqcCsdt}|r\|ddkr\|dtkrD|t|dd|dd}qt|\}}||q||fS)z Read everything up to the next ';'.

    This is outside the formal grammar.  The InvalidParameter TokenList that is
    returned acts like a Parameter, but the data attributes are None.

    rrbrKrN)rrBrnr
rD)rZinvalid_parameterr=rrrget_invalid_parametersrrcCsNt|}|std||}|t|d}t|d}t|||fS)a8ttext = <matches _ttext_matcher>

    We allow any non-TOKEN_ENDS in ttext, but add defects to the token's
    defects list if we find non-ttext characters.  We also register defects for
    *any* non-printables even though the RFC doesn't exclude all of them,
    because we follow the spirit of RFC 5322.

    zexpected ttext but found '{}'Nttext)_non_token_end_matcherrr r1rrr
r)rr4rsrrr	get_ttexts	
rucCst}|r,|dtkr,t|\}}|||rL|dtkrLtd|t|\}}|||r|dtkrt|\}}||||fS)ztoken = [CFWS] 1*ttext [CFWS]

    The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or
    tspecials.  We also exclude tabs even though the RFC doesn't.

    The RFC implies the CFWS but is not explicit about it in the BNF.

    rexpected token but found '{}')	rbr8r9rn
TOKEN_ENDSrr r1ru)rZmtokenr=rrr	get_tokens	


rxcCsNt|}|std||}|t|d}t|d}t|||fS)aQattrtext = 1*(any non-ATTRIBUTE_ENDS character)

    We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the
    token's defects list if we find non-attrtext characters.  We also register
    defects for *any* non-printables even though the RFC doesn't exclude all of
    them, because we follow the spirit of RFC 5322.

    z expected attrtext but found {!r}Nr)_non_attribute_end_matcherrr r1rrr
rrr4rrrrget_attrtexts	
r{cCst}|r,|dtkr,t|\}}|||rL|dtkrLtd|t|\}}|||r|dtkrt|\}}||||fS)aH [CFWS] 1*attrtext [CFWS]

    This version of the BNF makes the CFWS explicit, and as usual we use a
    value terminal for the actual run of characters.  The RFC equivalent of
    attrtext is the token characters, with the subtraction of '*', "'", and '%'.
    We include tab in the excluded set just as we do for token.

    rrv)	rr8r9rnATTRIBUTE_ENDSrr r1r{rrr=rrr
get_attribute	s	


r~cCsNt|}|std||}|t|d}t|d}t|||fS)zattrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%')

    This is a special parsing routine so that we get a value that
    includes % escapes as a single string (which we decode as a single
    string later).

    z)expected extended attrtext but found {!r}Nextended-attrtext)#_non_extended_attribute_end_matcherrr r1rrr
rrzrrrget_extended_attrtext	s
rcCst}|r,|dtkr,t|\}}|||rL|dtkrLtd|t|\}}|||r|dtkrt|\}}||||fS)z [CFWS] 1*extended_attrtext [CFWS]

    This is like the non-extended version except we allow % characters, so that
    we can pick up an encoded value as a single string.

    rrv)	rr8r9rnEXTENDED_ATTRIBUTE_ENDSrr r1rr}rrrget_extended_attribute+	s


rcCst}|r|ddkr&td||tdd|dd}|rR|dsbtd|d}|r|dr||d7}|dd}qf|dd	kr|d	kr|jtd
t	||_
|t|d||fS)a6 '*' digits

    The formal BNF is more complicated because leading 0s are not allowed.  We
    check for that and add a defect.  We also assume no CFWS is allowed between
    the '*' and the digits, though the RFC is not crystal clear on that.
    The caller should already have dealt with leading CFWS.

    r*zExpected section but found {}zsection-markerrNz$Expected section number but found {}r%0z'section number has an invalid leading 0rm)rrr r1rnr
rorZInvalidHeaderErrorrpr)rrrmrrrget_sectionA	s,	

rcCst}|stdd}|dtkr0t|\}}|sDtd||ddkr^t|\}}nt|\}}|dk	r|g|dd<||||fS)z  quoted-string / attribute

    z&Expected value but found end of stringNrz Expected value but found only {}r)	rrr r8r9r1r:rrn)rvr@r=rrr	get_value_	s"

rcCst}t|\}}|||r,|ddkrL|jtd|||fS|ddkrz t|\}}d|_||Wntj	k
rYnX|st	d|ddkr|t
dd|dd	}d|_|dd
krt	d|t
d
d|dd	}d	}|r,|dtkr,t
|\}}||d	}|}|jrF|rF|dd
krFt|\}}|j}d}|jdkr|r|ddkrd}n$t|\}}	|	r|	ddkrd}n(zt|\}}	WnYnX|	sd}|r0|jtd|||D](}
|
jdkrg|
d	d	<|
}q*q|}nd	}|jtd|r`|ddkr`d	}nt|\}}|jr|jdkr|r|ddkr|||d	k	r|rt||}||fS|jtd|s
|jtd|||d	kr||fSn|d	k	rN|D]}
|
jdkrq2q|
jdk||
|
j|_|ddkrlt	d||t
dd|dd	}|r|ddkrt|\}}|||j|_|r|ddkrt	d||t
dd|dd	}|d	k	rrt}|rl|dtkr,t|\}}n2|dd
krRt
d
d}|dd	}nt|\}}||q
|}nt|\}}|||d	k	r|rt||}||fS)aY attribute [section] ["*"] [CFWS] "=" value

    The CFWS is implied by the RFC but not made explicit in the BNF.  This
    simplified form of the BNF from the RFC is made to conform with the RFC BNF
    through some extra checks.  We do it this way because it makes both error
    recovery and working with the resulting parse tree easier.
    rrbz)Parameter contains name ({}) but no valuerTzIncomplete parameterzextended-parameter-markerrN=zParameter not followed by '='parameter-separatorrF'z5Quoted string value for extended parameter is invalidrkzZParameter marked as extended but appears to have a quoted string value that is non-encodedzcApparent initial-extended-value but attribute was not marked as extended or was not initial sectionz(Missing required charset/lang delimitersrrz=Expected RFC2231 char/lang encoding delimiter, but found {!r}zRFC2231-delimiterz;Expected RFC2231 char/lang encoding delimiter, but found {}ZDQUOTE)rr~rnrrrr1rrr r
rr8r9r:rrrr{rrJrAssertionErrorrrfrgrrrr1)rrr=r@rZappendtoZqstringZinner_valueZ
semi_validr%trrrr
get_parameteru	s























rc
Csjt}|rfzt|\}}||Wntjk
r}zd}|dtkrVt|\}}|sp|||WYxS|ddkr|dk	r|||jtdn@t	|\}}|r|g|dd<|||jtd
|W5d}~XYnX|rD|ddkrD|d}d|_t	|\}}|||jtd
||r|t
dd	|d
d}q|S)a! parameter *( ";" parameter )

    That BNF is meant to indicate this routine should only be called after
    finding and handling the leading ';'.  There is no corresponding rule in
    the formal RFC grammar, but it is more convenient for us for the set of
    parameters to be treated as its own TokenList.

    This is 'parse' routine because it consumes the remaining value, but it
    would never be called to parse a full header.  Instead it is called to
    parse everything after the non-parameter value of a specific MIME header.

    Nrrbzparameter entry with no contentzinvalid parameter {!r}rrz)parameter with invalid trailing text {!r}rr)rrrnrr r8r9rrrrr1rJr;r
)rZmime_parametersr=rgr@rrrrparse_mime_parameters
sJ







rcCs|rV|ddkrV|dtkr>|t|dd|dd}qt|\}}||q|s^dS|tdd|t|dddS)zBDo our best to find the parameters in an invalid MIME header

    rrbrKrNr)rBrnr
rDr)Z	tokenlistrr=rrr_find_mime_parameters7
src
Cst}d}|s$|jtd|Szt|\}}Wn<tjk
rp|jtd|t	|||YSX|||r|ddkr|jtd|rt	|||S|j
|_
|tdd|dd	}zt|\}}Wn>tjk
r*|jtd
|t	|||YSX|||j
|_|sP|S|ddkr|jtd||`
|`t	|||S|tdd
|t|dd	|S)z maintype "/" subtype *( ";" parameter )

    The maintype and substype are tokens.  Theoretically they could
    be checked against the official IANA list + x-token, but we
    don't do that.
    Fz"Missing content type specificationz(Expected content maintype but found {!r}rrzInvalid content typezcontent-type-separatorrNz'Expected content subtype but found {!r}rbz<Only parameters are valid after content type, but found {!r}r)rrrnrrnrxr rr1rrrlowerrr
rr)rZctypeZrecoverr=rrrparse_content_type_headerG
sd












rc
Cst}|s |jtd|Szt|\}}Wn<tjk
rl|jtd|t	|||YSX|||j
|_
|s|S|ddkr|jtd|t	|||S|tdd|t|dd|S)	z* disposition-type *( ";" parameter )

    zMissing content dispositionz+Expected content disposition but found {!r}rrbzCOnly parameters are valid after content disposition, but found {!r}rrN)rrrnrrnrxr rr1rrrrrr
r)rZdisp_headerr=rrr parse_content_disposition_header
s:






rc
Cst}|s |jtd|Szt|\}}Wn.tjk
r^|jtd|YnX|||j	
|_|s|S|r|jtd|dt
kr|t|dd|dd}qt|\}}||q|S)z mechanism

    z!Missing content transfer encodingz1Expected content transfer encoding but found {!r}z*Extra text after content transfer encodingrrKrN)rrrnrrnrxr rr1rrrrerBr
rD)rZ
cte_headerr=rrr&parse_content_transfer_encoding_header
s4



rcCsDd}|r@|dr@|ddtkr@|dd}|ddd|d<|S)Nr%rr)linesZwsprrr_steal_trailing_WSP_if_exists
s
rcCs|jp
tj}|jrdnd}dg}d}d}d}tdd}t|}	|	r|	d}
|
|kr`|d8}q>t|
}|s|
jd	krt	
|}nt
|}z|||}Wn6t
k
rtd
d|
jDrd}nd}d
}YnX|
jdkrt|
|||q>|r|s|
js~d}d}|
jr~|
j|ddt|j}
|j|
kr~t|
|t|dkrlt|}|||d|
7<q>t|
dst|
|	}	d}q>n,|
jrt|||||
j|}d}q>nd}d}t||t|dkr|d|7<q>|
jr<t|d|kr<t|}|s(|
r<|||d}q>t|
dst|
}|
jdkrtdd	gdd|Dtdd	g}|
js|d7}||||	}	q>|
jr|s|	d|
d
}q>t|}|s|
r|||q>|d|7<q>|j||jS)zLReturn string of contents of parse_tree folded according to RFC rules.

    utf-8rr%NrFwrap_as_ew_blockedrrcss|]}t|tjVqdSr)rrrr'rrrr*
sz%_refold_parse_tree.<locals>.<genexpr>unknown-8bitTrr>rrHrUrcSs(g|] }|jdkr tt|dn|qS)r)rJr
r)r(prrrrW7sz&_refold_parse_tree.<locals>.<listcomp>r)Zmax_line_lengthsysmaxsizeutf8rrrrrJ
SPECIALSNL
isdisjointNLSETrHrr_r4_fold_mime_parametersr8rNrBrrrrnrK_fold_as_ewrOr7r
insertr,)Z
parse_treer?maxlenrrlast_ewrZ
want_encodingZend_ew_not_allowedrr9tstrrfZencoded_partnewlineZnewpartsrrrr@
s










r@cCs|dk	r<|r<tt|d|d|}|dd||d<|dtkr|d}|dd}t|d|krz|t||d|7<d}|dtkr|d}|dd}|dkrt|dn|}|dkrdn|}	t|	d}
|
d|krtd	|r|t|d}||
}|dkr,|d
q|d|}
tj	|
|	d}t||}|dkr|
dd}
tj	|
|	d}t||}qR|d|7<|t|
d}|r|d
t|d}q|d|7<|r|SdS)aFold string to_encode into lines as encoded word, combining if allowed.
    Return the new value for last_ew, or None if ew_combine_allowed is False.

    If there is already an encoded word in the last line of lines (indicated by
    a non-None value for last_ew) and ew_combine_allowed is true, decode the
    existing ew, combine it with to_encode, and re-encode.  Otherwise, encode
    to_encode.  In either case, split to_encode as necessary so that the
    encoded segments fit within maxlen.

    Nrrrr%rrz3max_line_length is too small to fit an encoded wordrT)rf)
rr-rrrnrrr r"rH)Z	to_encoderrrrOrfZleading_wspZtrailing_wspZnew_last_ewZ	encode_as
chrome_lenZremaining_spaceZ
text_spaceZto_encode_wordZencoded_wordZexcessrrrrOsT



rc	Cs|jD]\}}|dds2|dd7<|}d}z||d}Wn0tk
r|d}t|rtd}d}nd}YnX|rtjj	|d	|d
}	d
|||	}
nd
|t|}
t|dt|
d
|kr|dd|
|d<qn"t|
d|kr
|
d|
qd}|d}|rt|tt|dt|}
||
dkrLd}||
d}}|d|}tjj	|d	|d
}	t|	|krq|d
8}q\|
d
||||	d	}|d
7}||d}|r|dd7<qqdS)a>Fold TokenList 'part' into the 'lines' list as mime parameters.

    Using the decoded list of parameters and values, format them according to
    the RFC rules, including using RFC2231 encoding if the value cannot be
    expressed in 'encoding' and/or the parameter+value is too long to fit
    within 'maxlen'.

    rrbstrictFTrrrr%)Zsaferz
{}*={}''{}rrrTrrz''rNNz {}*{}*={}{})rrrrHrrrrrrur1rrrnr)r9rrrrrrfZ
error_handlerZencoding_requiredZ
encoded_valuerrZextra_chromerZ
splitpointZmaxcharspartialrrrrsn


 r)r
rerrstringroperatorrZemailrr"rrrrr8r?r;rrBZ	TSPECIALSrwZ	ASPECIALSr|rrrrrcompileVERBOSE	MULTILINEr)rrrRrXr[r]r^r`rbrcrhrsrtrvrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
rr rrrWr8rNrXr1r,rrrmatchr3findallrrtryrrrrr'r-r0r1r5r6r7r9r:r<r=r>rArDrJrGrLrPrRrSrUrYr\r]r^r`rarcrdrerfrhrirkrlrqrrrurxr{r~rrrrrrrrrrrr@rrrrrr<module>s8E
C"	
!*$
V	+






1C+
"&'/'&).9%7ED49/{A