o 0iҧ @sdZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z e dZee d BZe d ZeeBZee d Zee d Zee d Be d ZeeBZee dBZeeBZee dZddhZeeBZddZddZddZedejej BZ!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#ZBGdYdZdZe#ZCGd[d\d\eCZDGd]d^d^e#ZEGd_d`d`e#ZFGdadbdbe#ZGGdcdddde#ZHGdedfdfe#ZIGdgdhdheIZJGdidjdjeIZKGdkdldle#ZLGdmdndne#ZMGdodpdpe#ZNGdqdrdreNZOGdsdtdteOZPGdudvdve#ZQGdwdxdxeRZSGdydzdzeSZTGd{d|d|eSZUGd}d~d~eTZVGddde jWZXeUd dZYeUddZZeUddZ[ed\d]ej^Z_ed\e`d]ejaZbedjcZded\e`d]ejaZeed\e`d]ejaZfed\e`d]ejaZgddZhddZiddZjdddZkddZlddZmddZnddZoddZpddZqddZrddZsddZtddZuddZvddZwddZxddZyddZzddZ{ddZ|ddZ}ddZ~ddZddZddZddZdd„ZddĄZddƄZddȄZddʄZdd̄Zdd΄ZddЄZdd҄ZddԄZddքZdd؄ZddڄZdd܄ZddބZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZddZdS(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\"strreplacevaluerA/opt/alt/python310/lib64/python3.10/email/_header_value_parser.pymake_quoted_pairscsrcCs t|ddddddS)z:Escape parenthesis and backslash for use within a comment.r r r\()\)rrrrrmake_parenthesis_pairshsrcCst|}d|dS)Nr)r)rZescapedrrr quote_stringns rz =\? # 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__rrrs zTokenList.__init__cCddd|DS)Ncs|]}t|VqdSrr.0xrrr z$TokenList.__str__..joinr!rrr__str__zTokenList.__str__cd|jjtSNz{}({})formatr%__name__r__repr__r1r$rrr9s zTokenList.__repr__cCr&)Nr'css|] }|jr|jVqdSrrr*rrrr-sz"TokenList.value..r/r1rrrrzTokenList.valuecCstdd|D|jS)Ncs|]}|jVqdSr) all_defectsr*rrrr-z(TokenList.all_defects..)sumr r1rrrr<szTokenList.all_defectscCs |dSNr)startswith_fwsr1rrrr@ zTokenList.startswith_fwscCstdd|DS)zATrue if all top level tokens of this part may be RFC2047 encoded.csr;r) as_ew_allowed)r+partrrrr-r=z*TokenList.as_ew_allowed..)allr1rrrrBszTokenList.as_ew_allowedcCsg}|D]}||jq|Sr)extendcomments)r!rFtokenrrrrFszTokenList.commentscCs t||dS)Npolicy)_refold_parse_treer!rIrrrfoldrAzTokenList.foldr'cCst|j|ddS)Nindent)printppstrr!rNrrrpprintr3zTokenList.pprintcCsd|j|dS)Nr rM)r0_pprQrrrrPszTokenList.ppstrccs|d||jj|jV|D]}t|ds|d|Vq||dEdHq|jr3d|j}nd}d||VdS)Nz{}{}/{}(rSz* !! invalid element in token list: {!r}z z Defects: {}r'z{}){})r7r%r8 token_typehasattrrSr )r!rNrGZextrarrrrSs  z TokenList._ppr')r8 __module__ __qualname__rTsyntactic_breakew_combine_allowedrr2r9propertyrr<r@rBrFrLrRrPrS __classcell__rrr$rrs(        rc@s$eZdZeddZeddZdS)WhiteSpaceTokenListcCdSN rr1rrrrzWhiteSpaceTokenList.valuecCdd|DS)NcSg|] }|jdkr|jqS)comment)rTcontentr*rrr z0WhiteSpaceTokenList.comments..rr1rrrrFzWhiteSpaceTokenList.commentsN)r8rWrXr[rrFrrrrr]s  r]c@eZdZdZdS)UnstructuredTokenList unstructuredNr8rWrXrTrrrrrjrjc@ri)PhrasephraseNrlrrrrrnrmrnc@ri)WordZwordNrlrrrrrprmrpc@ri)CFWSListcfwsNrlrrrrrqrmrqc@ri)AtomatomNrlrrrrrsrmrsc@eZdZdZdZdS)TokenrGFN)r8rWrXrTZ encode_as_ewrrrrrvrvc@seZdZdZdZdZdZdS) EncodedWord encoded-wordN)r8rWrXrTctecharsetlangrrrrrx rxc@4eZdZdZeddZeddZeddZdS) QuotedString quoted-stringcC"|D] }|jdkr|jSqdSNbare-quoted-stringrTrr!r,rrrre   zQuotedString.contentcCs>g}|D]}|jdkr|t|q||jqd|S)Nrr')rTappendrrr0)r!resr,rrr quoted_values   zQuotedString.quoted_valuecCrrrr!rGrrrstripped_valuerzQuotedString.stripped_valueN)r8rWrXrTr[rerrrrrrrs   rc@s$eZdZdZddZeddZdS)BareQuotedStringrcCstddd|DS)Nr'csr(rr)r*rrrr-r.z+BareQuotedString.__str__..)rr0r1rrrr2szBareQuotedString.__str__cCr&)Nr'csr(rr)r*rrrr-r.z)BareQuotedString.value..r/r1rrrrr:zBareQuotedString.valueN)r8rWrXrTr2r[rrrrrr s rc@s8eZdZdZddZddZeddZedd Zd S) Commentrdcs(dtdgfddDdgggS)Nr'rcsg|]}|qSr)quoter*r1rrrfsz#Comment.__str__..r)r0r>r1rr1rr2szComment.__str__cCs2|jdkr t|St|ddddddS)Nrdr r rrrr)rTrr)r!rrrrr"s z Comment.quotecCr&)Nr'csr(rr)r*rrrr-+r.z"Comment.content..r/r1rrrre)r:zComment.contentcCs|jgSr)rer1rrrrF-szComment.commentsN) r8rWrXrTr2rr[rerFrrrrrs rc@r~) AddressListz address-listcCrb)NcSg|] }|jdkr|qS)addressrTr*rrrrf7z)AddressList.addresses..rr1rrr addresses5rhzAddressList.addressescCtdd|DgS)Ncs |] }|jdkr|jVqdSrNrT mailboxesr*rrrr-;  z(AddressList.mailboxes..r>r1rrrr9 zAddressList.mailboxescCr)NcsrrrT all_mailboxesr*rrrr-@rz,AddressList.all_mailboxes..rr1rrrr>rzAddressList.all_mailboxesN)r8rWrXrTr[rrrrrrrr1s  rc@r~) AddressrcC|djdkr |djSdS)NrgrouprT display_namer1rrrrH zAddress.display_namecCs4|djdkr |dgS|djdkrgS|djSNrmailboxinvalid-mailboxrr1rrrrMs   zAddress.mailboxescCs:|djdkr |dgS|djdkr|dgS|djSrrr1rrrrUs    zAddress.all_mailboxesN)r8rWrXrTr[rrrrrrrrDs  rc@(eZdZdZeddZeddZdS) MailboxList mailbox-listcCrb)NcSr)rrr*rrrrfcrz)MailboxList.mailboxes..rr1rrrrarhzMailboxList.mailboxescCrb)NcSsg|] }|jdvr|qS))rrrr*rrrrfgs z-MailboxList.all_mailboxes..rr1rrrrerhzMailboxList.all_mailboxesNr8rWrXrTr[rrrrrrr]s  rc@r) GroupList group-listcC |r |djdkr gS|djSNrrrr1rrrro zGroupList.mailboxescCrrrr1rrrrurzGroupList.all_mailboxesNrrrrrrks  rc@r~) GrouprcC|djdkr gS|djSNrrr1rrrr zGroup.mailboxescCrrrr1rrrrrzGroup.all_mailboxescC |djSr?)rr1rrrr zGroup.display_nameN)r8rWrXrTr[rrrrrrrr|s  rc@LeZdZdZeddZeddZeddZedd Zed d Z d S) NameAddr name-addrcCst|dkrdS|djSNr)lenrr1rrrr  zNameAddr.display_namecCrN local_partr1rrrrrzNameAddr.local_partcCrrdomainr1rrrrrzNameAddr.domaincCrr)router1rrrrrzNameAddr.routecCrr addr_specr1rrrrrzNameAddr.addr_specN r8rWrXrTr[rrrrrrrrrrs    rc@s@eZdZdZeddZeddZeddZedd Zd S) AngleAddrz angle-addrcCrN addr-spec)rTrrrrrrrzAngleAddr.local_partcCrrrTrrrrrrrzAngleAddr.domaincCr)N obs-route)rTdomainsrrrrrrzAngleAddr.routecCs<|D]}|jdkr|jr|jSt|j|jSqdS)Nrz<>)rTrrrrrrrrs  zAngleAddr.addr_specN) r8rWrXrTr[rrrrrrrrrs   rc@eZdZdZeddZdS)ObsRoutercCrb)NcSrcrrr*rrrrfrgz$ObsRoute.domains..rr1rrrrrhzObsRoute.domainsN)r8rWrXrTr[rrrrrrrc@r) MailboxrcCrNrrrr1rrrrrzMailbox.display_namecCrr?rr1rrrrrzMailbox.local_partcCrr?rr1rrrrrzMailbox.domaincCrr)rTrr1rrrrrz Mailbox.routecCrr?rr1rrrrrzMailbox.addr_specNrrrrrrs    rc@s,eZdZdZeddZeZZZZ dS)InvalidMailboxrcCdSrrr1rrrrrazInvalidMailbox.display_nameNrrrrrrs  rcs(eZdZdZdZefddZZS)DomainrFcdtjSNr'r0rrsplitr1r$rrrz Domain.domain)r8rWrXrTrBr[rr\rrr$rrs rc@ri)DotAtomdot-atomNrlrrrrrrmrc@ru) DotAtomTextz dot-atom-textTNr8rWrXrTrBrrrrr rwrc@ru) NoFoldLiteralzno-fold-literalFNrrrrrrrwrc@sDeZdZdZdZeddZeddZeddZed d Z d S) AddrSpecrFcCrr?rr1rrrrrzAddrSpec.local_partcCst|dkrdS|djS)Nr)rrr1rrrrrzAddrSpec.domaincCs<t|dkr |djS|dj|dj|djS)Nrrrr)rrrstriplstripr1rrrr$s  &zAddrSpec.valuecCsLt|j}t|t|tkrt|j}n|j}|jdur$|d|jS|S)N@)setrr DOT_ATOM_ENDSrr)r!ZnamesetZlprrrr*s   zAddrSpec.addr_specN) r8rWrXrTrBr[rrrrrrrrrs   rc@ru) ObsLocalPartzobs-local-partFNrrrrrr6rcs4eZdZdZdZeddZefddZZS) DisplayNamez display-nameFcCst|}t|dkr |jS|djdkr|dn|ddjdkr/t|ddd|d<|djdkr=||jS|ddjdkrRt|ddd|d<|jS)Nrrrrr)rrrrTpop)r!rrrrrAs  zDisplayName.display_namecsd}|jrd}n |D] }|jdkrd}q t|dkrM|rMd}}|djdks0|ddjdkr2d}|djdksB|ddjdkrDd}|t|j|StjS) NFTrrr'rrr`r)r rTrrrrr)r!rr,ZpreZpostr$rrrRs   zDisplayName.value) r8rWrXrTrZr[rrr\rrr$rr<s rc@s,eZdZdZdZeddZeddZdS) LocalPartz local-partFcCs"|djdkr |djS|djS)Nrr)rTrrr1rrrrks  zLocalPart.valuecCstg}t}d}|dtgD]J}|jdkrq|r.|jdkr.|djdkr.t|dd|d<t|t}|rM|jdkrM|djdkrM|t|ddn|||d}|}qt|dd}|jS)NFrrrdotrr)DOTrTr isinstancerr)r!rZlastZ last_is_tltokZis_tlrrrrrs$   zLocalPart.local_partN)r8rWrXrTrBr[rrrrrrrfs rcs4eZdZdZdZefddZeddZZS) DomainLiteralzdomain-literalFcrrrr1r$rrrrzDomainLiteral.domaincCr)NptextrrrrriprzDomainLiteral.ip) r8rWrXrTrBr[rrr\rrr$rrsrc@seZdZdZdZdZdS) MIMEVersionz mime-versionN)r8rWrXrTmajorminorrrrrrsrc@s4eZdZdZdZdZdZeddZeddZ dS) Parameter parameterFus-asciicCs|jr|djSdSr) sectionednumberr1rrrsection_numberszParameter.section_numbercCsf|D].}|jdkr|jS|jdkr0|D]}|jdkr/|D]}|jdkr.|jSqqqdS)Nrrrr')rTrrrrr param_values     zParameter.param_valueN) r8rWrXrTrextendedr{r[rrrrrrrs rc@ri)InvalidParameterinvalid-parameterNrlrrrrrsrc@r) Attribute attributecCs$|D] }|jdr|jSqdS)Nattrtext)rTendswithrrrrrrs   zAttribute.stripped_valueNr8rWrXrTr[rrrrrrrrc@seZdZdZdZdS)SectionsectionN)r8rWrXrTrrrrrrrrc@r)ValuercCs2|d}|jdkr |d}|jdr|jS|jS)Nrrrr)rrzextended-attribute)rTrrrrrrrrs zValue.stripped_valueNrrrrrrrrc@s(eZdZdZdZeddZddZdS)MimeParametersmime-parametersFc csi}|D]*}|jdsq|djdkrq|dj}||vr%g||<|||j|fq|D]\}}t|tdd}|dd}|j }|j smt |dkrm|dddkrm|ddj t d|dd}g}d}|D]n\} } | |kr| j s| j t dqs| j t d|d7}| j} | j rztj| } Wntytjj| d d } Yn(wz| |d } Wnttfy| d d } Ynwt| r| j t || qsd |} || fVq4dS)Nrrr)keyrz.duplicate parameter name; duplicate(s) ignoredz+duplicate parameter name; duplicate ignoredz(inconsistent RFC2231 parameter numberingzlatin-1)encodingsurrogateescaperr')rTrrstriprritemssortedrr{rrr rInvalidHeaderDefectrurllibparseZunquote_to_bytesUnicodeEncodeErrorZunquotedecode LookupErrorr_has_surrogatesUndecodableBytesDefectr0) r!paramsrGnamepartsZ first_paramr{Z value_partsirparamrrrrrsh           zMimeParameters.paramscCsTg}|jD]\}}|r|d|t|q||qd|}|r(d|SdS)N{}={}z; r`r')rrr7rr0)r!rrrrrrr2,s  zMimeParameters.__str__N)r8rWrXrTrYr[rr2rrrrr s   Er c@r)ParameterizedHeaderValueFcCs&t|D] }|jdkr|jSqiS)Nr )reversedrTrrrrrr=s   zParameterizedHeaderValue.paramsN)r8rWrXrYr[rrrrrr7src@seZdZdZdZdZdZdS) ContentTypez content-typeFtextZplainN)r8rWrXrTrBmaintypesubtyperrrrr!Er}r!c@seZdZdZdZdZdS)ContentDispositionzcontent-dispositionFN)r8rWrXrTrBcontent_dispositionrrrrr%Lr%c@seZdZdZdZdZdS)ContentTransferEncodingzcontent-transfer-encodingFZ7bitN)r8rWrXrTrBrzrrrrr(Rr'r(c@ru) HeaderLabelz header-labelFNrrrrrr)Xrwr)c@seZdZdZdZddZdS)MsgIDzmsg-idFcCst||jSr)rlineseprKrrrrLarhz MsgID.foldN)r8rWrXrTrBrLrrrrr*]s r*c@ri) MessageIDz message-idNrlrrrrr,frmr,c@ri)InvalidMessageIDzinvalid-message-idNrlrrrrr-jrmr-c@ri)HeaderheaderNrlrrrrr.nrmr.csreZdZdZdZdZfddZfddZddZe dd Z dfd d Z d dZ e ddZ ddZZS)TerminalTcst||}||_g|_|Sr)r__new__rTr )clsrrTr!r$rrr1|szTerminal.__new__cr4r5r6r1r$rrr9szTerminal.__repr__cCst|jjd|jdS)N/)rOr%r8rTr1rrrrRszTerminal.pprintcCs t|jSr)listr r1rrrr<rzTerminal.all_defectsr'c s6d||jj|jt|jsdgSd|jgS)Nz {}{}/{}({}){}r'z {})r7r%r8rTrr9r rQr$rrrSs z Terminal._ppcCrrrr1rrrpop_trailing_wsrazTerminal.pop_trailing_wscCsgSrrr1rrrrFrazTerminal.commentscCst||jfSr)rrTr1rrr__getnewargs__szTerminal.__getnewargs__rV)r8rWrXrBrZrYr1r9rRr[r<rSr5rFr6r\rrr$rr0vs     r0c@ eZdZeddZddZdS)WhiteSpaceTerminalcCr^r_rr1rrrrrazWhiteSpaceTerminal.valuecCs|o|dtvSr?WSPr1rrrr@sz!WhiteSpaceTerminal.startswith_fwsNr8rWrXr[rr@rrrrr8  r8c@r7) ValueTerminalcCs|Srrr1rrrrrazValueTerminal.valuecCr^)NFrr1rrrr@zValueTerminal.startswith_fwsNr;rrrrr=r<r=c@r7)EWWhiteSpaceTerminalcCr^rrr1rrrrrazEWWhiteSpaceTerminal.valuecCr^rrr1rrrr2r>zEWWhiteSpaceTerminal.__str__N)r8rWrXr[rr2rrrrr?r<r?c@ri)_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r8rWrX__doc__rrrrr@rmr@r,list-separatorrzroute-component-markerz([{}]+)r'z[^{}]+z[\x00-\x20\x7F]cCsBt|}|r|jt|t|r|jtddSdS)z@If input token contains ASCII non-printables, register a defect.z*Non-ASCII characters found in header tokenN)_non_printable_finderr rrZNonPrintableDefectrrr)xtextZnon_printablesrrr_validate_xtexts   rFcCst|d^}}g}d}d}tt|D]&}||dkr%|r"d}d}nd}q|r*d}n|||vr2n |||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_splitterrangerrr0)rendcharsZfragment remainderZvcharsescapehad_qpposrrr_get_ptext_to_endcharss$   $rNcCs.|}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)rr8r)rZnewvaluerOrrrget_fwssrPvtextc Cst}|dstd||dddd^}}||ddkr,td|d|}t|dkrX|dtvrX|dtvrX| d dkrX|dd^}}|d|}t|dkri|j t d ||_ d|}ztd|d\}}} } Wnttfytd |j w||_| |_|j | |r|dtvrt|\} }| | qt|d^} }t| |} t| | | d|}|s|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)rx startswithrHeaderParseErrorr7rr0rrcountr rrrz_ewr ValueErrorKeyErrorr@r{r|rEr:rPrGr=rF)rZ terminal_typeZewrrJZremstrrestr"r{r|r rGcharsrQrrrget_encoded_wordsb                 r\cCs@t}|r|dtvrt|\}}||qd}|drtz t|d\}}Wnty2d}YnBtjy;Yn9wd}t |dkrV|dj dkrV|j t dd}|rnt |d krn|d j d krnt |dd|d<||qt|d ^}}|rt|r|d^}}t|d}t|||d |}|s|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. rTrRZutextFrrOz&missing whitespace before encoded wordrryr')rjr:rPrrTr\r@rrUrrTr rr?rGrfc2047_matchersearch partitionr=rFr0)rrkrGvalid_ewZhave_wsrrJrQrrrget_unstructuredOsL           )rbcC*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)rNr8rFrr_rrr get_qp_ctexts rfcCrc)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)rNr=rFrdrrr get_qcontents rgcCNt|}|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_matcherrrUr7rrr=rF)rmrirrr get_atexts rlcCsn|ddkrtd|t}|dd}|r*|ddkr*t|\}}|||r|ddkr|dtvr?t|\}}nT|dddkrd}zt|\}}|j t d d }Wntjylt|\}}Ynw|rt |dkr|d j d kr|d j dkrt |d d |d <nt|\}}|||r|ddks2|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 '{}'rNrrRFz!encoded word inside quoted stringTrrOr]ryz"end of header inside quoted string)rrUr7rrgrr:rPr\r rrrTr?)rZbare_quoted_stringrGrarrrget_bare_quoted_stringsN          rmcCs|r|ddkrtd|t}|dd}|rN|ddkrN|dtvr.t|\}}n|ddkr;t|\}}nt|\}}|||rN|ddks!|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) rrUr7rr:rP get_commentrfrr r)rrdrGrrrrns(      rncCs^t}|r+|dtvr+|dtvrt|\}}nt|\}}|||r+|dtvs ||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS r)rq CFWS_LEADERr:rPrnr)rrrrGrrrget_cfwss   rpcCspt}|r|dtvrt|\}}||t|\}}|||r4|dtvr4t|\}}||||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)rrorprrm)rZ quoted_stringrGrrrget_quoted_strings      rqcCst}|r|dtvrt|\}}|||r&|dtvr&td||drDzt |\}}WntjyCt |\}}Ynwt |\}}|||rb|dtvrbt|\}}||||fS)zPatom = [CFWS] 1*atext [CFWS] An atom could be an rfc2047 encoded word. rzexpected atom but found '{}'rR) rsrorpr ATOM_ENDSrrUr7rTr\rl)rrtrGrrrget_atom%s(       rscCst}|r |dtvrtd||rA|dtvrAt|\}}|||r9|ddkr9|t|dd}|rA|dtvs|dturQtdd|||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 '{}')rrrrrUr7rlrr)rZ dot_atom_textrGrrrget_dot_atom_text@s"      rtcCst}|dtvrt|\}}|||dr2zt|\}}Wntjy1t|\}}Ynwt|\}}|||rP|dtvrPt|\}}||||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. rrR) rrorprrTr\rrUrt)rZdot_atomrGrrr get_dot_atomSs         rucCs|dtvr t|\}}nd}|std|ddkr#t|\}}n|dtvr1td|t|\}}|durB|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 '{}')rorprrUrqSPECIALSr7rs)rleaderrGrrrget_wordls"    rxcCst}z t|\}}||Wntjy#|jtdYnw|r~|dtvr~|ddkrG|t|jt d|dd}n/zt|\}}Wn!tjyp|dt vrmt |\}}|jt dnYnw|||r~|dtvs,||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) rnrxrrrUr r PHRASE_ENDSrObsoleteHeaderDefectrorp)rrorGrrr get_phrases<           r{c Cslt}d}|dtvrt|\}}|std|zt|\}}Wn-tjyPzt|\}}WntjyM|ddkrH|dtvrHt }YnwYnw|dur\|g|dd<| ||r|ddkso|dtvrt t ||\}}|j dkr|j tdn |j td||d<z |jdW||fSty|j td Y||fSw) z= local-part = dot-atom / quoted-string / obs-local-part Nrz"expected local-part but found '{}'r invalid-obs-local-partz / 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)rNr=r rrrzrF)rrrLrrr get_dtext s  rcCs,|rdS|td|tdddS)NFz"end of input inside domain-literal]domain-literal-endT)rrrr=)rdomain_literalrrr_check_for_early_dl_endsrcCsdt}|dtvrt|\}}|||std|ddkr)td||dd}t||r8||fS|tdd|dt vrQt |\}}||t |\}}||t||re||fS|dt vrvt |\}}||t||r||fS|ddkrtd ||tdd |dd}|r|dtvrt|\}}||||fS) zB domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] rzexpected domain-literal[z6expected '[' at start of domain-literal but found '{}'rNzdomain-literal-startrz4expected ']' at end of domain-literal but found '{}'r) rrorprrrUr7rr=r:rPr)rrrGrrrget_domain_literal&sH                     rcCsrt}d}|dtvrt|\}}|std||ddkr;t|\}}|dur2|g|dd<||||fSzt|\}}WntjySt |\}}Ynw|ra|ddkratd|durl|g|dd<|||r|ddkr|j t d|dj d kr|d|dd<|r|ddkr|t t |d d\}}|||r|ddks||fS) z] domain = dot-atom / domain-literal / obs-domain obs-domain = atom *("." atom)) Nrzexpected domain but found '{}'rrzInvalid Domainrz(domain is not a dot-atom (contains CFWS)rr)rrorprrUr7rrrursr rzrTr)rrrwrGrrr get_domainMsH          rcCs|t}t|\}}|||r|ddkr#|jtd||fS|tddt|dd\}}||||fS)z( addr-spec = local-part "@" domain rrz#addr-spec local part with no domainaddress-at-symbolrN)rrrr rrr=r)rrrGrrr get_addr_specss    rcCst}|rB|ddks|dtvrB|dtvr#t|\}}||n|ddkr4|t|dd}|rB|ddks|dtvs|rJ|ddkrRtd||tt |dd\}}|||r|ddkr|t|dd}|s|n3|dtvrt|\}}|||ddkr|tt |dd\}}|||r|ddksn|std|ddkrtd ||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). rrBrNrz(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) rrorpr ListSeparatorrrUr7RouteComponentMarkerrr=)rZ obs_routerGrrr get_obs_routesJ                  rc Cst}|dtvrt|\}}|||r|ddkr$td||tdd|dd}|ddkrS|tdd|jt d |dd}||fSzt |\}}Wn7tjyzt |\}}|jt d Wntjytd |w||t |\}}Ynw|||r|ddkr|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) rrorprrrUr7r=r rrrrz)rZ angle_addrrGrrrget_angle_addrsX               rcCs<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)rr{rEr )rrrGrrrget_display_names  rcCst}d}|dtvrt|\}}|std||ddkrS|dtvr/td|t|\}}|s?td||durN|g|ddd<d}||t |\}}|durd|g|dd<||||fS)z, name-addr = [display-name] angle-addr Nrz!expected name-addr but found '{}'r) rrorprrUr7ryrrr)rZ name_addrrwrGrrr get_name_addrs6        rc Cst}zt|\}}Wn#tjy.zt|\}}Wntjy+td|wYnwtdd|jDr.r) rrrrUrr7anyr<rTr)rrrGrrr get_mailboxs& rcCsrt}|r5|d|vr5|dtvr"|t|dd|dd}n t|\}}|||r5|d|vs ||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. rrrN)rryrr=r{)rrIZinvalid_mailboxrGrrrget_invalid_mailbox    rcCst}|r|ddkrz t|\}}||Wntjyd}|dtvrft|\}}|r6|ddvrE|||jtdnQt |d\}}|durW|g|dd<|||jt dn0|ddkrv|jtdn t |d\}}|dur|g|dd<|||jt dYnw|r|ddvr|d}d |_ t |d\}}| ||jt d|r|ddkr|t |d d}|r|ddks ||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-listrBrrr)rrrrrUrorpr rzrrrTrEr)rZ mailbox_listrGrwrrrrget_mailbox_list.s^                )rcCst}|s|jtd||fSd}|rE|dtvrEt|\}}|s6|jtd||||fS|ddkrE||||fSt|\}}t|j dkrm|dur[||| ||jt d||fS|durx|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-listrzgroup-list with empty entries) rr rrrrorprrrrErz)rZ group_listrwrGrrrget_group_listgs>           rcCst}t|\}}|r|ddkrtd||||tdd|dd}|rD|ddkrD|tdd||ddfSt|\}}|||s[|jt d n|ddkritd ||tdd|dd}|r|dt vrt |\}}||||fS) z7 group = display-name ":" [group-list] ";" [CFWS] rrz8expected ':' at end of group display name but found '{}'zgroup-display-name-terminatorrNrzgroup-terminatorzend of header in groupz)expected ';' at end of group but found {}) rrrrUr7rr=rr rrorp)rrrGrrr get_groups8          rc Cspt}zt|\}}Wn#tjy.zt|\}}Wntjy+td|wYnw||||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 '{}')rrrrUrr7r)rrrGrrr get_addresss rc Cst}|rz t|\}}||Wntjy}zd}|dtvrdt|\}}|r1|ddkr@|||jtdnWt |d\}}|durR|g|dd<|t |g|jt dn3|ddkrt|jtdn#t |d\}}|dur|g|dd<|t |g|jt dWYd}~nd}~ww|r|ddkr|dd}d|_ t |d\}}| ||jt d|r|tdd |d d}|s||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. NrrBz"address-list entry with no contentzinvalid address in address-listzempty element in address-listrrrCr)rrrrrUrorpr rzrrrrTrEr=)rZ address_listrGerrrwrrrrget_address_lists^              )rcCst}|s td||ddkrtd||tdd|dd}t|\}}|||r<|ddkrDtd ||tdd ||ddfS) z& no-fold-literal = "[" *dtext "]" z'expected no-fold-literal but found '{}'rrz;expected '[' at the start of no-fold-literal but found '{}'zno-fold-literal-startrNrz9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)rrrUr7rr=r)rZno_fold_literalrGrrrget_no_fold_literals*    rcCspt}|r|dtvrt|\}}|||r|ddkr&td||tdd|dd}zt|\}}Wn,tjyhzt |\}}|j t dWntjyetd|wYnw|||rv|dd kr|j t d |r|dd kr|td d |dd}||fS|td d |dd}zt|\}}WnHtjyzt |\}}Wn5tjy}z(zt|\}}|j t dWntjytd|wWYd}~nd}~wwYnw|||r|dd kr|dd}n |j t d|td d |r4|dtvr4t|\}}||||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 "]" rrzexpected 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-rightrz msg-id-endrzobsolete id-right in msg-idzFexpected dot-atom-text, no-fold-literal or obs-id-right but found '{}'zmissing trailing '>' on msg-id)r*rorprrrUr7r=rtr~r rzrrr)rZmsg_idrGerrr get_msg_ids                  rc Cst}z t|\}}||Wn(tjy8}zt|}t|}|jtd |WYd}~|Sd}~ww|rG|jtd ||S)z2message-id = "Message-ID:" msg-id CRLF zInvalid msg-id: {!r}NzUnexpected {!r}) r,rrrrUrbr-r rr7)rZ message_idrGZexrrrparse_message_idYs$  rcCst}|s|jtd|S|dtvr,t|\}}|||s,|jtdd}|rV|ddkrV|dtvrV||d7}|dd}|rV|ddkrV|dtvs<|so|jtd ||t |d n t ||_ |t |d |r|dtvrt|\}}|||r|ddkr|j dur|jtd |r|t |d |S|t dd |dd}|r|dtvrt|\}}|||s|j dur|jtd |Sd}|r|dtvr||d7}|dd}|r|dtvs|s|jtd ||t |d n t ||_ |t |d |rA|dtvrAt|\}}|||rU|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}rEdigitsz0Incomplete MIME version; found only major numberzversion-separatorz1Expected MIME minor version number but found {!r}z'Excess non-CFWS text after MIME version)rr rrHeaderMissingRequiredValuerorpisdigitrr7r=intrr)rZ mime_versionrGrrrrparse_mime_versionus                          rcCsrt}|r5|ddkr5|dtvr"|t|dd|dd}n t|\}}|||r5|ddks ||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. rrrrN)rryrr=r{)rZinvalid_parameterrGrrrget_invalid_parameterrrcCrh)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_matcherrrUr7rrr=rF)rrkrrrr get_ttext  rcCt}|r|dtvrt|\}}|||r&|dtvr&td|t|\}}|||rD|dtvrDt|\}}||||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 '{}') rvrorpr TOKEN_ENDSrrUr7r)rZmtokenrGrrr get_token       rcCrh)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_matcherrrUr7rrr=rFrrkrrrr get_attrtextrrcCr)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. rr) rrorprATTRIBUTE_ENDSrrUr7rrrrGrrr get_attribute rrcCrh)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_matcherrrUr7rrr=rFrrrrget_extended_attrtext s rcCr)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. rr) rrorprEXTENDED_ATTRIBUTE_ENDSrrUr7rrrrrget_extended_attribute1 s      rcCst}|r |ddkrtd||tdd|dd}|r)|ds1td|d}|rO|drO||d7}|dd}|rO|ds;|dd krb|d krb|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 0r) rrrUr7rr=rr rrr)rrrrrr get_sectionG s.      rcCst}|s tdd}|dtvrt|\}}|s"td||ddkr/t|\}}nt|\}}|dur@|g|dd<||||fS)z quoted-string / attribute z&Expected value but found end of stringNrz Expected value but found only {}r) rrrUrorpr7rqrr)rvrwrGrrr get_valuee s"      rc Csxt}t|\}}|||r|ddkr&|jtd|||fS|ddkrezt|\}}d|_||Wn tj yFYnw|sNt d|ddkre|t dd|dd }d|_ |dd krpt d |t d d |dd }d }|r|dt vrt |\}}||d }|}|j r|r|dd krt|\}}|j}d}|jdkr|r|ddkrd}n#t|\}} | r| ddkrd}nzt|\}} WnYn| sd}|r |jtd|||D]} | jdkrg| d d <| }nq|}n d }|jtd|r$|ddkr$d }nt|\}}|j r4|jdkrW|r>|ddkrN|||d urJ|}||fS|jtd|sr|jtd|||d urq||fSnw|d ur|D] } | jdkrnqy| jdk|| | j|_|ddkrt d||t dd|dd }|r|ddkrt|\}}|||j|_|r|ddkrt d||t dd|dd }|d ur&t} |r#|dtvrt|\}}n|dd krt d d}|dd }nt|\}}| ||s| }nt|\}}|||d ur8|}||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. rrz)Parameter contains name ({}) but no valuerTzIncomplete parameterzextended-parameter-markerrN=zParameter not followed by '='parameter-separatorrF'z5Quoted string value for extended parameter is invalidrzZParameter 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)rrrr rrr7rrrUr=rrorprqrrrrrTrrr{r|rr:rPrg) rrrGrwrJZappendtoZqstringZ inner_valueZ semi_validrZtrrrr get_parameter{ s                                           rc Cslt}|rz t|\}}||Wnitjy{}z\d}|dtvr)t|\}}|s8|||WYd}~S|ddkrQ|durG|||jtdn t |\}}|r`|g|dd<|||jtd |WYd}~nd}~ww|r|ddkr|d}d|_ t |\}}| ||jtd ||r|t dd |d d}|s|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. Nrrzparameter entry with no contentzinvalid parameter {!r}rrz)parameter with invalid trailing text {!r}rr)r rrrrUrorpr rrr7rTrEr=)rZmime_parametersrGrrwrrrrparse_mime_parameters sP               $rcCs|r2|ddkr2|dtvr|t|dd|dd}n t|\}}|||r2|ddks|s6dS|tdd|t|dddS)zBDo our best to find the parameters in an invalid MIME header rrrrNr)ryrr=r{r)Z tokenlistrrGrrr_find_mime_parameters= s   rc Cst}d}|s|jtd|Szt|\}}Wntjy7|jtd|t |||YSw|||rE|ddkrW|jtd|rUt |||S|j |_ |tdd|dd }zt|\}}Wntjy|jtd |t |||YSw|||j |_|s|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}rr3zInvalid content typezcontent-type-separatorrNz'Expected content subtype but found {!r}rz. unknown-8bitTr rHrrrrrcSsg|] }tt|dqSr)r=rr+prrrrf7 sz&_refold_parse_tree..rdrcSs(g|]}|jdkrtt|dn|qSr)rTr=rrrrrrf= s  r)Zmax_line_lengthsysmaxsizeutf8r0r4rrrT SPECIALSNL isdisjointNLSETrrrr<_fold_mime_parametersrBrYrLrr+rrrU _fold_as_ewrZr@r=insertr0)Z parse_treerImaxlenr rlast_ewrZ want_encodingZend_ew_not_allowedrrCtstrr{Z encoded_partnewlineZnewpartsrrrrJ s                     lrJcCs|dur|rtt|d|d|}|dd||d<|dtvrE|d}|dd}t|d|kr=|t||d|7<d}|dtvrW|d}|dd}|durat|dn|}|dkridn|} t| d} | d|kr|td |r|t|d} | | } | dkr|d q||d| } tj | | d }t|| }|dkr| dd} tj | | d }t|| }|dks|d|7<|t| d}|r|d t|d}|s~|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 wordr`)r{) rrbr:rrrrrUrWr)Z to_encoderrrrZr{Z leading_wspZ trailing_wspZ new_last_ewZ encode_as chrome_lenZremaining_spaceZ text_spaceZto_encode_wordZ encoded_wordZexcessrrrrU sX               rc Cs|jD]\}}|dds|dd7<|}d}z ||d}Wnty<d}t|r8d}d}nd}Ynw|rPtjj |d |d } d ||| } nd |t |} t |dt | d |krq|dd| |d<qt | d|kr| d| qd} |d} |rt |t t| dt | } || dkrd}|| d}} |d|}tjj |d |d } t | |krn|d 8}q| d || | | d } | d 7} ||d}|r|dd7<|sqdS)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'. rrstrictFTrr rr')Zsaferz {}*={}''{}rrr`rrz''rNNz {}*{}*={}{})rrrrrrrrrrr7rrrr)rCrrr rrr{Z error_handlerZencoding_requiredZ encoded_valuerrZ extra_chromerZ splitpointZmaxcharspartialrrrr sn        r)rQ)rArerrstringroperatorrZemailrrWrrrr:rorvrrrryZ TSPECIALSrZ ASPECIALSrrrrrrrcompileVERBOSE MULTILINEr^r4rr]rjrnrprqrsrvrxrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rr!r%r(r)r*r,r-r.rr0r8r=r?rUr@rrrr7r0rrGrKmatchrjfindallrDrrrrFrNrPr\rbrfrgrlrmrnrprqrsrtrurxr{rr~rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrJrrrrrrsHE           C  "   !*$ V +        1C+ "&'/'&).9%7ED49/{ A