o ?OgƢ @sdZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z e dZee d BZe d ZeeBZee d Zee d Zee d Be d ZeeBZee dBZeeBZee dZddhZeeBZddZedejejBZGddde Z!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!ZAGdWdXdXeAZBGdYdZdZe!ZCGd[d\d\e!ZDGd]d^d^e!ZEGd_d`d`e!ZFGdadbdbe!ZGGdcddddeGZHGdedfdfeGZIGdgdhdhe!ZJGdidjdje!ZKGdkdldle!ZLGdmdndneLZMGdodpdpeMZNGdqdrdre!ZOGdsdtdtePZQGdudvdveQZRGdwdxdxeQZSGdydzdzeRZTGd{d|d|e jUZVeSd d}ZWeSd~dZXeSddZYedZd[ej\Z]edZe^d[ej_Z`edjaZbedZe^d[ej_ZcedZe^d[ej_ZdedZe^d[ej_ZeddZfddZgddZhddZiddZjddZkddZlddZmddZnddZoddZpddZqddZrddZsddZtddZuddZvddZwddZxddZyddZzddZ{ddZ|ddZ}ddZ~ddZddZddZddZddZddÄZddńZddDŽZddɄZdd˄Zdd̈́ZddτZddфZddӄZddՄZddׄZddلZddۄZdd݄Zdd߄ZddZddZddZddZddZddZddZddZddZddZddZddZddZdS)alHeader value parser implementing various email-related RFC parsing rules. The parsing methods defined in this module implement various email related parsing rules. Principal among them is RFC 5322, which is the followon to RFC 2822 and primarily a clarification of the former. It also implements RFC 2047 encoded word decoding. RFC 5322 goes to considerable trouble to maintain backward compatibility with RFC 822 in the parse phase, while cleaning up the structure on the generation phase. This parser supports correct RFC 5322 generation by tagging white space as folding white space only when folding is allowed in the non-obsolete rule sets. Actually, the parser is even more generous when accepting input than RFC 5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages. Where possible deviations from the standard are annotated on the 'defects' attribute of tokens that deviate. The general structure of the parser follows RFC 5322, and uses its terminology where there is a direct correspondence. Where the implementation requires a somewhat different structure than that used by the formal grammar, new terms that mimic the closest existing terms are used. Thus, it really helps to have a copy of RFC 5322 handy when studying this code. Input to the parser is a string that has already been unfolded according to RFC 5322 rules. According to the RFC this unfolding is the very first step, and this parser leaves the unfolding step to a higher level message parser, which will have already detected the line breaks that need unfolding while determining the beginning and end of each header. The output of the parser is a TokenList object, which is a list subclass. A TokenList is a recursive data structure. The terminal nodes of the structure are Terminal objects, which are subclasses of str. These do not correspond directly to terminal objects in the formal grammar, but are instead more practical higher level combinations of true terminals. All TokenList and Terminal objects have a 'value' attribute, which produces the semantically meaningful value of that part of the parse subtree. The value of all whitespace tokens (no matter how many sub-tokens they may contain) is a single space, as per the RFC rules. This includes 'CFWS', which is herein included in the general class of whitespace tokens. There is one exception to the rule that whitespace tokens are collapsed into single spaces in values: in the value of a 'bare-quoted-string' (a quoted-string with no leading or trailing whitespace), any whitespace that appeared between the quotation marks is preserved in the returned value. Note that in all Terminal strings quoted pairs are turned into their unquoted values. All TokenList and Terminal objects also have a string value, which attempts to be a "canonical" representation of the RFC-compliant form of the substring that produced the parsed subtree, including minimal use of quoted pair quoting. Whitespace runs are not collapsed. Comment tokens also have a 'content' attribute providing the string found between the parens (including any nested comments) with whitespace preserved. All TokenList and Terminal objects have a 'defects' attribute which is a possibly empty list all of the defects found while creating the token. Defects may appear on any token in the tree, and a composite list of all defects in the subtree is available through the 'all_defects' attribute of any node. (For Terminal notes x.defects == x.all_defects.) Each object in a parse tree is called a 'token', and each has a 'token_type' attribute that gives the name from the RFC 5322 grammar that it represents. Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that may be produced: 'ptext'. A 'ptext' is a string of printable ascii characters. It is returned in place of lists of (ctext/quoted-pair) and (qtext/quoted-pair). XXX: provide complete list of token types. N) hexdigits) itemgetter)_encoded_words)errors)utilsz (z ()<>@,:;.\"[].z."(z/?=z*'%%  cCs dt|dddddS)N"\\\z\")strreplacevaluerA/opt/alt/python310/lib64/python3.10/email/_header_value_parser.py quote_stringbs 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__rrr{s zTokenList.__init__cCddd|DS)Ncs|]}t|VqdSrr.0xrrr z$TokenList.__str__..joinrrrr__str__zTokenList.__str__cd|jjtSNz{}({})formatr__name__r__repr__r+rrrr3s 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+rrrr6szTokenList.all_defectscCs |dSNr)startswith_fwsr+rrrr: zTokenList.startswith_fwscCstdd|DS)zATrue if all top level tokens of this part may be RFC2047 encoded.csr5r) as_ew_allowed)r%partrrrr'r7z*TokenList.as_ew_allowed..)allr+rrrr<szTokenList.as_ew_allowedcCsg}|D]}||jq|Sr)extendcomments)rr@tokenrrrr@szTokenList.commentscCs t||dS)Npolicy)_refold_parse_treerrCrrrfoldr;zTokenList.foldr!cCst|j|ddS)Nindent)printppstrrrHrrrpprintr-zTokenList.pprintcCsd|j|dS)Nr rG)r*_pprKrrrrJszTokenList.ppstrccs|d||jj|jV|D]}t|ds|d|Vq||dEdHq|jr3d|j}nd}d||VdS)Nz{}{}/{}(rMz* !! invalid element in token list: {!r}z z Defects: {}r!z{}){})r1rr2 token_typehasattrrMr)rrHrAZextrarrrrMs  z TokenList._ppr!)r2 __module__ __qualname__rNsyntactic_breakew_combine_allowedrr,r3propertyrr6r:r<r@rFrLrJrM __classcell__rrrrrus(        rc@s$eZdZeddZeddZdS)WhiteSpaceTokenListcCdSN rr+rrrrzWhiteSpaceTokenList.valuecCdd|DS)NcSg|] }|jdkr|jqS)comment)rNcontentr$rrr z0WhiteSpaceTokenList.comments..rr+rrrr@zWhiteSpaceTokenList.commentsN)r2rQrRrUrr@rrrrrWs  rWc@eZdZdZdS)UnstructuredTokenList unstructuredNr2rQrRrNrrrrrdrdc@rc)PhrasephraseNrfrrrrrhrgrhc@rc)WordZwordNrfrrrrrjrgrjc@rc)CFWSListcfwsNrfrrrrrkrgrkc@rc)AtomatomNrfrrrrrmrgrmc@eZdZdZdZdS)TokenrAFN)r2rQrRrNZ encode_as_ewrrrrrprpc@seZdZdZdZdZdZdS) EncodedWord encoded-wordN)r2rQrRrNctecharsetlangrrrrrr rrc@4eZdZdZeddZeddZeddZdS) QuotedString quoted-stringcC"|D] }|jdkr|jSqdSNbare-quoted-stringrNrrr&rrrr_   zQuotedString.contentcCs>g}|D]}|jdkr|t|q||jqd|S)Nr}r!)rNappendrrr*)rresr&rrr quoted_values   zQuotedString.quoted_valuecCr{r|r~rrArrrstripped_valuerzQuotedString.stripped_valueN)r2rQrRrNrUr_rrrrrrrys   ryc@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+rrrrr4zBareQuotedString.valueN)r2rQrRrNr,rUrrrrrrs rc@s8eZdZdZddZddZeddZedd Zd S) Commentr^cs(dtdgfddDdgggS)Nr!rcsg|]}|qSr)quoter$r+rrr`sz#Comment.__str__..))r*r8r+rr+rr, szComment.__str__cCs2|jdkr t|St|ddddddS)Nr^r rrz\(rz\))rNrr)rrrrrrs z Comment.quotecCr )Nr!csr"rr#r$rrrr'r(z"Comment.content..r)r+rrrr_r4zComment.contentcCs|jgSr)r_r+rrrr@szComment.commentsN) r2rQrRrNr,rrUr_r@rrrrr s rc@rx) AddressListz address-listcCr\)NcSg|] }|jdkr|qS)addressrNr$rrrr`)z)AddressList.addresses..rr+rrr addresses'rbzAddressList.addressescCtdd|DgS)Ncs |] }|jdkr|jVqdSrNrN mailboxesr$rrrr'-  z(AddressList.mailboxes..r8r+rrrr+ zAddressList.mailboxescCr)NcsrrrN all_mailboxesr$rrrr'2rz,AddressList.all_mailboxes..rr+rrrr0rzAddressList.all_mailboxesN)r2rQrRrNrUrrrrrrrr#s  rc@rx) AddressrcC|djdkr |djSdS)NrgrouprN display_namer+rrrr: zAddress.display_namecCs4|djdkr |dgS|djdkrgS|djSNrmailboxinvalid-mailboxrr+rrrr?s   zAddress.mailboxescCs:|djdkr |dgS|djdkr|dgS|djSrrr+rrrrGs    zAddress.all_mailboxesN)r2rQrRrNrUrrrrrrrr6s  rc@(eZdZdZeddZeddZdS) MailboxList mailbox-listcCr\)NcSr)rrr$rrrr`Urz)MailboxList.mailboxes..rr+rrrrSrbzMailboxList.mailboxescCr\)NcSsg|] }|jdvr|qS))rrrr$rrrr`Ys z-MailboxList.all_mailboxes..rr+rrrrWrbzMailboxList.all_mailboxesNr2rQrRrNrUrrrrrrrOs  rc@r) GroupList group-listcC |r |djdkr gS|djSNrrrr+rrrra zGroupList.mailboxescCrrrr+rrrrgrzGroupList.all_mailboxesNrrrrrr]s  rc@rx) GrouprcC|djdkr gS|djSNrrr+rrrrr zGroup.mailboxescCrrrr+rrrrxrzGroup.all_mailboxescC |djSr9)rr+rrrr~ zGroup.display_nameN)r2rQrRrNrUrrrrrrrrns  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 r2rQrRrNrUrrrrrrrrrrs    rc@s@eZdZdZeddZeddZeddZedd Zd S) AngleAddrz angle-addrcCr{N addr-spec)rNrrrrrrrzAngleAddr.local_partcCr{rrNrrrrrrrzAngleAddr.domaincCr{)N obs-route)rNdomainsrrrrrrzAngleAddr.routecCs<|D]}|jdkr|jr|jSt|j|jSqdS)Nrz<>)rNrrrrrrrrs  zAngleAddr.addr_specN) r2rQrRrNrUrrrrrrrrrs   rc@eZdZdZeddZdS)ObsRoutercCr\)NcSr]rrr$rrrr`raz$ObsRoute.domains..rr+rrrrrbzObsRoute.domainsN)r2rQrRrNrUrrrrrrrc@r) MailboxrcCrNrrrr+rrrrrzMailbox.display_namecCrr9rr+rrrrrzMailbox.local_partcCrr9rr+rrrrrzMailbox.domaincCrr)rNrr+rrrrrz Mailbox.routecCrr9rr+rrrrrzMailbox.addr_specNrrrrrrs    rc@s,eZdZdZeddZeZZZZ dS)InvalidMailboxrcCdSrrr+rrrrr[zInvalidMailbox.display_nameNrrrrrrs  rcs(eZdZdZdZefddZZS)DomainrFcdtjSNr!r*rrsplitr+rrrrz Domain.domain)r2rQrRrNr<rUrrVrrrrrs rc@rc)DotAtomdot-atomNrfrrrrrrgrc@ro) DotAtomTextz dot-atom-textTNr2rQrRrNr<rrrrrrqrc@ro) NoFoldLiteralzno-fold-literalFNrrrrrrrqrc@sDeZdZdZdZeddZeddZeddZed d Z d S) AddrSpecrFcCrr9rr+rrrr rzAddrSpec.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)rZnamesetZlprrrrs   zAddrSpec.addr_specN) r2rQrRrNr<rUrrrrrrrrrs   rc@ro) ObsLocalPartzobs-local-partFNrrrrrr(rcs4eZdZdZdZeddZefddZZS) DisplayNamez display-nameFcCst|}t|dkr |jS|djdkr|dn|ddjdkr/t|ddd|d<|djdkr=||jS|ddjdkrRt|ddd|d<|jS)Nrrlrr)rrrrNpop)rrrrrr3s  zDisplayName.display_namecsd}|jrd}n |D] }|jdkrd}q t|dkrM|rMd}}|djdks0|ddjdkr2d}|djdksB|ddjdkrDd}|t|j|StjS) NFTrzrr!rlrZr)rrNrrrrr)rrr&ZpreZpostrrrrDs   zDisplayName.value) r2rQrRrNrTrUrrrVrrrrr.s rc@s,eZdZdZdZeddZeddZdS) LocalPartz local-partFcCs"|djdkr |djS|djS)Nrrz)rNrrr+rrrr]s  zLocalPart.valuecCstg}t}d}|dtgD]J}|jdkrq|r.|jdkr.|djdkr.t|dd|d<t|t}|rM|jdkrM|djdkrM|t|ddn|||d}|}qt|dd}|jS)NFrrldotrr)DOTrNr isinstancerr)rrZlastZ last_is_tltokZis_tlrrrrds$   zLocalPart.local_partN)r2rQrRrNr<rUrrrrrrrXs rcs4eZdZdZdZefddZeddZZS) DomainLiteralzdomain-literalFcrrrr+rrrrrzDomainLiteral.domaincCr{)Nptextr~rrrriprzDomainLiteral.ip) r2rQrRrNr<rUrrrVrrrrr|src@seZdZdZdZdZdS) MIMEVersionz mime-versionN)r2rQrRrNmajorminorrrrrrsrc@s4eZdZdZdZdZdZeddZeddZ dS) Parameter parameterFus-asciicCs|jr|djSdSr) sectionednumberr+rrrsection_numberszParameter.section_numbercCsf|D].}|jdkr|jS|jdkr0|D]}|jdkr/|D]}|jdkr.|jSqqqdS)Nrrzr}r!)rNrrrrr param_values     zParameter.param_valueN) r2rQrRrNrextendedrurUrrrrrrrs rc@rc)InvalidParameterinvalid-parameterNrfrrrrrsrc@r) Attribute attributecCs$|D] }|jdr|jSqdS)Nattrtext)rNendswithrrrrrrs   zAttribute.stripped_valueNr2rQrRrNrUrrrrrrrrc@seZdZdZdZdS)SectionsectionN)r2rQrRrNrrrrrrrrc@r)ValuercCs2|d}|jdkr |d}|jdr|jS|jS)Nrrlr)rzrzextended-attribute)rNrrrrrrrrs 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!)rNrrstriprritemssortedrrurrrrInvalidHeaderDefectrurllibparseZunquote_to_bytesUnicodeEncodeErrorZunquotedecode LookupErrorr_has_surrogatesUndecodableBytesDefectr*) rparamsrAnamepartsZ first_paramruZ value_partsirparamrrrrrsh           zMimeParameters.paramscCsTg}|jD]\}}|r|d|t|q||qd|}|r(d|SdS)N{}={}z; rZr!)rrr1rr*)rrrrrrrr,s  zMimeParameters.__str__N)r2rQrRrNrSrUrr,rrrrrs   Erc@r)ParameterizedHeaderValueFcCs&t|D] }|jdkr|jSqiS)Nr)reversedrNrrrrrr/s   zParameterizedHeaderValue.paramsN)r2rQrRrSrUrrrrrr)src@seZdZdZdZdZdZdS) ContentTypez content-typeFtextZplainN)r2rQrRrNr<maintypesubtyperrrrr7rwrc@seZdZdZdZdZdS)ContentDispositionzcontent-dispositionFN)r2rQrRrNr<content_dispositionrrrrr >r c@seZdZdZdZdZdS)ContentTransferEncodingzcontent-transfer-encodingFZ7bitN)r2rQrRrNr<rtrrrrr#Dr"r#c@ro) HeaderLabelz header-labelFNrrrrrr$Jrqr$c@seZdZdZdZddZdS)MsgIDzmsg-idFcCst||jSr)rlineseprErrrrFSrbz MsgID.foldN)r2rQrRrNr<rFrrrrr%Os r%c@rc) MessageIDz message-idNrfrrrrr'Xrgr'c@rc)InvalidMessageIDzinvalid-message-idNrfrrrrr(\rgr(c@rc)HeaderheaderNrfrrrrr)`rgr)csreZdZdZdZdZfddZfddZddZe dd Z dfd d Z d dZ e ddZ ddZZS)TerminalTcst||}||_g|_|Sr)r__new__rNr)clsrrNrrrrr,nszTerminal.__new__cr.r/r0r+rrrr3tszTerminal.__repr__cCst|jjd|jdS)N/)rIrr2rNr+rrrrLwszTerminal.pprintcCs t|jSr)listrr+rrrr6zrzTerminal.all_defectsr!c s6d||jj|jt|jsdgSd|jgS)Nz {}{}/{}({}){}r!z {})r1rr2rNrr3rrKrrrrM~s z Terminal._ppcCrrrr+rrrpop_trailing_wsr[zTerminal.pop_trailing_wscCsgSrrr+rrrr@r[zTerminal.commentscCst||jfSr)rrNr+rrr__getnewargs__szTerminal.__getnewargs__rP)r2rQrRr<rTrSr,r3rLrUr6rMr0r@r1rVrrrrr+hs     r+c@ eZdZeddZddZdS)WhiteSpaceTerminalcCrXrYrr+rrrrr[zWhiteSpaceTerminal.valuecCrX)NTrr+rrrr:z!WhiteSpaceTerminal.startswith_fwsNr2rQrRrUrr:rrrrr3  r3c@r2) ValueTerminalcCs|Srrr+rrrrr[zValueTerminal.valuecCrX)NFrr+rrrr:r4zValueTerminal.startswith_fwsNr5rrrrr7r6r7c@r2)EWWhiteSpaceTerminalcCrXrrr+rrrrr[zEWWhiteSpaceTerminal.valuecCrXrrr+rrrr,r4zEWWhiteSpaceTerminal.__str__N)r2rQrRrUrr,rrrrr8r6r8c@rc)_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r2rQrR__doc__rrrrr9rgr9r,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$   $rGcCs.|}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)rr3r)rZnewvaluerHrrrget_fwssrIc 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| d } 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: '{}'vtextz.missing trailing whitespace after encoded-word)rr startswithrHeaderParseErrorr1rr*rrcountrrr rt_ewr ValueErrorKeyErrorr9rurvr?WSPrIr@r7r?) rZewrrCZremstrrestrrurvrrAcharsrLrrrget_encoded_wordsb                 rVcCs>t}|r|dtvrt|\}}||qd}|drszt|\}}Wnty1d}YnBtjy:Yn9wd}t |dkrU|dj dkrU|j t dd}|rmt |dkrm|d j d krmt |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. rTrJFrrHz&missing whitespace before encoded wordrrsrLr!)rdrSrIrrMrVr9rrNrrNrr r8r@rfc2047_matchersearch partitionr7r?r*)rrerAvalid_ewZhave_wsrrCrLrrrget_unstructuredAsL           )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)rGr3r?rr_rrr get_qp_ctexts r`cCr])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. r r)rGr7r?r^rrr get_qcontents racCNt|}|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_matcherrrNr1rrr7r?)rmrcrrr get_atexts rfcCsn|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. rr zexpected '"' but found '{}'rNrrJFz!encoded word inside quoted stringTrrHrWrsz"end of header inside quoted string)rrNr1rrarrSrIrVrr rrNr8)rZbare_quoted_stringrAr[rrrget_bare_quoted_stringsN          rgcCs|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) rrNr1rrSrI get_commentr`rrr )rr^rArrrrhs(      rhcCs^t}|r+|dtvr+|dtvrt|\}}nt|\}}|||r+|dtvs ||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS r)rk CFWS_LEADERrSrIrhr)rrlrArrrget_cfwss   rjcCspt}|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)ryrirjrrg)rZ quoted_stringrArrrget_quoted_strings      rkcCst}|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 '{}'rJ) rmrirjr ATOM_ENDSrrNr1rMrVrf)rrnrArrrget_atoms(       rmcCst}|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 '{}')rrlrrNr1rfrr)rZ dot_atom_textrArrrget_dot_atom_text2s"      rncCst}|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. rrJ) rrirjrrMrVrrNrn)rZdot_atomrArrr get_dot_atomEs         rocCs|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.r z1Expected 'atom' or 'quoted-string' but found '{}')rirjrrNrkSPECIALSr1rm)rleaderrArrrget_word^s"    rrcCst}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) rhrrrrrNrr  PHRASE_ENDSrObsoleteHeaderDefectrirj)rrirArrr get_phrases<           ruc 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)rGr7rrrrtr?)rrrErrr get_dtexts  r}cCs,|rdS|td|tdddS)NFz"end of input inside domain-literal]domain-literal-endT)rrr r7)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-startr~z4expected ']' at end of domain-literal but found '{}'r) rrirjrrrNr1rr7rSrIr})rrrArrrget_domain_literalsH                     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)rrirjrrNr1rrrormrrtrNr)rrrqrArrr get_domain?sH          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 r7r)rrrArrr get_addr_speces    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) rrirjr ListSeparatorrrNr1RouteComponentMarkerrr7)rZ obs_routerArrr get_obs_routeusJ                  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) rrirjrrrNr1r7rr rrrt)rZ angle_addrrArrrget_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)rrur?r)rrrArrrget_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) rrirjrrNr1rsrrr)rZ name_addrrqrArrr get_name_addrs6        rc Cst}zt|\}}Wn#tjy.zt|\}}Wntjy+td|wYnwtdd|jDr.r) rrrrNrr1anyr6rNr)rrrArrr 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)rrsrr7ru)rrBZinvalid_mailboxrArrrget_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)rrrrrNrirjrrtrr rNr?r)rZ mailbox_listrArqrrrrget_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 rirjrrrr?rt)rZ group_listrqrArrrget_group_listYs>           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 {}) rrrrNr1rr7rrr rirj)rrrArrr get_group~s8          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 '{}')rrrrNrr1r)rrrArrr 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)rrrrrNrirjrrtrrr rNr?r7)rZ address_listrAerrrqrrrrget_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-startrNr~z9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)rrrNr1rr7r})rZno_fold_literalrArrrget_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%rirjrrrNr1r7rnrxrrtr rr)rZmsg_idrAerrr 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'rrrrNr\r(rr r1)rZ message_idrAZexrrrparse_message_idKs$  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)rrrrHeaderMissingRequiredValuerirjisdigitr r1r7intrr)rZ mime_versionrArrrrparse_mime_versiongs                          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)rrsrr7ru)rZinvalid_parameterrArrrget_invalid_parameterrrcCrb)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_matcherrrNr1rrr7r?)rrerrrr 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 '{}') rprirjr TOKEN_ENDSrrNr1r)rZmtokenrArrr get_token       rcCrb)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_matcherrrNr1rrr7r?rrerrrr 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) rrirjrATTRIBUTE_ENDSrrNr1rrrrArrr get_attributerrcCrb)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_matcherrrNr1rrr7r?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) rrirjrEXTENDED_ATTRIBUTE_ENDSrrNr1rrrrrget_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) rrrNr1rr7rrr rr)rrrrrr get_section9 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 ) rrrNrirjr1rkrr)rvrqrArrr get_valueW 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-separatorr F'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 r1rrrNr7rrirjrkrrrrrNrrrurvrrSrIra) rrrArqrCZappendtoZqstringZ inner_valueZ semi_validrTtrrrr get_parameterm 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)rrrrrNrirjrr rr1rNr?r7)rZmime_parametersrArrqrrrrparse_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)rsrr7rur)Z tokenlistrrArrr_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}rr.zInvalid content typezcontent-type-separatorrNz'Expected content subtype but found {!r}rz. unknown-8bitTrrBrry)Zmax_line_lengthsysmaxsizeutf8r+r/rrrN SPECIALSNL isdisjointNLSETryrrr6_fold_mime_parametersr<rSrFrr&rrrO _fold_as_ewrTr:insertr*)Z parse_treerCmaxlenrrlast_ewrZ want_encodingZend_ew_not_allowedrr=tstrruZ encoded_partnewlineZnewpartsrrrrD s               \rDcCs|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 wordrZ)ru) rr\rSrrrrrNrPry)Z to_encoderrrrTruZ leading_wspZ trailing_wspZ new_last_ewZ encode_as chrome_lenZremaining_spaceZ text_spaceZto_encode_wordZ encoded_wordZexcessrrrr7 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'. rrstrictFTrrrr!)Zsaferz {}*={}''{}rrrZrrz''rNNz {}*{}*={}{})rrrryrrrr rrr1rrrr)r=rrrrrruZ error_handlerZencoding_requiredZ encoded_valuerrZ extra_chromerZ splitpointZmaxcharspartialrrrrx sn        r)r:rerr stringroperatorrZemailrrPrrrrSrirprlrrsZ TSPECIALSrZ ASPECIALSrrrrrcompileVERBOSE MULTILINErXr/rrWrdrhrjrkrmrprrryrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr r#r$r%r'r(r)rr+r3r7r8rNr9rrrr1r*rr@rDmatchrdfindallr=rrrr?rGrIrVr\r`rarfrgrhrjrkrmrnrorrrur{rxr}rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrDrrrrrrsDE           C  "   !*$ V +        1C+ "&'/'&).9%7ED49/k A