o 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\")strreplacevaluerA/opt/alt/python310/lib64/python3.10/email/_header_value_parser.pymake_quoted_pairscsrcCst|}d|dS)Nr)r)rZescapedrrr quote_stringhs 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__..joinrrrr__str__zTokenList.__str__cd|jjtSNz{}({})formatr __name__r__repr__r,rrrr4s zTokenList.__repr__cCr!)Nr"css|] }|jr|jVqdSrrr%rrrr(sz"TokenList.value..r*r,rrrrzTokenList.valuecCstdd|D|jS)Ncs|]}|jVqdSr) all_defectsr%rrrr(z(TokenList.all_defects..)sumrr,rrrr7szTokenList.all_defectscCs |dSNr)startswith_fwsr,rrrr; zTokenList.startswith_fwscCstdd|DS)zATrue if all top level tokens of this part may be RFC2047 encoded.csr6r) as_ew_allowed)r&partrrrr(r8z*TokenList.as_ew_allowed..)allr,rrrr=szTokenList.as_ew_allowedcCsg}|D]}||jq|Sr)extendcomments)rrAtokenrrrrAszTokenList.commentscCs t||dS)Npolicy)_refold_parse_treerrDrrrfoldr<zTokenList.foldr"cCst|j|ddS)Nindent)printppstrrrIrrrpprintr.zTokenList.pprintcCsd|j|dS)Nr rH)r+_pprLrrrrKszTokenList.ppstrccs|d||jj|jV|D]}t|ds|d|Vq||dEdHq|jr3d|j}nd}d||VdS)Nz{}{}/{}(rNz* !! invalid element in token list: {!r}z z Defects: {}r"z{}){})r2r r3 token_typehasattrrNr)rrIrBZextrarrrrNs  z TokenList._ppr")r3 __module__ __qualname__rOsyntactic_breakew_combine_allowedrr-r4propertyrr7r;r=rArGrMrKrN __classcell__rrrrr}s(        rc@s$eZdZeddZeddZdS)WhiteSpaceTokenListcCdSN rr,rrrrzWhiteSpaceTokenList.valuecCdd|DS)NcSg|] }|jdkr|jqS)comment)rOcontentr%rrr z0WhiteSpaceTokenList.comments..rr,rrrrAzWhiteSpaceTokenList.commentsN)r3rRrSrVrrArrrrrXs  rXc@eZdZdZdS)UnstructuredTokenList unstructuredNr3rRrSrOrrrrrerec@rd)PhrasephraseNrgrrrrrirhric@rd)WordZwordNrgrrrrrkrhrkc@rd)CFWSListcfwsNrgrrrrrlrhrlc@rd)AtomatomNrgrrrrrnrhrnc@eZdZdZdZdS)TokenrBFN)r3rRrSrOZ encode_as_ewrrrrrqrqc@seZdZdZdZdZdZdS) EncodedWord encoded-wordN)r3rRrSrOctecharsetlangrrrrrs rsc@4eZdZdZeddZeddZeddZdS) QuotedString quoted-stringcC"|D] }|jdkr|jSqdSNbare-quoted-stringrOrrr'rrrr`   zQuotedString.contentcCs>g}|D]}|jdkr|t|q||jqd|S)Nr~r")rOappendrrr+)rresr'rrr quoted_values   zQuotedString.quoted_valuecCr|r}rrrBrrrstripped_valuerzQuotedString.stripped_valueN)r3rRrSrOrVr`rrrrrrrzs   rzc@s$eZdZdZddZeddZdS)BareQuotedStringr~cCstddd|DS)Nr"csr#rr$r%rrrr( r)z+BareQuotedString.__str__..)rr+r,rrrr- szBareQuotedString.__str__cCr!)Nr"csr#rr$r%rrrr(r)z)BareQuotedString.value..r*r,rrrr r5zBareQuotedString.valueN)r3rRrSrOr-rVrrrrrrs rc@s8eZdZdZddZddZeddZedd Zd S) Commentr_cs(dtdgfddDdgggS)Nr"rcsg|]}|qSr)quoter%r,rrrasz#Comment.__str__..))r+r9r,rr,rr-szComment.__str__cCs2|jdkr t|St|ddddddS)Nr_r r rz\(rz\))rOrr)rrrrrrs z Comment.quotecCr!)Nr"csr#rr$r%rrrr(%r)z"Comment.content..r*r,rrrr`#r5zComment.contentcCs|jgSr)r`r,rrrrA'szComment.commentsN) r3rRrSrOr-rrVr`rArrrrrs rc@ry) AddressListz address-listcCr])NcSg|] }|jdkr|qS)addressrOr%rrrra1z)AddressList.addresses..rr,rrr addresses/rczAddressList.addressescCtdd|DgS)Ncs |] }|jdkr|jVqdSrNrO mailboxesr%rrrr(5  z(AddressList.mailboxes..r9r,rrrr3 zAddressList.mailboxescCr)NcsrrrO all_mailboxesr%rrrr(:rz,AddressList.all_mailboxes..rr,rrrr8rzAddressList.all_mailboxesN)r3rRrSrOrVrrrrrrrr+s  rc@ry) AddressrcC|djdkr |djSdS)NrgrouprO display_namer,rrrrB zAddress.display_namecCs4|djdkr |dgS|djdkrgS|djSNrmailboxinvalid-mailboxrr,rrrrGs   zAddress.mailboxescCs:|djdkr |dgS|djdkr|dgS|djSrrr,rrrrOs    zAddress.all_mailboxesN)r3rRrSrOrVrrrrrrrr>s  rc@(eZdZdZeddZeddZdS) MailboxList mailbox-listcCr])NcSr)rrr%rrrra]rz)MailboxList.mailboxes..rr,rrrr[rczMailboxList.mailboxescCr])NcSsg|] }|jdvr|qS))rrrr%rrrraas z-MailboxList.all_mailboxes..rr,rrrr_rczMailboxList.all_mailboxesNr3rRrSrOrVrrrrrrrWs  rc@r) GroupList group-listcC |r |djdkr gS|djSNrrrr,rrrri zGroupList.mailboxescCrrrr,rrrrorzGroupList.all_mailboxesNrrrrrres  rc@ry) GrouprcC|djdkr gS|djSNrrr,rrrrz zGroup.mailboxescCrrrr,rrrrrzGroup.all_mailboxescC |djSr:)rr,rrrr zGroup.display_nameN)r3rRrSrOrVrrrrrrrrvs  rc@LeZdZdZeddZeddZeddZedd Zed d Z d S) NameAddr name-addrcCst|dkrdS|djSNr)lenrr,rrrr  zNameAddr.display_namecCrN local_partr,rrrrrzNameAddr.local_partcCrrdomainr,rrrrrzNameAddr.domaincCrr)router,rrrrrzNameAddr.routecCrr addr_specr,rrrrrzNameAddr.addr_specN r3rRrSrOrVrrrrrrrrrrs    rc@s@eZdZdZeddZeddZeddZedd Zd S) AngleAddrz angle-addrcCr|N addr-spec)rOrrrrrrrzAngleAddr.local_partcCr|rrOrrrrrrrzAngleAddr.domaincCr|)N obs-route)rOdomainsrrrrrrzAngleAddr.routecCs<|D]}|jdkr|jr|jSt|j|jSqdS)Nrz<>)rOrrrrrrrrs  zAngleAddr.addr_specN) r3rRrSrOrVrrrrrrrrrs   rc@eZdZdZeddZdS)ObsRoutercCr])NcSr^rrr%rrrrarbz$ObsRoute.domains..rr,rrrrrczObsRoute.domainsN)r3rRrSrOrVrrrrrrrc@r) MailboxrcCrNrrrr,rrrrrzMailbox.display_namecCrr:rr,rrrrrzMailbox.local_partcCrr:rr,rrrrrzMailbox.domaincCrr)rOrr,rrrrrz Mailbox.routecCrr:rr,rrrrrzMailbox.addr_specNrrrrrrs    rc@s,eZdZdZeddZeZZZZ dS)InvalidMailboxrcCdSrrr,rrrrr\zInvalidMailbox.display_nameNrrrrrrs  rcs(eZdZdZdZefddZZS)DomainrFcdtjSNr"r+rrsplitr,rrrrz Domain.domain)r3rRrSrOr=rVrrWrrrrrs rc@rd)DotAtomdot-atomNrgrrrrrrhrc@rp) DotAtomTextz dot-atom-textTNr3rRrSrOr=rrrrrrrrc@rp) NoFoldLiteralzno-fold-literalFNrrrrrr rrrc@sDeZdZdZdZeddZeddZeddZed d Z d S) AddrSpecrFcCrr:rr,rrrrrzAddrSpec.local_partcCst|dkrdS|djS)Nr)rrr,rrrrrzAddrSpec.domaincCs<t|dkr |djS|dj|dj|djS)Nrrrr)rrrstriplstripr,rrrrs  &zAddrSpec.valuecCsLt|j}t|t|tkrt|j}n|j}|jdur$|d|jS|S)N@)setrr DOT_ATOM_ENDSrr)rZnamesetZlprrrr$s   zAddrSpec.addr_specN) r3rRrSrOr=rVrrrrrrrrrs   rc@rp) ObsLocalPartzobs-local-partFNrrrrrr0rcs4eZdZdZdZeddZefddZZS) DisplayNamez display-nameFcCst|}t|dkr |jS|djdkr|dn|ddjdkr/t|ddd|d<|djdkr=||jS|ddjdkrRt|ddd|d<|jS)Nrrmrr)rrrrOpop)rrrrrr;s  zDisplayName.display_namecsd}|jrd}n |D] }|jdkrd}q t|dkrM|rMd}}|djdks0|ddjdkr2d}|djdksB|ddjdkrDd}|t|j|StjS) NFTr{rr"rmr[r)rrOrrrrr)rrr'ZpreZpostrrrrLs   zDisplayName.value) r3rRrSrOrUrVrrrWrrrrr6s rc@s,eZdZdZdZeddZeddZdS) LocalPartz local-partFcCs"|djdkr |djS|djS)Nrr{)rOrrr,rrrres  zLocalPart.valuecCstg}t}d}|dtgD]J}|jdkrq|r.|jdkr.|djdkr.t|dd|d<t|t}|rM|jdkrM|djdkrM|t|ddn|||d}|}qt|dd}|jS)NFrrmdotrr)DOTrOr isinstancerr)rrZlastZ last_is_tltokZis_tlrrrrls$   zLocalPart.local_partN)r3rRrSrOr=rVrrrrrrr`s rcs4eZdZdZdZefddZeddZZS) DomainLiteralzdomain-literalFcrrrr,rrrrrzDomainLiteral.domaincCr|)NptextrrrrriprzDomainLiteral.ip) r3rRrSrOr=rVrrrWrrrrrsrc@seZdZdZdZdZdS) MIMEVersionz mime-versionN)r3rRrSrOmajorminorrrrrrsrc@s4eZdZdZdZdZdZeddZeddZ dS) Parameter parameterFus-asciicCs|jr|djSdSr) sectionednumberr,rrrsection_numberszParameter.section_numbercCsf|D].}|jdkr|jS|jdkr0|D]}|jdkr/|D]}|jdkr.|jSqqqdS)Nrr{r~r")rOrrrrr param_values     zParameter.param_valueN) r3rRrSrOrextendedrvrVrrrrrrrs rc@rd)InvalidParameterinvalid-parameterNrgrrrrrsrc@r) Attribute attributecCs$|D] }|jdr|jSqdS)Nattrtext)rOendswithrrrrrrs   zAttribute.stripped_valueNr3rRrSrOrVrrrrrrrrc@seZdZdZdZdS)SectionsectionN)r3rRrSrOrrrrrrrrc@r)ValuercCs2|d}|jdkr |d}|jdr|jS|jS)Nrrmr)r{rzextended-attribute)rOrrrrrrrrs 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")rOrrstriprritemssortedrrvrrrrInvalidHeaderDefectrurllibparseZunquote_to_bytesUnicodeEncodeErrorZunquotedecode LookupErrorr_has_surrogatesUndecodableBytesDefectr+) rparamsrBnamepartsZ first_paramrvZ value_partsirparamrrrrrsh           zMimeParameters.paramscCsTg}|jD]\}}|r|d|t|q||qd|}|r(d|SdS)N{}={}z; r[r")rrr2rr+)rrrrrrrr-&s  zMimeParameters.__str__N)r3rRrSrOrTrVrr-rrrrrs   Erc@r)ParameterizedHeaderValueFcCs&t|D] }|jdkr|jSqiS)Nr)reversedrOrrrrrr7s   zParameterizedHeaderValue.paramsN)r3rRrSrTrVrrrrrr1src@seZdZdZdZdZdZdS) ContentTypez content-typeFtextZplainN)r3rRrSrOr=maintypesubtyperrrrr?rxrc@seZdZdZdZdZdS)ContentDispositionzcontent-dispositionFN)r3rRrSrOr=content_dispositionrrrrr!Fr!c@seZdZdZdZdZdS)ContentTransferEncodingzcontent-transfer-encodingFZ7bitN)r3rRrSrOr=rurrrrr$Lr#r$c@rp) HeaderLabelz header-labelFNrrrrrr%Rrrr%c@seZdZdZdZddZdS)MsgIDzmsg-idFcCst||jSr)rlineseprFrrrrG[rcz MsgID.foldN)r3rRrSrOr=rGrrrrr&Ws r&c@rd) MessageIDz message-idNrgrrrrr(`rhr(c@rd)InvalidMessageIDzinvalid-message-idNrgrrrrr)drhr)c@rd)HeaderheaderNrgrrrrr*hrhr*csreZdZdZdZdZfddZfddZddZe dd Z dfd d Z d dZ e ddZ ddZZS)TerminalTcst||}||_g|_|Sr)r__new__rOr)clsrrOrrrrr-vszTerminal.__new__cr/r0r1r,rrrr4|szTerminal.__repr__cCst|jjd|jdS)N/)rJr r3rOr,rrrrMszTerminal.pprintcCs t|jSr)listrr,rrrr7rzTerminal.all_defectsr"c s6d||jj|jt|jsdgSd|jgS)Nz {}{}/{}({}){}r"z {})r2r r3rOrr4rrLrrrrNs z Terminal._ppcCrrrr,rrrpop_trailing_wsr\zTerminal.pop_trailing_wscCsgSrrr,rrrrAr\zTerminal.commentscCst||jfSr)rrOr,rrr__getnewargs__szTerminal.__getnewargs__rQ)r3rRrSr=rUrTr-r4rMrVr7rNr1rAr2rWrrrrr,ps     r,c@ eZdZeddZddZdS)WhiteSpaceTerminalcCrYrZrr,rrrrr\zWhiteSpaceTerminal.valuecCrY)NTrr,rrrr;z!WhiteSpaceTerminal.startswith_fwsNr3rRrSrVrr;rrrrr4  r4c@r3) ValueTerminalcCs|Srrr,rrrrr\zValueTerminal.valuecCrY)NFrr,rrrr;r5zValueTerminal.startswith_fwsNr6rrrrr8r7r8c@r3)EWWhiteSpaceTerminalcCrYrrr,rrrrr\zEWWhiteSpaceTerminal.valuecCrYrrr,rrrr-r5zEWWhiteSpaceTerminal.__str__N)r3rRrSrVrr-rrrrr9r7r9c@rd)_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r3rRrS__doc__rrrrr:rhr: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_finderrrrZNonPrintableDefectrrr)xtextZnon_printablesrrr_validate_xtexts   r@cCst|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_splitterrangerrr+)rendcharsZfragment remainderZvcharsescapehad_qpposrrr_get_ptext_to_endcharss$   $rHcCs.|}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)rr4r)rZnewvaluerIrrrget_fws srJvtextc 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)rs startswithrHeaderParseErrorr2rr+rrcountrrr ru_ewr ValueErrorKeyErrorr:rvrwr@WSPrJrAr8r@)rZ terminal_typeZewrrDZremstrrestrrvrwrrBcharsrKrrrget_encoded_wordsb                 rWcCs@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. rTrLZutextFrrIz&missing whitespace before encoded wordrrtr")rerTrJrrNrWr:rrOrrOrr r9rArfc2047_matchersearch partitionr8r@r+)rrfrBvalid_ewZhave_wsrrDrKrrrget_unstructuredIsL           )r]cC*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)rHr4r@rr_rrr get_qp_ctexts racCr^)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)rHr8r@r_rrr get_qcontents rbcCNt|}|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_matcherrrOr2rrr8r@)rmrdrrr get_atexts rgcCsn|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 '{}'rNrrLFz!encoded word inside quoted stringTrrIrXrtz"end of header inside quoted string)rrOr2rrbrrTrJrWrr rrOr9)rZbare_quoted_stringrBr\rrrget_bare_quoted_stringsN          rhcCs|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) rrOr2rrTrJ get_commentrarrr )rr_rBrrrris(      ricCs^t}|r+|dtvr+|dtvrt|\}}nt|\}}|||r+|dtvs ||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS r)rl CFWS_LEADERrTrJrir)rrmrBrrrget_cfwss   rkcCspt}|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)rzrjrkrrh)rZ quoted_stringrBrrrget_quoted_string s      rlcCst}|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 '{}'rL) rnrjrkr ATOM_ENDSrrOr2rNrWrg)rrorBrrrget_atoms(       rncCst}|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 '{}')rrmrrOr2rgrr)rZ dot_atom_textrBrrrget_dot_atom_text:s"      rocCst}|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. rrL) rrjrkrrNrWrrOro)rZdot_atomrBrrr get_dot_atomMs         rpcCs|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 '{}')rjrkrrOrlSPECIALSr2rn)rleaderrBrrrget_wordfs"    rscCst}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) rirsrrrOrr  PHRASE_ENDSrObsoleteHeaderDefectrjrk)rrjrBrrr get_phrases<           rvc 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)rHr8rrrrur@)rrrFrrr get_dtexts  r~cCs,|rdS|td|tdddS)NFz"end of input inside domain-literal]domain-literal-endT)rrr r8)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) rrjrkrrrOr2rr8rTrJr~)rrrBrrrget_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)rrjrkrrOr2rrrprnrrurOr)rrrrrBrrr get_domainGsH          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)rr|rrrr r8r)rrrBrrr get_addr_specms    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). 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) rrjrkr ListSeparatorrrOr2RouteComponentMarkerrr8)rZ obs_routerBrrr get_obs_route}sJ                  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) rrjrkrrrOr2r8rr rrru)rZ angle_addrrBrrrget_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)rrvr@r)rrrBrrrget_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) rrjrkrrOr2rtrrr)rZ name_addrrrrBrrr get_name_addrs6        rc Cst}zt|\}}Wn#tjy.zt|\}}Wntjy+td|wYnwtdd|jDr.r) rrrrOrr2anyr7rOr)rrrBrrr 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. rr}rN)rrtrr8rv)rrCZinvalid_mailboxrBrrrget_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-listr<rrr)rrrrrOrjrkrrurr rOr@r)rZ mailbox_listrBrrrrrrget_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) rrrrr rjrkrrrr@ru)rZ group_listrrrBrrrget_group_listas>           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 {}) rrrrOr2rr8rrr rjrk)rrrBrrr 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 '{}')rrrrOrr2r)rrrBrrr 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. Nrr<z"address-list entry with no contentzinvalid address in address-listzempty element in address-listrrr=r)rrrrrOrjrkrrurrr rOr@r8)rZ address_listrBerrrrrrrrget_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)rrrOr2rr8r~)rZno_fold_literalrBrrrget_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&rjrkrrrOr2r8roryrrur rr)rZmsg_idrBerrr 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(rrrrOr]r)rr r2)rZ message_idrBZexrrrparse_message_idSs$  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}r?digitsz0Incomplete MIME version; found only major numberzversion-separatorz1Expected MIME minor version number but found {!r}z'Excess non-CFWS text after MIME version)rrrrHeaderMissingRequiredValuerjrkisdigitr r2r8intrr)rZ mime_versionrBrrrrparse_mime_versionos                          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. rrr}rN)rrtrr8rv)rZinvalid_parameterrBrrrget_invalid_parameterrrcCrc)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_matcherrrOr2rrr8r@)rrfrrrr 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 '{}') rqrjrkr TOKEN_ENDSrrOr2r)rZmtokenrBrrr get_token       rcCrc)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_matcherrrOr2rrr8r@rrfrrrr 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) rrjrkrATTRIBUTE_ENDSrrOr2rrrrBrrr get_attribute rrcCrc)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_matcherrrOr2rrr8r@rrrrget_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) rrjrkrEXTENDED_ATTRIBUTE_ENDSrrOr2rrrrrget_extended_attribute+ 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) rrrOr2rr8rrr rr)rrrrrr get_sectionA 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) rrrOrjrkr2rlrr)rvrrrBrrr get_value_ s"      rc Cst}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|jdkr^|r>|ddkrU|||d urQ|rOJ||}||fS|jtd|sy|jtd|||d urx||fSnw|d ur|D] } | jdkrnq| jdk|| | j|_|ddkrt d||t dd|dd }|r|ddkrt|\}}|||j|_|r|ddkrt d||t dd|dd }|d ur-t} |r*|dtvr t|\}}n|dd krt d d}|dd }nt|\}}| ||s| }nt|\}}|||d urF|rDJ||}||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 invalidr~zZParameter 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)rrrrrr r2rrrOr8rrjrkrlrrrrrOrrrvrwrrTrJrb) rrrBrrrDZappendtoZqstringZ inner_valueZ semi_validrUtrrrr get_parameteru 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)rrrrrOrjrkrr rr2rOr@r8)rZmime_parametersrBrrrrrrrparse_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 rrr}rNr)rtrr8rvr)Z tokenlistrrBrrr_find_mime_parameters7 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}rr/zInvalid content typezcontent-type-separatorrNz'Expected content subtype but found {!r}rz. unknown-8bitTrrCrrzr~rrcSsg|] }tt|dqS)r)r8r)r&prrrra1 sz&_refold_parse_tree..)Zmax_line_lengthsysmaxsizeutf8r,r0rrrO SPECIALSNL isdisjointNLSETrzrrr7_fold_mime_parametersr=rTrGrr'rrrP _fold_as_ewrUr;r8insertr+)Z parse_treerDmaxlenrrlast_ewrZ want_encodingZend_ew_not_allowedrr>tstrrvZ encoded_partnewlineZnewpartsrrrrE s                  erEcCs|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[)rv) rr]rTrrrrrOrQrz)Z to_encoderrrrUrvZ leading_wspZ trailing_wspZ new_last_ewZ encode_as chrome_lenZremaining_spaceZ text_spaceZto_encode_wordZ encoded_wordZexcessrrrrH 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 {}*{}*={}{})rrrrzrrrrrrr2rrrr)r>rrrrrrvZ error_handlerZencoding_requiredZ encoded_valuerrZ extra_chromerZ splitpointZmaxcharspartialrrrr sn        r)rK)r;rerrstringroperatorrZemailrrQrrrrTrjrqrmrrtZ TSPECIALSrZ ASPECIALSrrrrrrcompileVERBOSE MULTILINErYr0rrXrerirkrlrnrqrsrzrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr!r$r%r&r(r)r*rr,r4r8r9rOr:rrrr2r+rrArEmatchrefindallr>rrrr@rHrJrWr]rarbrgrhrirkrlrnrorprsrvr|ryr~rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrErrrrrrsFE           C  "   !*$ V +        1C+ "&'/'&).9%7ED49/t A