a XC?h @sdZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z e dZee d BZe d ZeeBZee d Zee d Zee d Be d ZeeBZee 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<dd>e"Z5Gd?d@d@e"Z6GdAdBdBe"Z7GdCdDdDe"Z8GdEdFdFe"Z9GdGdHdHe"Z:GdIdJdJe"Z;GdKdLdLe"ZGdQdRdRe"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~e jVZWeTd dZXeTddZYeTddZZed[d\ej]Z^ed[e_d\ej`ZaedjbZced[e_d\ej`Zded[e_d\ej`Zeed[e_d\ej`ZfddZgddZhddZidddZjddZkddZlddZmddZnddZoddZpddZqddZrddZsddZtddZuddZvddZwddZxddZyddZzddZ{ddZ|ddZ}ddZ~ddZddZddZddZdd„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*'%%  cCst|ddddS)z;Escape dquote and backslash for use within a quoted-string.\\\"z\")strreplacevaluer?/opt/alt/python39/lib64/python3.9/email/_header_value_parser.pymake_quoted_pairscsrcCst|}d|dS)Nr)r)rZescapedrrr quote_stringhsrz =\? # literal =? [^?]* # charset \? # literal ? [qQbB] # literal 'q' or 'b', case insensitive \? # literal ? .*? # encoded word \?= # literal ?= cseZdZdZdZdZfddZddZfddZe d d Z e d d Z d dZ e ddZ e ddZddZdddZdddZdddZZS) TokenListNTcstj|i|g|_dSN)super__init__defects)selfargskw __class__rrrszTokenList.__init__cCsddd|DS)Ncss|]}t|VqdSrr.0xrrr z$TokenList.__str__..joinrrrr__str__szTokenList.__str__csd|jjtSNz{}({})formatr __name__r__repr__r*rrrr0s zTokenList.__repr__cCsddd|DS)Nr!css|]}|jr|jVqdSrrr#rrrr&r'z"TokenList.value..r(r*rrrrszTokenList.valuecCstdd|D|jS)Ncss|] }|jVqdSr) all_defectsr#rrrr&r'z(TokenList.all_defects..)sumrr*rrrr1szTokenList.all_defectscCs |dSNr)startswith_fwsr*rrrr4szTokenList.startswith_fwscCstdd|DS)zATrue if all top level tokens of this part may be RFC2047 encoded.css|] }|jVqdSr) as_ew_allowed)r$partrrrr&r'z*TokenList.as_ew_allowed..)allr*rrrr5szTokenList.as_ew_allowedcCsg}|D]}||jq|Sr)extendcomments)rr9tokenrrrr9szTokenList.commentscCs t||dS)Npolicy)_refold_parse_treerr<rrrfoldszTokenList.foldr!cCst|j|ddS)Nindent)printppstrrrArrrpprintszTokenList.pprintcCsd|j|dS)Nr r@)r)_pprDrrrrCszTokenList.ppstrccszd||jj|jV|D]4}t|ds:|d|Vq||dEdHq|jrdd|j}nd}d||VdS)Nz{}{}/{}(rFz* !! invalid element in token list: {!r}z z Defects: {}r!z{}){})r.r r/ token_typehasattrrFr)rrAr:ZextrarrrrFs  z TokenList._pp)r!)r!)r!)r/ __module__ __qualname__rGsyntactic_breakew_combine_allowedrr+r0propertyrr1r4r5r9r?rErCrF __classcell__rrrrr}s&        rc@s$eZdZeddZeddZdS)WhiteSpaceTokenListcCsdSN rr*rrrrszWhiteSpaceTokenList.valuecCsdd|DS)NcSsg|]}|jdkr|jqS)comment)rGcontentr#rrr r'z0WhiteSpaceTokenList.comments..rr*rrrr9szWhiteSpaceTokenList.commentsN)r/rIrJrMrr9rrrrrOs rOc@seZdZdZdS)UnstructuredTokenList unstructuredNr/rIrJrGrrrrrUsrUc@seZdZdZdS)PhrasephraseNrWrrrrrXsrXc@seZdZdZdS)WordZwordNrWrrrrrZsrZc@seZdZdZdS)CFWSListcfwsNrWrrrrr[sr[c@seZdZdZdS)AtomatomNrWrrrrr]sr]c@seZdZdZdZdS)Tokenr:FN)r/rIrJrGZ encode_as_ewrrrrr_sr_c@seZdZdZdZdZdZdS) EncodedWord encoded-wordN)r/rIrJrGctecharsetlangrrrrr`sr`c@s4eZdZdZeddZeddZeddZdS) QuotedString quoted-stringcCs"|D]}|jdkr|jSqdSNbare-quoted-stringrGrrr%rrrrSs zQuotedString.contentcCs>g}|D]*}|jdkr&|t|q||jqd|S)Nrhr!)rGappendrrr))rresr%rrr quoted_values  zQuotedString.quoted_valuecCs"|D]}|jdkr|jSqdSrgrirr:rrrstripped_values zQuotedString.stripped_valueN)r/rIrJrGrMrSrmrorrrrres  rec@s$eZdZdZddZeddZdS)BareQuotedStringrhcCstddd|DS)Nr!css|]}t|VqdSrr"r#rrrr& r'z+BareQuotedString.__str__..)rr)r*rrrr+ szBareQuotedString.__str__cCsddd|DS)Nr!css|]}t|VqdSrr"r#rrrr&r'z)BareQuotedString.value..r(r*rrrr szBareQuotedString.valueN)r/rIrJrGr+rMrrrrrrpsrpc@s8eZdZdZddZddZeddZedd Zd S) CommentrRcs(dtdgfddDdgggS)Nr!rcsg|]}|qSr)quoter#r*rrrTr'z#Comment.__str__..))r)r2r*rr*rr+szComment.__str__cCs2|jdkrt|St|ddddddS)NrRr r rz\(rsz\))rGrr)rrrrrrrs z Comment.quotecCsddd|DS)Nr!css|]}t|VqdSrr"r#rrrr&%r'z"Comment.content..r(r*rrrrS#szComment.contentcCs|jgSr)rSr*rrrr9'szComment.commentsN) r/rIrJrGr+rrrMrSr9rrrrrqs rqc@s4eZdZdZeddZeddZeddZdS) AddressListz address-listcCsdd|DS)NcSsg|]}|jdkr|qS)addressrGr#rrrrT1r'z)AddressList.addresses..rr*rrr addresses/szAddressList.addressescCstdd|DgS)Ncss|]}|jdkr|jVqdSruNrG mailboxesr#rrrr&5s z(AddressList.mailboxes..r2r*rrrrz3s zAddressList.mailboxescCstdd|DgS)Ncss|]}|jdkr|jVqdSrxrG all_mailboxesr#rrrr&:s z,AddressList.all_mailboxes..r{r*rrrr}8s zAddressList.all_mailboxesN)r/rIrJrGrMrwrzr}rrrrrt+s  rtc@s4eZdZdZeddZeddZeddZdS) AddressrucCs|djdkr|djSdS)NrgrouprG display_namer*rrrrBszAddress.display_namecCs4|djdkr|dgS|djdkr*gS|djSNrmailboxinvalid-mailboxryr*rrrrzGs  zAddress.mailboxescCs:|djdkr|dgS|djdkr0|dgS|djSrr|r*rrrr}Os   zAddress.all_mailboxesN)r/rIrJrGrMrrzr}rrrrr~>s  r~c@s(eZdZdZeddZeddZdS) MailboxList mailbox-listcCsdd|DS)NcSsg|]}|jdkr|qS)rrvr#rrrrT]r'z)MailboxList.mailboxes..rr*rrrrz[szMailboxList.mailboxescCsdd|DS)NcSsg|]}|jdvr|qS))rrrvr#rrrrTas z-MailboxList.all_mailboxes..rr*rrrr}_szMailboxList.all_mailboxesNr/rIrJrGrMrzr}rrrrrWs  rc@s(eZdZdZeddZeddZdS) GroupList group-listcCs |r|djdkrgS|djSNrrryr*rrrrziszGroupList.mailboxescCs |r|djdkrgS|djSrr|r*rrrr}oszGroupList.all_mailboxesNrrrrrres  rc@s4eZdZdZeddZeddZeddZdS) GrouprcCs|djdkrgS|djSNrryr*rrrrzzszGroup.mailboxescCs|djdkrgS|djSrr|r*rrrr}szGroup.all_mailboxescCs |djSr3)rr*rrrrszGroup.display_nameN)r/rIrJrGrMrzr}rrrrrrvs  rc@sLeZdZdZeddZeddZeddZedd Zed d Z 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 r/rIrJrGrMrrrrrrrrrrs    rc@s@eZdZdZeddZeddZeddZedd Zd S) AngleAddrz angle-addrcCs"|D]}|jdkr|jSqdSN addr-spec)rGrrjrrrrs zAngleAddr.local_partcCs"|D]}|jdkr|jSqdSrrGrrjrrrrs zAngleAddr.domaincCs"|D]}|jdkr|jSqdS)N obs-route)rGdomainsrjrrrrs zAngleAddr.routecCs<|D]2}|jdkr|jr"|jSt|j|jSqdS)Nrz<>)rGrrrrjrrrrs   zAngleAddr.addr_specN) r/rIrJrGrMrrrrrrrrrs   rc@seZdZdZeddZdS)ObsRoutercCsdd|DS)NcSsg|]}|jdkr|jqSrrr#rrrrTr'z$ObsRoute.domains..rr*rrrrszObsRoute.domainsN)r/rIrJrGrMrrrrrrsrc@sLeZdZdZeddZeddZeddZedd Zed d Z d S) MailboxrcCs|djdkr|djSdSNrrrr*rrrrszMailbox.display_namecCs |djSr3rr*rrrrszMailbox.local_partcCs |djSr3rr*rrrrszMailbox.domaincCs|djdkr|djSdSr)rGrr*rrrrsz Mailbox.routecCs |djSr3rr*rrrrszMailbox.addr_specNrrrrrrs    rc@s,eZdZdZeddZeZZZZ dS)InvalidMailboxrcCsdSrrr*rrrrszInvalidMailbox.display_nameNrrrrrrs rcs(eZdZdZdZefddZZS)DomainrFcsdtjSNr!r)rrsplitr*rrrrsz Domain.domain)r/rIrJrGr5rMrrNrrrrrsrc@seZdZdZdS)DotAtomdot-atomNrWrrrrrsrc@seZdZdZdZdS) DotAtomTextz dot-atom-textTNr/rIrJrGr5rrrrrsrc@seZdZdZdZdS) NoFoldLiteralzno-fold-literalFNrrrrrr src@sDeZdZdZdZeddZeddZeddZed d Z d S) AddrSpecrFcCs |djSr3rr*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}|jdurH|d|jS|S)N@)setrr DOT_ATOM_ENDSrr)rZnamesetZlprrrr$s   zAddrSpec.addr_specN) r/rIrJrGr5rMrrrrrrrrrs   rc@seZdZdZdZdS) ObsLocalPartzobs-local-partFNrrrrrr0srcs4eZdZdZdZeddZefddZZS) DisplayNamez display-nameFcCst|}t|dkr|jS|djdkr4|dn*|ddjdkr^t|ddd|d<|djdkrv|n*|ddjdkrt|ddd|d<|jS)Nrr\rr)rrrrGpop)rrlrrrr;s   zDisplayName.display_namecsd}|jrd}n|D]}|jdkrd}qt|dkr|rd}}|djdks`|ddjdkrdd}|djdks|ddjdkrd}|t|j|StjSdS) NFTrfrr!r\rQr)rrGrrrrr)rrrr%ZpreZpostrrrrLs   zDisplayName.value) r/rIrJrGrLrMrrrNrrrrr6s  rc@s,eZdZdZdZeddZeddZdS) LocalPartz local-partFcCs&|djdkr|djS|djSdS)Nrrf)rGrmrr*rrrres 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)DOTrGr isinstancerkr)rrlZlastZ last_is_tltokZis_tlrrrrls(     zLocalPart.local_partN)r/rIrJrGr5rMrrrrrrr`s  rcs4eZdZdZdZefddZeddZZS) DomainLiteralzdomain-literalFcsdtjSrrr*rrrrszDomainLiteral.domaincCs"|D]}|jdkr|jSqdS)Nptextrirjrrrips zDomainLiteral.ip) r/rIrJrGr5rMrrrNrrrrrs rc@seZdZdZdZdZdS) MIMEVersionz mime-versionN)r/rIrJrGmajorminorrrrrrsrc@s4eZdZdZdZdZdZeddZeddZ dS) Parameter parameterFus-asciicCs|jr|djSdSr) sectionednumberr*rrrsection_numberszParameter.section_numbercCsf|D]\}|jdkr|jS|jdkr|D]4}|jdkr*|D] }|jdkr<|jSqrrrr?[sz MsgID.foldN)r/rIrJrGr5r?rrrrrWsrc@seZdZdZdS) MessageIDz message-idNrWrrrrr`src@seZdZdZdS)InvalidMessageIDzinvalid-message-idNrWrrrrrdsrc@seZdZdZdS)HeaderheaderNrWrrrrrhsrcsreZdZdZdZdZfddZfddZddZe dd Z dfd d Z d dZ e ddZ ddZZS)TerminalTcst||}||_g|_|Sr)r__new__rGr)clsrrGrrrrrvszTerminal.__new__csd|jjtSr,r-r*rrrr0|szTerminal.__repr__cCst|jjd|jdS)N/)rBr r/rGr*rrrrEszTerminal.pprintcCs t|jSr)listrr*rrrr1szTerminal.all_defectsr!c s2d||jj|jt|js"dn d|jgS)Nz {}{}/{}({}){}r!z {})r.r r/rGrr0rrDrrrrFsz Terminal._ppcCsdSrrr*rrrpop_trailing_wsszTerminal.pop_trailing_wscCsgSrrr*rrrr9szTerminal.commentscCst||jfSr)rrGr*rrr__getnewargs__szTerminal.__getnewargs__)r!)r/rIrJr5rLrKrr0rErMr1rFrr9rrNrrrrrps     rc@s eZdZeddZddZdS)WhiteSpaceTerminalcCsdSrPrr*rrrrszWhiteSpaceTerminal.valuecCsdS)NTrr*rrrr4sz!WhiteSpaceTerminal.startswith_fwsNr/rIrJrMrr4rrrrrs rc@s eZdZeddZddZdS) ValueTerminalcCs|Srrr*rrrrszValueTerminal.valuecCsdS)NFrr*rrrr4szValueTerminal.startswith_fwsNrrrrrrs rc@s eZdZeddZddZdS)EWWhiteSpaceTerminalcCsdSrrr*rrrrszEWWhiteSpaceTerminal.valuecCsdSrrr*rrrr+szEWWhiteSpaceTerminal.__str__N)r/rIrJrMrr+rrrrrs rc@seZdZdZdS)_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r/rIrJ__doc__rrrrrsrr,list-separatorrzroute-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_finderrrkrZNonPrintableDefectrrr)xtextZnon_printablesrrr_validate_xtexts  rcCst|d^}}g}d}d}tt|D]L}||dkrJ|rDd}d}nd}q&|rTd}n|||vrdq||||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_splitterrangerrkr))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 srvtextc Cst}|ds td||dddd^}}||ddkrXtd|d|}t|dkr|dtvr|dtvr| d dkr|dd^}}|d|}t|dkr|j t d ||_ d|}ztd|d\}}} } Wn(ttfy(td |j Yn0||_| |_|j | |r|dtvrpt|\} }| | qBt|d^} }t| |} t| | | d|}qB|r|dtvr|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: '{}'z.missing trailing whitespace after encoded-word)r` startswithrHeaderParseErrorr.rr)rrcountrrkrrb_ewr ValueErrorKeyErrorrrcrdr8WSPrrrr)rZ terminal_typeZewrrZremstrrestrrcrdrr:charsrrrrget_encoded_wordsd                r%cCsDt}|r@|dtvr0t|\}}||qd}|drzt|d\}}Wn(tyfd}YntjyxYnr0d}t |dkr|dj dkr|j t dd}|rt |d kr|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. rTrZutextFrrz&missing whitespace before encoded wordrrar!)rUr"rrkrr%rrrrrGrrrrrfc2047_matchersearch partitionrrr))rrVr:valid_ewZhave_wsrrrrrrget_unstructuredIsH           r+cCs*t|d\}}}t|d}t|||fS)actext = 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  r.cCs*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)rrrr,rrr get_qcontents  r/cCsNt|}|std||}|t|d}t|d}t|||fS)zatext = 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_matcherrrr.rrrr)rmr0rrr get_atexts r3cCsp|ddkrtd|t}|dd}|rT|ddkrTt|\}}|||r@|ddkr@|dtvrt|\}}n|dddkr(d}z&t|\}}|j t d d }Wn tjyt|\}}Yn0|r4t |dkr4|d j d kr4|d j dkr4t |d d |d <n t|\}}||qT|s`|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&raz"end of header inside quoted string)rrr.rpr/rkr"rr%rrrrGr)rZbare_quoted_stringr:r*rrrget_bare_quoted_stringsJ            r4cCs|r |ddkr td|t}|dd}|r|ddkr|dtvr\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 '{}'rNrszend of header inside comment) rrr.rqr"r get_commentr.rkrr)rrRr:rrrr5s&      r5cCsPt}|rH|dtvrH|dtvr0t|\}}n t|\}}||q||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS r)r[ CFWS_LEADERr"rr5rk)rr\r:rrrget_cfwss   r7cCspt}|r,|dtvr,t|\}}||t|\}}|||rh|dtvrht|\}}||||fS)zquoted-string = [CFWS] [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)rer6r7rkr4)rZ quoted_stringr:rrrget_quoted_string s      r8cCst}|r,|dtvr,t|\}}|||rL|dtvrLtd||drzt |\}}Wqtjyt |\}}Yq0n t |\}}|||r|dtvrt|\}}||||fS)zPatom = [CFWS] 1*atext [CFWS] An atom could be an rfc2047 encoded word. rzexpected atom but found '{}'r) r]r6r7rk ATOM_ENDSrrr.rr%r3)rr^r:rrrget_atoms&       r:cCst}|r|dtvr&td||rt|dtvrtt|\}}|||r&|ddkr&|t|dd}q&|dturtdd|||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 '{}')rr9rrr.r3rkr)rZ dot_atom_textr:rrrget_dot_atom_text:s     r;cCst}|dtvr(t|\}}|||drfzt|\}}Wqrtjybt|\}}Yqr0n t|\}}|||r|dtvrt|\}}||||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) rr6r7rkrr%rrr;)rZdot_atomr:rrr get_dot_atomMs        r<cCs|dtvrt|\}}nd}|s,td|ddkrFt|\}}n*|dtvrdtd|n t|\}}|dur|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 '{}')r6r7rrr8SPECIALSr.r:)rleaderr:rrrget_wordfs"    r?cCst}zt|\}}||Wn&tjyF|jtdYn0|r|dtvr|ddkr|t|jt d|dd}qHzt|\}}WnBtjy|dt vrt |\}}|jt dnYn0||qH||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) rXr?rkrrrr PHRASE_ENDSrObsoleteHeaderDefectr6r7)rrYr:rrr get_phrases4           rBc Cspt}d}|dtvr"t|\}}|s6td|zt|\}}WnZtjyzt|\}}Wn4tjy|ddkr|dtvrt }Yn0Yn0|dur|g|dd<| ||r0|ddks|dtvr0t t ||\}}|j dkr|j tdn|j td||d<z|jdWn&tyf|j td Yn0||fS) z= local-part = dot-atom / quoted-string / obs-local-part Nrz"expected local-part but found '{}'r invalid-obs-local-partzr:obs_local_partrrrget_local_partsJ         rHcCst}d}|r&|ddks*|dtvr&|ddkrj|rL|jtd|td}|dd}q nD|ddkr|t|dd |dd}|jtd d}q |r|d jd kr|jtd zt |\}}d}Wn2tj y|dt vrt |\}}Yn0||q |djd ksV|djdkrh|djd krh|jtd|d jd ks|d jdkr|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 partrC) rr@rrkrrrrrGr?rr6r7)rrGZlast_non_ws_was_dotr:rrrrEsj                  rEcCs@t|d\}}}t|d}|r0|jtdt|||fS)a dtext = / 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)rrrrkrrAr)rrrrrr get_dtexts   rJcCs,|rdS|td|tdddS)NFz"end of input inside domain-literal]domain-literal-endT)rkrrr)rdomain_literalrrr_check_for_early_dl_endsrNcCsjt}|dtvr(t|\}}|||s6td|ddkrRtd||dd}t||rp||fS|tdd|dt vrt |\}}||t |\}}||t||r||fS|dt vrt |\}}||t||r||fS|ddkrtd ||tdd |dd}|rb|dtvrbt|\}}||||fS) zB domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] rzexpected domain-literal[z6expected '[' at start of domain-literal but found '{}'rNzdomain-literal-startrKz4expected ']' at end of domain-literal but found '{}'rL) rr6r7rkrrr.rNrr"rrJ)rrMr:rrrget_domain_literal sH                    rPcCspt}d}|dtvr"t|\}}|s6td||ddkrvt|\}}|durd|g|dd<||||fSzt|\}}Wn tjyt |\}}Yn0|r|ddkrtd|dur|g|dd<|||rh|ddkrh|j t d|dj d kr(|d|dd<|rh|ddkrh|t t |d d\}}||q(||fS) z] domain = dot-atom / domain-literal / obs-domain obs-domain = atom *("." atom)) Nrzexpected domain but found '{}'rOrzInvalid Domainrz(domain is not a dot-atom (contains CFWS)rr)rr6r7rrr.rPrkr<r:rrArGr)rrr>r:rrr get_domainGsD         rQcCs|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)rrHrkrrrrrQ)rrr:rrr get_addr_specms    rScCst}|rj|ddks"|dtvrj|dtvrFt|\}}||q|ddkr|t|dd}q|rz|ddkrtd||tt |dd\}}|||r>|ddkr>|t|dd}|sq>|dtvrt|\}}|||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). rr rNrz(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) rr6r7rk ListSeparatorrrr.RouteComponentMarkerrQr)rZ obs_router:rrr get_obs_route}sF               rWc Cst}|dtvr(t|\}}|||r8|ddkrHtd||tdd|dd}|ddkr|tdd|jt d |dd}||fSzt |\}}Wnvtjy,z"t |\}}|jt d Wn&tjytd |Yn0||t |\}}Yn0|||rZ|ddkrZ|dd}n|jt d |tdd|r|dtvrt|\}}||||fS) z angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] rzangle-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) rr6r7rkrrr.rrrrSrWrA)rZ angle_addrr:rrrget_angle_addrsT                rZcCs<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)rrBr8r)rrr:rrrget_display_names  r[cCst}d}|dtvr6t|\}}|s6td||ddkr|dtvr^td|t|\}}|s~td||dur|g|ddd<d}||t |\}}|dur|g|dd<||||fS)z, name-addr = [display-name] angle-addr Nrz!expected name-addr but found '{}'rX) rr6r7rrr.r@r[rkrZ)rZ name_addrr>r:rrr get_name_addrs6        r\c Cst}zt|\}}WnJtjy`zt|\}}Wn$tjyZtd|Yn0Yn0tdd|jDr|d|_| |||fS)z& mailbox = name-addr / addr-spec zexpected mailbox but found '{}'css|]}t|tjVqdSr)rrrr#rrrr&szget_mailbox..r) rr\rrrSr.anyr1rGrk)rrr:rrr get_mailboxs  r^cCsdt}|r\|d|vr\|dtvrD|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. rrIrN)rr@rkrrB)rrZinvalid_mailboxr:rrrget_invalid_mailboxs    r_cCst}|r|ddkrzt|\}}||Wntjy:d}|dtvrt|\}}|rt|ddvr|||jtdn@t |d\}}|dur|g|dd<|||jt dnb|ddkr|jtdnBt |d\}}|dur|g|dd<|||jt dYn0|r|ddvr|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-listr rrr)rr^rkrrr6r7rrAr_rrGr8rU)rZ mailbox_listr:r>rrrrget_mailbox_list(sX                 racCst}|s$|jtd||fSd}|r|dtvrt|\}}|sl|jtd||||fS|ddkr||||fSt|\}}t|j dkr|dur||| ||jt d||fS|dur|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-listr`zgroup-list with empty entries) rrrkrrr6r7rarr}r8rA)rZ group_listr>r:rrrget_group_listas>           rbcCs t}t|\}}|r"|ddkr2td||||tdd|dd}|r|ddkr|tdd||ddfSt|\}}|||s|jt d n|ddkrtd ||tdd|dd}|r|dt vrt |\}}||||fS) z7 group = display-name ":" [group-list] ";" [CFWS] rrTz8expected ':' at end of group display name but found '{}'zgroup-display-name-terminatorrNr`zgroup-terminatorzend of header in groupz)expected ';' at end of group but found {}) rr[rrr.rkrrbrrr6r7)rrr:rrr get_groups8          rcc Cstt}zt|\}}WnJtjy`zt|\}}Wn$tjyZtd|Yn0Yn0||||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 '{}')r~rcrrr^r.rk)rrur:rrr get_addresss rdc Cst}|rzt|\}}||Wn$tjyL}zd}|dtvrt|\}}|rj|ddkr|||jtdnFt |d\}}|dur|g|dd<|t |g|jt dnh|ddkr|jtdnHt |d\}}|dur|g|dd<|t |g|jt dWYd}~n d}~00|r|ddkr|dd}d|_ t |d\}}| ||jt d|r|tdd |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. Nrr z"address-list entry with no contentzinvalid address in address-listzempty element in address-listrrr r)rtrdrkrrr6r7rrAr_r~rrGr8r)rZ address_listr:errr>rrrrget_address_listsX              rfcCst}|std||ddkr6td||tdd|dd}t|\}}|||rx|ddkrtd ||tdd ||ddfS) z& no-fold-literal = "[" *dtext "]" z'expected no-fold-literal but found '{}'rrOz;expected '[' at the start of no-fold-literal but found '{}'zno-fold-literal-startrNrKz9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)rrrr.rkrrJ)rZno_fold_literalr:rrrget_no_fold_literals.    rgcCst}|r,|dtvr,t|\}}|||r<|ddkrLtd||tdd|dd}zt|\}}Wn\tjyz"t |\}}|j t dWn$tjytd|Yn0Yn0|||r|dd kr<|j t d |r4|dd kr4|td d |dd}||fS|td d |dd}zt|\}}Wntjyzt |\}}Wnrtjy}zVz"t|\}}|j t dWn&tjytd|Yn0WYd}~n d}~00Yn0|||r0|dd kr0|dd}n|j t d|td d |r||dtvr|t|\}}||||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 "]" rrXzexpected 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-rightrYz msg-id-endrRzobsolete id-right in msg-idzFexpected dot-atom-text, no-fold-literal or obs-id-right but found '{}'zmissing trailing '>' on msg-id)rr6r7rkrrr.rr;rErrArrgrQ)rZmsg_idr:errr get_msg_ids~             &    ric Cst}zt|\}}||WnNtjyn}z4t|}t|}|jtd |WYd}~n&d}~00|r|jtd ||S)z2message-id = "Message-ID:" msg-id CRLF zInvalid msg-id: {!r}NzUnexpected {!r}) rrirkrrr+rrrr.)rZ message_idr:Zexrrrparse_message_idSs  rjcCst}|s |jtd|S|dtvrXt|\}}|||sX|jtdd}|r|ddkr|dtvr||d7}|dd}q\|s|jtd ||t |d nt ||_ |t |d |r|dtvrt|\}}|||r|ddkrT|j dur:|jtd |rP|t |d |S|t dd |dd}|r|dtvrt|\}}|||s|j dur|jtd |Sd}|r|dtvr||d7}|dd}q|s*|jtd ||t |d nt ||_ |t |d |rn|dtvrnt|\}}|||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}r digitsz0Incomplete MIME version; found only major numberzversion-separatorz1Expected MIME minor version number but found {!r}z'Excess non-CFWS text after MIME version)rrrkrHeaderMissingRequiredValuer6r7isdigitrr.rintrr)rZ mime_versionr:rkrrrparse_mime_versionos                        rocCsdt}|r\|ddkr\|dtvrD|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. rr`rIrN)rr@rkrrB)rZinvalid_parameterr:rrrget_invalid_parameters    rpcCsNt|}|std||}|t|d}t|d}t|||fS)a8ttext = 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_matcherrrr.rrrr)rr2rqrrr get_ttexts  rscCst}|r,|dtvr,t|\}}|||rL|dtvrLtd|t|\}}|||r|dtvrt|\}}||||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 '{}') r_r6r7rk TOKEN_ENDSrrr.rs)rZmtokenr:rrr get_tokens       rvcCsNt|}|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_matcherrrr.rrrrrr2rrrr get_attrtexts  rycCst}|r,|dtvr,t|\}}|||rL|dtvrLtd|t|\}}|||r|dtvrt|\}}||||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. rrt) rr6r7rkATTRIBUTE_ENDSrrr.ryrrr: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_matcherrrr.rrrrrxrrrget_extended_attrtext s rcCst}|r,|dtvr,t|\}}|||rL|dtvrLtd|t|\}}|||r|dtvrt|\}}||||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. rrt) rr6r7rkEXTENDED_ATTRIBUTE_ENDSrrr.rr{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 0rk) rrrr.rkrrmrZInvalidHeaderErrorrnr)rrrkrrr get_sectionA s,     rcCst}|stdd}|dtvr0t|\}}|sDtd||ddkr^t|\}}n t|\}}|dur|g|dd<||||fS)z quoted-string / attribute z&Expected value but found end of stringNrz Expected value but found only {}r) rrrr6r7r.r8rrk)rvr>r:rrr get_value_ s"      rc Cst}t|\}}|||r,|ddkrL|jtd|||fS|ddkrz t|\}}d|_||Wntj yYn0|st d|ddkr|t dd|dd }d|_ |dd krt d |t d d |dd }d }|r*|dt vr*t |\}}||d }|}|j rD|rD|dd krDt|\}}|j}d}|jdkr|r|ddkrd}n$t|\}} | r| ddkrd}n(zt|\}} Wn Yn 0| sd}|r.|jtd|||D](} | jdkrg| d d <| }q(q|}nd }|jtd|r^|ddkr^d }n t|\}}|j r~|jdkr|r|ddkr|||d ur|}||fS|jtd|s|jtd|||d ur||fSn|d ur>|D]} | jdkrq"q| jdk|| | j|_|ddkr\t d||t dd|dd }|r|ddkrt|\}}|||j|_|r|ddkrt d||t dd|dd }|d urbt} |r\|dtvrt|\}}n2|dd krBt d d}|dd }n t|\}}| |q| }n t|\}}|||d ur|}||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. rr`z)Parameter contains name ({}) but no valuerTzIncomplete parameterzextended-parameter-markerrN=zParameter not followed by '='parameter-separatorrF'z5Quoted string value for extended parameter is invalidrhzZParameter 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 delimitersr}rz=Expected RFC2231 char/lang encoding delimiter, but found {!r}zRFC2231-delimiterz;Expected RFC2231 char/lang encoding delimiter, but found {}ZDQUOTE)rr|rkrrrr.rrrrrr6r7r8rorryrrGrrrcrdrr"rr/) rrr:r>rZappendtoZqstringZ inner_valueZ semi_validr#trrrr get_parameteru s                                             rc Cspt}|rlzt|\}}||Wntjy}zd}|dtvrTt|\}}|sr|||WYd}~S|ddkr|dur|||jtdn@t |\}}|r|g|dd<|||jtd |WYd}~n d}~00|rJ|ddkrJ|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. Nrr`zparameter entry with no contentzinvalid parameter {!r}rrz)parameter with invalid trailing text {!r}rr)rrrkrrr6r7rrrpr.rGr8r)rZmime_parametersr:rer>rrrrparse_mime_parameters sJ              rcCs|rV|ddkrV|dtvr>|t|dd|dd}qt|\}}||q|s^dS|tdd|t|dddS)zBDo our best to find the parameters in an invalid MIME header rr`rIrNr)r@rkrrBr)Z tokenlistrr:rrr_find_mime_parameters7 s   rc Cst}d}|s$|jtd|Szt|\}}Wn:tjyn|jtd|t |||YS0|||r|ddkr|jtd|rt |||S|j |_ |tdd|dd }zt|\}}Wn<tjy&|jtd |t |||YS0|||j |_|sL|S|dd kr|jtd ||` |`t |||S|td d |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}r`zt| } |s| jd vrt |  }n t |  }z| ||} Wn4t ytd d | jDrd } nd} d }Yn0| jdkrt| |||q>|r|s| js|d}d}| jr|| j|ddt|j } |j| vr|t| |t|dkrjt|}|||d| 7<q>t| dst| | } nt| |||| j| }d}q>t| |t|dkr|d| 7<q>| jr"t| d|kr"t|}|s| r"||| d}q>t| dst| }| jdkrhtddgdd|Dtddg}| 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_blockedr)rrcss|]}t|tjVqdSr)rrrr#rrrr& sz%_refold_parse_tree.. unknown-8bitTrr;rrFrhrrcSsg|]}tt|dqS)r)rr)r$prrrrT1 sz&_refold_parse_tree..)Zmax_line_lengthsysmaxsizeutf8rrrrrG SPECIALSNL isdisjointNLSETrFrr]r1_fold_mime_parametersr5rKr?rrrrkrH _fold_as_ewrLr4rinsertr))Z parse_treer<maxlenrrlast_ewrZ want_encodingZend_ew_not_allowedrr6tstrrcZ encoded_partnewlineZnewpartsrrrr= s                    r=cCs|dur<|rFold 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'. rr`strictFTrrrr!)Zsaferz {}*={}''{}rrrQrrz''rNNz {}*{}*={}{})rrrrFrrrrrrrr.rrrkr)r6rrrrrrcZ error_handlerZencoding_requiredZ encoded_valuerrZ extra_chromerZ splitpointZmaxcharspartialrrrr s`        r)r)r rerrstringroperatorrZemailrrrrrr"r6r=r9rr@Z TSPECIALSruZ ASPECIALSrzrrrrrcompileVERBOSE MULTILINEr'rrrOrUrXrZr[r]r_r`rerprqrtr~rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrUrVr.r)rrrmatchr1findallr rrrwr~rrrr%r+r.r/r3r4r5r7r8r:r;r<r?rBrHrErJrNrPrQrSrWrZr[r\r^r_rarbrcrdrfrgrirjrorprsrvryr|rrrrrrrrrrrr=rrrrrrs4E           C  "   !*$ V +         1C+ "&'/'&).9%7ED49/tA