U e5dϡ @sdZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z e dZee d BZe d ZeeBZee d Zee d Zee d Be d ZeeBZee dBZeeBZee dZddZedejejBZGdddeZGdddeZ GdddeZ!GdddeZ"GdddeZ#Gddde Z$Gdd d eZ%Gd!d"d"eZ&Gd#d$d$eZ'Gd%d&d&eZ(Gd'd(d(e(Z)Gd)d*d*e Z*Gd+d,d,eZ+Gd-d.d.eZ,Gd/d0d0eZ-Gd1d2d2eZ.Gd3d4d4eZ/Gd5d6d6eZ0Gd7d8d8eZ1Gd9d:d:eZ2Gd;d<dd>eZ4Gd?d@d@eZ5GdAdBdBeZ6GdCdDdDeZ7GdEdFdFeZ8GdGdHdHeZ9GdIdJdJeZ:GdKdLdLe"Z;GdMdNdNeZGdSdTdTeZ?GdUdVdVe?Z@GdWdXdXeZAGdYdZdZeZBGd[d\d\eZCGd]d^d^eZDGd_d`d`eZEGdadbdbeEZFGdcddddeEZGGdedfdfeZHGdgdhdheZIGdidjdjeZJGdkdldleJZKGdmdndneKZLGdodpdpeZMGdqdrdreNZOGdsdtdteOZPGdudvdveOZQGdwdxdxePZRGdydzdze jSZTeQd d{ZUeQd|d}ZVeQd~dZWedXdYejZZ[edXe\dYej]Z^edj_Z`edXe\dYej]ZaedXe\dYej]ZbedXe\dYej]ZcddZdddZeddZfddZgddZhddZiddZjddZkddZlddZmddZnddZoddZpddZqddZrddZsddZtddZuddZvddZwddZxddZyddZzddZ{ddZ|ddZ}ddZ~ddZddZddZddZddÄZddńZddDŽZddɄZdd˄Zdd̈́ZddτZddфZddӄZddՄZddׄZddلZddۄZdd݄Zdd߄ZddZddZddZddZddZddZddZddZddZddZddZddZdS)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\")strreplacevaluer2/usr/lib64/python3.8/email/_header_value_parser.py quote_string`srz =\? # 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||g|_dSN)super__init__defects)selfargskw __class__rrryszTokenList.__init__cCsddd|DS)Ncss|]}t|VqdSrr .0xrrr ~sz$TokenList.__str__..joinrrrr__str__}szTokenList.__str__csd|jjtSNz{}({})formatr__name__r__repr__r&rrrr,s zTokenList.__repr__cCsddd|DS)Nrcss|]}|jr|jVqdSrrr rrrr#sz"TokenList.value..r$r&rrrrszTokenList.valuecCstdd|D|jS)Ncss|] }|jVqdSr) all_defectsr rrrr#sz(TokenList.all_defects..)sumrr&rrrr-szTokenList.all_defectscCs |dSNr)startswith_fwsr&rrrr0szTokenList.startswith_fwscCstdd|DS)zATrue if all top level tokens of this part may be RFC2047 encoded.css|] }|jVqdSr) as_ew_allowed)r!partrrrr#sz*TokenList.as_ew_allowed..)allr&rrrr1szTokenList.as_ew_allowedcCsg}|D]}||jq|Sr)extendcomments)rr5tokenrrrr5szTokenList.commentscCs t||dS)Npolicy)_refold_parse_treerr8rrrfoldszTokenList.foldrcCst|j|ddS)Nindent)printppstrrr=rrrpprintszTokenList.pprintcCsd|j|dS)N r<)r%_ppr@rrrr?szTokenList.ppstrccszd||jj|jV|D]4}t|ds:|d|Vq||dEdHq|jrdd|j}nd}d||VdS)Nz{}{}/{}(rCz* !! invalid element in token list: {!r}z z Defects: {}rz{}){})r*rr+ token_typehasattrrCr)rr=r6ZextrarrrrCs  z TokenList._pp)r)r)r)r+ __module__ __qualname__rDsyntactic_breakew_combine_allowedrr'r,propertyrr-r0r1r5r;rAr?rC __classcell__rrrrrss&        rc@s$eZdZeddZeddZdS)WhiteSpaceTokenListcCsdSN rr&rrrrszWhiteSpaceTokenList.valuecCsdd|DS)NcSsg|]}|jdkr|jqS)comment)rDcontentr rrr s z0WhiteSpaceTokenList.comments..rr&rrrr5szWhiteSpaceTokenList.commentsN)r+rFrGrJrr5rrrrrLs rLc@seZdZdZdS)UnstructuredTokenList unstructuredNr+rFrGrDrrrrrRsrRc@seZdZdZdS)PhrasephraseNrTrrrrrUsrUc@seZdZdZdS)WordZwordNrTrrrrrWsrWc@seZdZdZdS)CFWSListcfwsNrTrrrrrXsrXc@seZdZdZdS)AtomatomNrTrrrrrZsrZc@seZdZdZdZdS)Tokenr6FN)r+rFrGrDZ encode_as_ewrrrrr\sr\c@seZdZdZdZdZdZdS) EncodedWord encoded-wordN)r+rFrGrDctecharsetlangrrrrr]sr]c@s4eZdZdZeddZeddZeddZdS) QuotedString quoted-stringcCs"|D]}|jdkr|jSqdSNbare-quoted-stringrDrrr"rrrrPs zQuotedString.contentcCs>g}|D]*}|jdkr&|t|q||jqd|S)Nrer)rDappendr rr%)rresr"rrr quoted_values  zQuotedString.quoted_valuecCs"|D]}|jdkr|jSqdSrdrfrr6rrrstripped_values zQuotedString.stripped_valueN)r+rFrGrDrJrPrjrlrrrrrbs  rbc@s$eZdZdZddZeddZdS)BareQuotedStringrecCstddd|DS)Nrcss|]}t|VqdSrrr rrrr#sz+BareQuotedString.__str__..)rr%r&rrrr'szBareQuotedString.__str__cCsddd|DS)Nrcss|]}t|VqdSrrr rrrr#sz)BareQuotedString.value..r$r&rrrrszBareQuotedString.valueN)r+rFrGrDr'rJrrrrrrmsrmc@s8eZdZdZddZddZeddZedd Zd S) CommentrOcs(dtdgfddDdgggS)Nrrcsg|]}|qSr)quoter r&rrrQsz#Comment.__str__..))r%r.r&rr&rr' szComment.__str__cCs2|jdkrt|St|ddddddS)NrOr r rz\(rpz\))rDr r)rrrrrros z Comment.quotecCsddd|DS)Nrcss|]}t|VqdSrrr rrrr#sz"Comment.content..r$r&rrrrPszComment.contentcCs|jgSr)rPr&rrrr5szComment.commentsN) r+rFrGrDr'rorJrPr5rrrrrns rnc@s4eZdZdZeddZeddZeddZdS) AddressListz address-listcCsdd|DS)NcSsg|]}|jdkr|qS)addressrDr rrrrQ's z)AddressList.addresses..rr&rrr addresses%szAddressList.addressescCstdd|DgS)Ncss|]}|jdkr|jVqdSrrNrD mailboxesr rrrr#+s z(AddressList.mailboxes..r.r&rrrrw)s zAddressList.mailboxescCstdd|DgS)Ncss|]}|jdkr|jVqdSrurD all_mailboxesr rrrr#0s z,AddressList.all_mailboxes..rxr&rrrrz.s zAddressList.all_mailboxesN)r+rFrGrDrJrtrwrzrrrrrq!s  rqc@s4eZdZdZeddZeddZeddZdS) AddressrrcCs|djdkr|djSdS)NrgrouprD display_namer&rrrr~8szAddress.display_namecCs4|djdkr|dgS|djdkr*gS|djSNrmailboxinvalid-mailboxrvr&rrrrw=s  zAddress.mailboxescCs:|djdkr|dgS|djdkr0|dgS|djSrryr&rrrrzEs   zAddress.all_mailboxesN)r+rFrGrDrJr~rwrzrrrrr{4s  r{c@s(eZdZdZeddZeddZdS) MailboxList mailbox-listcCsdd|DS)NcSsg|]}|jdkr|qS)rrsr rrrrQSs z)MailboxList.mailboxes..rr&rrrrwQszMailboxList.mailboxescCsdd|DS)NcSsg|]}|jdkr|qS))rrrsr rrrrQWs z-MailboxList.all_mailboxes..rr&rrrrzUszMailboxList.all_mailboxesNr+rFrGrDrJrwrzrrrrrMs  rc@s(eZdZdZeddZeddZdS) GroupList group-listcCs |r|djdkrgS|djSNrrrvr&rrrrw_szGroupList.mailboxescCs |r|djdkrgS|djSrryr&rrrrzeszGroupList.all_mailboxesNrrrrrr[s  rc@s4eZdZdZeddZeddZeddZdS) Groupr|cCs|djdkrgS|djSNrrvr&rrrrwpszGroup.mailboxescCs|djdkrgS|djSrryr&rrrrzvszGroup.all_mailboxescCs |djSr/)r~r&rrrr~|szGroup.display_nameN)r+rFrGrDrJrwrzr~rrrrrls  rc@sLeZdZdZeddZeddZeddZedd Zed d Z d S) NameAddr name-addrcCst|dkrdS|djSNr)lenr~r&rrrr~s zNameAddr.display_namecCs |djSN local_partr&rrrrszNameAddr.local_partcCs |djSrdomainr&rrrrszNameAddr.domaincCs |djSr)router&rrrrszNameAddr.routecCs |djSr addr_specr&rrrrszNameAddr.addr_specN r+rFrGrDrJr~rrrrrrrrrs    rc@s@eZdZdZeddZeddZeddZedd Zd S) AngleAddrz angle-addrcCs"|D]}|jdkr|jSqdSN addr-spec)rDrrgrrrrs zAngleAddr.local_partcCs"|D]}|jdkr|jSqdSrrDrrgrrrrs zAngleAddr.domaincCs"|D]}|jdkr|jSqdS)N obs-route)rDdomainsrgrrrrs zAngleAddr.routecCs<|D]2}|jdkr|jr"|jSt|j|jSqdS)Nrz<>)rDrrrrgrrrrs   zAngleAddr.addr_specN) r+rFrGrDrJrrrrrrrrrs   rc@seZdZdZeddZdS)ObsRoutercCsdd|DS)NcSsg|]}|jdkr|jqSrrr rrrrQs z$ObsRoute.domains..rr&rrrrszObsRoute.domainsN)r+rFrGrDrJrrrrrrsrc@sLeZdZdZeddZeddZeddZedd Zed d Z d S) MailboxrcCs|djdkr|djSdSNrrr}r&rrrr~szMailbox.display_namecCs |djSr/rr&rrrrszMailbox.local_partcCs |djSr/rr&rrrrszMailbox.domaincCs|djdkr|djSdSr)rDrr&rrrrsz Mailbox.routecCs |djSr/rr&rrrrszMailbox.addr_specNrrrrrrs    rc@s,eZdZdZeddZeZZZZ dS)InvalidMailboxrcCsdSrrr&rrrr~szInvalidMailbox.display_nameNrrrrrrs rcs(eZdZdZdZefddZZS)DomainrFcsdtjSNrr%rrsplitr&rrrrsz Domain.domain)r+rFrGrDr1rJrrKrrrrrsrc@seZdZdZdS)DotAtomdot-atomNrTrrrrrsrc@seZdZdZdZdS) DotAtomTextz dot-atom-textTNr+rFrGrDr1rrrrrsrc@seZdZdZdZdS) NoFoldLiteralzno-fold-literalFNrrrrrrsrc@sDeZdZdZdZeddZeddZeddZed d Z d S) AddrSpecrFcCs |djSr/rr&rrrr szAddrSpec.local_partcCst|dkrdS|djS)Nr)rrr&rrrrs zAddrSpec.domaincCs<t|dkr|djS|dj|dj|djS)Nrrrr)rrrstriplstripr&rrrrs  zAddrSpec.valuecCsLt|j}t|t|tkr*t|j}n|j}|jdk rH|d|jS|S)N@)setrr DOT_ATOM_ENDSrr)rZnamesetZlprrrrs   zAddrSpec.addr_specN) r+rFrGrDr1rJrrrrrrrrrs   rc@seZdZdZdZdS) ObsLocalPartzobs-local-partFNrrrrrr&srcs4eZdZdZdZeddZefddZZS) DisplayNamez display-nameFcCst|}t|dkr|jS|djdkr4|dn*|ddjdkr^t|ddd|d<|djdkrv|n*|ddjdkrt|ddd|d<|jS)NrrYrr)rrrrDpop)rrirrrr~1s   zDisplayName.display_namecsd}|jrd}n|D]}|jdkrd}qt|dkr|rd}}|djdks`|ddjdkrdd}|djdks|ddjdkrd}|t|j|StjSdS) NFTrcrrrYrNr)rrDrrr~rr)rror"ZpreZpostrrrrBs   zDisplayName.value) r+rFrGrDrIrJr~rrKrrrrr,s  rc@s,eZdZdZdZeddZeddZdS) LocalPartz local-partFcCs&|djdkr|djS|djSdS)Nrrc)rDrjrr&rrrr[s zLocalPart.valuecCstg}t}d}|dtgD]}|jdkr,q|r\|jdkr\|djdkr\t|dd|d<t|t}|r|jdkr|djdkr|t|ddn |||d}|}qt|dd}|jS)NFrrYdotrr)DOTrDr isinstancerhr)rriZlastZ last_is_tltokZis_tlrrrrbs(     zLocalPart.local_partN)r+rFrGrDr1rJrrrrrrrVs  rcs4eZdZdZdZefddZeddZZS) DomainLiteralzdomain-literalFcsdtjSrrr&rrrrszDomainLiteral.domaincCs"|D]}|jdkr|jSqdS)Nptextrfrgrrrips zDomainLiteral.ip) r+rFrGrDr1rJrrrKrrrrrzs rc@seZdZdZdZdZdS) MIMEVersionz mime-versionN)r+rFrGrDmajorminorrrrrrsrc@s4eZdZdZdZdZdZeddZeddZ dS) Parameter parameterFus-asciicCs|jr|djSdSr) sectionednumberr&rrrsection_numberszParameter.section_numbercCsf|D]\}|jdkr|jS|jdkr|D]4}|jdkr*|D] }|jdkr<|jSqrr+rDr&rrrrAuszTerminal.pprintcCs t|jSr)listrr&rrrr-xszTerminal.all_defectsrc s2d||jj|jt|js"dn d|jgS)Nz {}{}/{}({}){}rz {})r*rr+rDrr,rr@rrrrC|sz Terminal._ppcCsdSrrr&rrrpop_trailing_wsszTerminal.pop_trailing_wscCsgSrrr&rrrr5szTerminal.commentscCst||jfSr)r rDr&rrr__getnewargs__szTerminal.__getnewargs__)r)r+rFrGr1rIrHrr,rArJr-rCrr5rrKrrrrrfs     rc@s eZdZeddZddZdS)WhiteSpaceTerminalcCsdSrMrr&rrrrszWhiteSpaceTerminal.valuecCsdS)NTrr&rrrr0sz!WhiteSpaceTerminal.startswith_fwsNr+rFrGrJrr0rrrrrs rc@s eZdZeddZddZdS) ValueTerminalcCs|Srrr&rrrrszValueTerminal.valuecCsdS)NFrr&rrrr0szValueTerminal.startswith_fwsNrrrrrrs rc@s eZdZeddZddZdS)EWWhiteSpaceTerminalcCsdSrrr&rrrrszEWWhiteSpaceTerminal.valuecCsdSrrr&rrrr'szEWWhiteSpaceTerminal.__str__N)r+rFrGrJrr'rrrrrs rc@seZdZdZdS)_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r+rFrG__doc__rrrrrsrr,list-separatorrzroute-component-markerz([{}]+)rz[^{}]+z[\x00-\x20\x7F]cCs>t|}|r|jt|t|r:|jtddS)z@If input token contains ASCII non-printables, register a defect.z*Non-ASCII characters found in header tokenN)_non_printable_finderrrhrZNonPrintableDefectrrr)xtextZnon_printablesrrr_validate_xtexts  r cCst|d^}}g}d}d}tt|D]L}||dkrJ|rDd}d}nd}q&|rTd}n|||krdq||||q&|d}d|d||dg||fS)akScan printables/quoted-pairs until endchars and return unquoted ptext. This function turns a run of qcontent, ccontent-without-comments, or dtext-with-quoted-printables into a single string by unquoting any quoted printables. It returns the string, the remaining value, and a flag that is True iff there were any quoted printables decoded. rFr TrN) _wsp_splitterrangerrhr%)rendcharsZfragment remainderZvcharsescapehad_qpposrrr_get_ptext_to_endcharss$   rcCs.|}t|dt|t|d}||fS)zFWS = 1*WSP This isn't the RFC definition. We're using fws to represent tokens where folding can be done, but when we are parsing the *un*folding has already been done so we don't need to watch out for CRLF. Nfws)rrr)rZnewvaluerrrrget_fwssrc Cst}|ds td||dddd^}}||ddkrXtd|d|}t|dkr|dtkr|dtkr| d dkr|dd^}}|d|}t|dkr|j t d ||_ d|}ztd|d\}}}} Wn*ttfk r*td |j YnX||_||_|j | |r|dtkrrt|\} }| | qDt|d^} }t| d } t| | | d|}qD|r|dtkr|j t d ||fS)zE encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" =?z"expected encoded word but found {}rNz?=rrr?zwhitespace inside encoded wordz!encoded word format invalid: '{}'vtextz.missing trailing whitespace after encoded-word)r] startswithrHeaderParseErrorr*rr%rrcountrrhrr__ewr ValueErrorKeyErrorrr`rar4WSPrr rr ) rZewrrZremstrrestrr`rarr6charsrrrrget_encoded_wordsd                r"cCsFt}|rB|dtkr0t|\}}||qd}|drzt|\}}Wn,tk rfd}Yntjk rzYnrXd}t |dkr|dj dkr|j t dd}|rt |dkr|d j d krt |dd|d<||qt|d^}}|rt|r|d^}}t|d }t|||d |}q|S) aOunstructured = (*([FWS] vchar) *WSP) / obs-unstruct obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS) obs-utext = %d0 / obs-NO-WS-CTL / LF / CR obs-NO-WS-CTL is control characters except WSP/CR/LF. So, basically, we have printable runs, plus control characters or nulls in the obsolete syntax, separated by whitespace. Since RFC 2047 uses the obsolete syntax in its specification, but requires whitespace on either side of the encoded words, I can see no reason to need to separate the non-printable-non-whitespace from the printable runs if they occur, so we parse this into xtext tokens separated by WSP tokens. Because an 'unstructured' value must by definition constitute the entire value, this 'get' routine does not return a remaining value, only the parsed TokenList. rTrFrrz&missing whitespace before encoded wordrr^rr)rRrrrhrr"rrrrrDrrrr rfc2047_matchersearch partitionrr r%)rrSr6valid_ewZhave_wsrrrrrrget_unstructured?sJ          r(cCs*t|d\}}}t|d}t|||fS)actext = This is not the RFC ctext, since we are handling nested comments in comment and unquoting quoted-pairs here. We allow anything except the '()' characters, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Since quoted pairs are converted to their unquoted values, what is returned is a 'ptext' token. In this case it is a WhiteSpaceTerminal, so it's value is ' '. z()r)rrr rr_rrr get_qp_ctexts  r+cCs*t|d\}}}t|d}t|||fS)aoqcontent = qtext / quoted-pair We allow anything except the DQUOTE character, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Any quoted pairs are converted to their unquoted values, so what is returned is a 'ptext' token. In this case it is a ValueTerminal. r r)rrr r)rrr get_qcontents  r,cCsNt|}|std||}|t|d}t|d}t|||fS)zatext = We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to the token's defects list if we find non-atext characters. zexpected atext but found '{}'Natext)_non_atom_end_matcherrrr*r|rrr )rmr-rrr get_atexts r0cCsr|ddkrtd|t}|dd}|rT|ddkrTt|\}}|||rB|ddkrB|dtkrt|\}}n|dddkr*d}z&t|\}}|j t d d }Wn"tjk rt|\}}YnX|r6t |dkr6|d j d kr6|d j dkr6t |d d |d <n t|\}}||qT|sb|j t d||fS||ddfS)zbare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE A quoted-string without the leading or trailing white space. Its value is the text between the quote marks, with whitespace preserved and quoted pairs decoded. rr zexpected '"' but found '{}'rNrrFz!encoded word inside quoted stringTrrr#r^z"end of header inside quoted string)rrr*rmr,rhrrr"rrrrDr)rZbare_quoted_stringr6r'rrrget_bare_quoted_stringsL            r1cCs|r |ddkr td|t}|dd}|r|ddkr|dtkr\t|\}}n&|ddkrvt|\}}n t|\}}||q2|s|j t d||fS||ddfS)zcomment = "(" *([FWS] ccontent) [FWS] ")" ccontent = ctext / quoted-pair / comment We handle nested comments here, and quoted-pair in our qp-ctext routine. rrzexpected '(' but found '{}'rNrpzend of header inside comment) rrr*rnrr get_commentr+rhrr)rrOr6rrrr2s&      r2cCsPt}|rH|dtkrH|dtkr0t|\}}n t|\}}||q||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS r)rX CFWS_LEADERrrr2rh)rrYr6rrrget_cfwss   r4cCspt}|r,|dtkr,t|\}}||t|\}}|||rh|dtkrht|\}}||||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)rbr3r4rhr1)rZ quoted_stringr6rrrget_quoted_strings      r5cCst}|r,|dtkr,t|\}}|||rL|dtkrLtd||drzt |\}}Wqtjk rt |\}}YqXn t |\}}|||r|dtkrt|\}}||||fS)zPatom = [CFWS] 1*atext [CFWS] An atom could be an rfc2047 encoded word. rzexpected atom but found '{}'r) rZr3r4rh ATOM_ENDSrrr*rr"r0)rr[r6rrrget_atoms&       r7cCst}|r|dtkr&td||rt|dtkrtt|\}}|||r&|ddkr&|t|dd}q&|dtkrtdd|||fS)z( dot-text = 1*atext *("." 1*atext) rz8expected atom at a start of dot-atom-text but found '{}'rrNrz4expected atom at end of dot-atom-text but found '{}')rr6rrr*r0rhr)rZ dot_atom_textr6rrrget_dot_atom_text0s     r8cCst}|dtkr(t|\}}|||drhzt|\}}Wqttjk rdt|\}}YqtXn t|\}}|||r|dtkrt|\}}||||fS)z dot-atom = [CFWS] dot-atom-text [CFWS] Any place we can have a dot atom, we could instead have an rfc2047 encoded word. rr) rr3r4rhrr"rrr8)rZdot_atomr6rrr get_dot_atomCs        r9cCs|dtkrt|\}}nd}|s,td|ddkrFt|\}}n*|dtkrdtd|n t|\}}|dk r|g|dd<||fS)aword = atom / quoted-string Either atom or quoted-string may start with CFWS. We have to peel off this CFWS first to determine which type of word to parse. Afterward we splice the leading CFWS, if any, into the parsed sub-token. If neither an atom or a quoted-string is found before the next special, a HeaderParseError is raised. The token returned is either an Atom or a QuotedString, as appropriate. This means the 'word' level of the formal grammar is not represented in the parse tree; this is because having that extra layer when manipulating the parse tree is more confusing than it is helpful. rNz5Expected 'atom' or 'quoted-string' but found nothing.r z1Expected 'atom' or 'quoted-string' but found '{}')r3r4rrr5SPECIALSr*r7)rleaderr6rrrget_word\s"    r<cCst}zt|\}}||Wn(tjk rH|jtdYnX|r|dtkr|ddkr|t|jt d|dd}qJzt|\}}WnDtjk r|dt krt |\}}|jt dnYnX||qJ||fS)a phrase = 1*word / obs-phrase obs-phrase = word *(word / "." / CFWS) This means a phrase can be a sequence of words, periods, and CFWS in any order as long as it starts with at least one word. If anything other than words is detected, an ObsoleteHeaderDefect is added to the token's defect list. We also accept a phrase that starts with CFWS followed by a dot; this is registered as an InvalidHeaderDefect, since it is not supported by even the obsolete grammar. zphrase does not start with wordrrzperiod in 'phrase'rNzcomment found without atom) rUr<rhrrrr PHRASE_ENDSrObsoleteHeaderDefectr3r4)rrVr6rrr get_phrase~s4           r?c Csvt}d}|dtkr"t|\}}|s6td|zt|\}}Wn^tjk rzt|\}}Wn6tjk r|ddkr|dtkrt }YnXYnX|dk r|g|dd<| ||r4|ddks|dtkr4t t ||\}}|j dkr|j tdn|j td||d<z|jdWn(tk rl|j td YnX||fS) z= local-part = dot-atom / quoted-string / obs-local-part Nrz"expected local-part but found '{}'r invalid-obs-local-partzrencoderZNonASCIILocalPartDefect)rrr;r6obs_local_partrrrget_local_partsJ         rEcCst}d}|r(|ddks*|dtkr(|ddkrj|rL|jtd|td}|dd}q nD|ddkr|t|dd |dd}|jtd d}q |r|d jd kr|jtd zt |\}}d}Wn4tj k r|dt kr t |\}}YnX||q |djd ksX|djdkrj|djd krj|jtd|d jd ks|d jdkr|djd kr|jtd|jrd|_||fS)z' obs-local-part = word *("." word) Frr rzinvalid repeated '.'TrNmisplaced-specialz/'\' character outside of quoted-string/ccontentrrzmissing '.' between wordsrYz!Invalid leading '.' in local partr#z"Invalid trailing '.' in local partr@) rr=rrhrrrrrDr<rr3r4)rrDZlast_non_ws_was_dotr6rrrrBsj                  rBcCs@t|d\}}}t|d}|r0|jtdt|||fS)a dtext = / obs-dtext obs-dtext = obs-NO-WS-CTL / quoted-pair We allow anything except the excluded characters, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Quoted pairs are converted to their unquoted values, so what is returned is a ptext token, in this case a ValueTerminal. If there were quoted-printables, an ObsoleteHeaderDefect is added to the returned token's defect list. z[]rz(quoted printable found in domain-literal)rrrrhrr>r )rrrrrr get_dtexts   rGcCs,|rdS|td|tdddS)NFz"end of input inside domain-literal]domain-literal-endT)rhrrr)rdomain_literalrrr_check_for_early_dl_endsrKcCsjt}|dtkr(t|\}}|||s6td|ddkrRtd||dd}t||rp||fS|tdd|dt krt |\}}||t |\}}||t||r||fS|dt krt |\}}||t||r||fS|ddkrtd ||tdd |dd}|rb|dtkrbt|\}}||||fS) zB domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] rzexpected domain-literal[z6expected '[' at start of domain-literal but found '{}'rNzdomain-literal-startrHz4expected ']' at end of domain-literal but found '{}'rI) rr3r4rhrrr*rKrrrrG)rrJr6rrrget_domain_literalsH                    rMcCsrt}d}|dtkr"t|\}}|s6td||ddkrvt|\}}|dk rd|g|dd<||||fSzt|\}}Wn"tjk rt |\}}YnX|r|ddkrtd|dk r|g|dd<|||rj|ddkrj|j t d|dj d kr*|d|dd<|rj|ddkrj|t t |d d\}}||q*||fS) z] domain = dot-atom / domain-literal / obs-domain obs-domain = atom *("." atom)) Nrzexpected domain but found '{}'rLrzInvalid Domainrz(domain is not a dot-atom (contains CFWS)rr)rr3r4rrr*rMrhr9r7rr>rDr)rrr;r6rrr get_domain=sD         rNcCs|t}t|\}}|||r,|ddkrF|jtd||fS|tddt|dd\}}||||fS)z( addr-spec = local-part "@" domain rrz#addr-spec local part with no domainaddress-at-symbolrN)rrErhrrrrrN)rrr6rrr get_addr_speccs    rPcCst}|rj|ddks"|dtkrj|dtkrFt|\}}||q|ddkr|t|dd}q|rz|ddkrtd||tt |dd\}}|||r>|ddkr>|t|dd}|sq>|dtkrt|\}}|||ddkr|tt |dd\}}||q|sNtd|ddkrltd ||t dd ||ddfS) z obs-route = obs-domain-list ":" obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain]) Returns an obs-route token with the appropriate sub-tokens (that is, there is no obs-domain-list in the parse tree). rrrNrz(expected obs-route domain but found '{}'z%end of header while parsing obs-route:z4expected ':' marking end of obs-route but found '{}'zend-of-obs-route-marker) rr3r4rh ListSeparatorrrr*RouteComponentMarkerrNr)rZ obs_router6rrr get_obs_routessF               rTc Cst}|dtkr(t|\}}|||r8|ddkrHtd||tdd|dd}|ddkr|tdd|jt d |dd}||fSzt |\}}Wnztjk r0z"t |\}}|jt d Wn(tjk rtd |YnX||t |\}}YnX|||r^|ddkr^|dd}n|jt d |tdd|r|dtkrt|\}}||||fS) z angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] 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) rr3r4rhrrr*rrrrPrTr>)rZ angle_addrr6rrrget_angle_addrsT                rWcCs<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?r4r)rr~r6rrrget_display_names  rXcCst}d}|dtkr6t|\}}|s6td||ddkr|dtkr^td|t|\}}|s~td||dk r|g|ddd<d}||t |\}}|dk r|g|dd<||||fS)z, name-addr = [display-name] angle-addr Nrz!expected name-addr but found '{}'rU) rr3r4rrr*r=rXrhrW)rZ name_addrr;r6rrr get_name_addrs6        rYc Cst}zt|\}}WnNtjk rdzt|\}}Wn&tjk r^td|YnXYnXtdd|jDrd|_| |||fS)z& mailbox = name-addr / addr-spec zexpected mailbox but found '{}'css|]}t|tjVqdSr)rrrr rrrr#szget_mailbox..r) rrYrrrPr*anyr-rDrh)rrr6rrr get_mailboxs  r[cCsdt}|r\|d|kr\|dtkrD|t|dd|dd}qt|\}}||q||fS)z Read everything up to one of the chars in endchars. This is outside the formal grammar. The InvalidMailbox TokenList that is returned acts like a Mailbox, but the data attributes are None. rrFrN)rr=rhrr?)rrZinvalid_mailboxr6rrrget_invalid_mailbox s    r\cCst}|r|ddkrzt|\}}||Wntjk r<d}|dtkrt|\}}|rv|ddkr|||jtdn@t |d\}}|dk r|g|dd<|||jt dnb|ddkr|jtdnBt |d\}}|dk r|g|dd<|||jt dYnX|r|ddkr|d}d |_ t |d\}}| ||jt d|r|ddkr|t |d d}q||fS) aJ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) For this routine we go outside the formal grammar in order to improve error handling. We recognize the end of the mailbox list only at the end of the value or at a ';' (the group terminator). This is so that we can turn invalid mailboxes into InvalidMailbox tokens and continue parsing any remaining valid mailboxes. We also allow all mailbox entries to be null, and this condition is handled appropriately at a higher level. r;Nz,;zempty element in mailbox-listzinvalid mailbox in mailbox-listrrrr)rr[rhrrr3r4rr>r\rrDr4rR)rZ mailbox_listr6r;rrrrget_mailbox_listsX                 r^cCst}|s$|jtd||fSd}|r|dtkrt|\}}|sl|jtd||||fS|ddkr||||fSt|\}}t|j dkr|dk r||| ||jt d||fS|dk r|g|dd<||||fS)zg group-list = mailbox-list / CFWS / obs-group-list obs-group-list = 1*([CFWS] ",") [CFWS] zend of header before group-listNrzend of header in group-listr]zgroup-list with empty entries) rrrhrrr3r4r^rrzr4r>)rZ group_listr;r6rrrget_group_listWs>           r_cCs t}t|\}}|r"|ddkr2td||||tdd|dd}|r|ddkr|tdd||ddfSt|\}}|||s|jt d n|ddkrtd ||tdd|dd}|r|dt krt |\}}||||fS) z7 group = display-name ":" [group-list] ";" [CFWS] rrQz8expected ':' at end of group display name but found '{}'zgroup-display-name-terminatorrNr]zgroup-terminatorzend of header in groupz)expected ';' at end of group but found {}) rrXrrr*rhrr_rrr3r4)rr|r6rrr get_group|s8          r`c Csxt}zt|\}}WnNtjk rdzt|\}}Wn&tjk r^td|YnXYnX||||fS)a address = mailbox / group Note that counter-intuitively, an address can be either a single address or a list of addresses (a group). This is why the returned Address object has a 'mailboxes' attribute which treats a single address as a list of length one. When you need to differentiate between to two cases, extract the single element, which is either a mailbox or a group token. zexpected address but found '{}')r{r`rrr[r*rh)rrrr6rrr get_addresss rac Cst}|rzt|\}}||Wn tjk rH}zd}|dtkrt|\}}|rj|ddkr|||jtdnFt |d\}}|dk r|g|dd<|t |g|jt dnh|ddkr|jtdnHt |d\}}|dk r|g|dd<|t |g|jt dW5d}~XYnX|r|ddkr|dd}d|_ t |d\}}| ||jt d|r|tdd |d d}q||fS) a address_list = (address *("," address)) / obs-addr-list obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) We depart from the formal grammar here by continuing to parse until the end of the input, assuming the input to be entirely composed of an address-list. This is always true in email parsing, and allows us to skip invalid addresses to parse additional valid ones. Nrrz"address-list entry with no contentzinvalid address in address-listzempty element in address-listrrrr)rqrarhrrr3r4rr>r\r{rrDr4r)rZ address_listr6errr;rrrrget_address_listsX              rccCst}|std||ddkr6td||tdd|dd}t|\}}|||rx|ddkrtd ||tdd ||ddfS) z& no-fold-literal = "[" *dtext "]" z'expected no-fold-literal but found '{}'rrLz;expected '[' at the start of no-fold-literal but found '{}'zno-fold-literal-startrNrHz9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)rrrr*rhrrG)rZno_fold_literalr6rrrget_no_fold_literals.    rdcCst}|r,|dtkr,t|\}}|||r<|ddkrLtd||tdd|dd}zt|\}}Wn`tjk rz"t |\}}|j t dWn&tjk rtd|YnXYnX|||r|dd kr@|j t d |r8|dd kr8|td d |dd}||fS|td d |dd}zt|\}}Wntjk rzt |\}}Wnrtjk r}zPz"t|\}}|j t dWn(tjk rtd|YnXW5d}~XYnXYnX|||r6|dd kr6|dd}n|j t d|td d |r|dtkrt|\}}||||fS)zmsg-id = [CFWS] "<" id-left '@' id-right ">" [CFWS] id-left = dot-atom-text / obs-id-left id-right = dot-atom-text / no-fold-literal / obs-id-right no-fold-literal = "[" *dtext "]" rrUzexpected 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-rightrVz msg-id-endrOzobsolete id-right in msg-idzFexpected dot-atom-text, no-fold-literal or obs-id-right but found '{}'zmissing trailing '>' on msg-id)rr3r4rhrrr*rr8rBrr>rrdrN)rZmsg_idr6errr get_msg_ids~             "    rfc Cst}zt|\}}||WnLtjk rl}z,t|}t|}|jtd |W5d}~XYnX|r|jtd ||S)z2message-id = "Message-ID:" msg-id CRLF zInvalid msg-id: {!r}NzUnexpected {!r}) rrfrhrrr(rrrr*)rZ message_idr6Zexrrrparse_message_idIs  rgcCst}|s |jtd|S|dtkrXt|\}}|||sX|jtdd}|r|ddkr|dtkr||d7}|dd}q\|s|jtd ||t |d nt ||_ |t |d |r|dtkrt|\}}|||r|ddkrT|j dk r:|jtd |rP|t |d |S|t dd |dd}|r|dtkrt|\}}|||s|j dk r|jtd |Sd}|r|dtkr||d7}|dd}q|s*|jtd ||t |d nt ||_ |t |d |rn|dtkrnt|\}}|||r|jtd|t |d |S)zE mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS] z%Missing MIME version number (eg: 1.0)rz0Expected MIME version number but found only CFWSrrrNz1Expected 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)rrrhrHeaderMissingRequiredValuer3r4isdigitrr*rintrr)rZ mime_versionr6rhrrrparse_mime_versiones                        rlcCsdt}|r\|ddkr\|dtkrD|t|dd|dd}qt|\}}||q||fS)z Read everything up to the next ';'. This is outside the formal grammar. The InvalidParameter TokenList that is returned acts like a Parameter, but the data attributes are None. rr]rFrN)rr=rhrr?)rZinvalid_parameterr6rrrget_invalid_parameters    rmcCsNt|}|std||}|t|d}t|d}t|||fS)a8ttext = We allow any non-TOKEN_ENDS in ttext, but add defects to the token's defects list if we find non-ttext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322. zexpected ttext but found '{}'Nttext)_non_token_end_matcherrrr*r|rrr )rr/rnrrr get_ttexts  rpcCst}|r,|dtkr,t|\}}|||rL|dtkrLtd|t|\}}|||r|dtkrt|\}}||||fS)ztoken = [CFWS] 1*ttext [CFWS] The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or tspecials. We also exclude tabs even though the RFC doesn't. The RFC implies the CFWS but is not explicit about it in the BNF. rexpected token but found '{}') r\r3r4rh TOKEN_ENDSrrr*rp)rZmtokenr6rrr get_tokens       rscCsNt|}|std||}|t|d}t|d}t|||fS)aQattrtext = 1*(any non-ATTRIBUTE_ENDS character) We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the token's defects list if we find non-attrtext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322. z expected attrtext but found {!r}Nr)_non_attribute_end_matcherrrr*r|rrr rr/rrrr get_attrtexts  rvcCst}|r,|dtkr,t|\}}|||rL|dtkrLtd|t|\}}|||r|dtkrt|\}}||||fS)aH [CFWS] 1*attrtext [CFWS] This version of the BNF makes the CFWS explicit, and as usual we use a value terminal for the actual run of characters. The RFC equivalent of attrtext is the token characters, with the subtraction of '*', "'", and '%'. We include tab in the excluded set just as we do for token. rrq) rr3r4rhATTRIBUTE_ENDSrrr*rvrrr6rrr get_attributes       rycCsNt|}|std||}|t|d}t|d}t|||fS)zattrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') This is a special parsing routine so that we get a value that includes % escapes as a single string (which we decode as a single string later). z)expected extended attrtext but found {!r}Nextended-attrtext)#_non_extended_attribute_end_matcherrrr*r|rrr rurrrget_extended_attrtext s r|cCst}|r,|dtkr,t|\}}|||rL|dtkrLtd|t|\}}|||r|dtkrt|\}}||||fS)z [CFWS] 1*extended_attrtext [CFWS] This is like the non-extended version except we allow % characters, so that we can pick up an encoded value as a single string. rrq) rr3r4rhEXTENDED_ATTRIBUTE_ENDSrrr*r|rxrrrget_extended_attribute! s      r~cCst}|r|ddkr&td||tdd|dd}|rR|dsbtd|d}|r|dr||d7}|dd}qf|dd kr|d kr|jtd t ||_ |t|d ||fS) a6 '*' digits The formal BNF is more complicated because leading 0s are not allowed. We check for that and add a defect. We also assume no CFWS is allowed between the '*' and the digits, though the RFC is not crystal clear on that. The caller should already have dealt with leading CFWS. r*zExpected section but found {}zsection-markerrNz$Expected section number but found {}r0z'section number has an invalid leading 0rh) rrrr*rhrrjrZInvalidHeaderErrorrkr)rrrhrrr get_section7 s,     rcCst}|stdd}|dtkr0t|\}}|sDtd||ddkr^t|\}}n t|\}}|dk r|g|dd<||||fS)z quoted-string / attribute z&Expected value but found end of stringNrz Expected value but found only {}r ) rrrr3r4r*r5r~rh)rvr;r6rrr get_valueU s"      rc Cst}t|\}}|||r,|ddkrL|jtd|||fS|ddkrz t|\}}d|_||Wntj k rYnX|st d|ddkr|t dd|dd }d|_ |dd krt d |t d d |dd }d }|r,|dt kr,t |\}}||d }|}|j rF|rF|dd krFt|\}}|j}d}|jdkr|r|ddkrd}n$t|\}} | r| ddkrd}n(zt|\}} Wn Yn X| sd}|r0|jtd|||D](} | jdkrg| d d <| }q*q|}nd }|jtd|r`|ddkr`d }n t|\}}|j r|jdkr|r|ddkr|||d k r|}||fS|jtd|s|jtd|||d kr||fSn|d k r@|D]} | jdkr q$q | jdk|| | j|_|ddkr^t d||t dd|dd }|r|ddkrt|\}}|||j|_|r|ddkrt d||t dd|dd }|d k rdt} |r^|dtkrt|\}}n2|dd krDt d d}|dd }n t|\}}| |q| }n t|\}}|||d k r|}||fS)aY attribute [section] ["*"] [CFWS] "=" value The CFWS is implied by the RFC but not made explicit in the BNF. This simplified form of the BNF from the RFC is made to conform with the RFC BNF through some extra checks. We do it this way because it makes both error recovery and working with the resulting parse tree easier. rr]z)Parameter contains name ({}) but no valuerTzIncomplete parameterzextended-parameter-markerrN=zParameter not followed by '='parameter-separatorr F'z5Quoted string value for extended parameter is invalidrezZParameter 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 delimitersrzrz=Expected RFC2231 char/lang encoding delimiter, but found {!r}zRFC2231-delimiterz;Expected RFC2231 char/lang encoding delimiter, but found {}ZDQUOTE)rryrhrrrr*rrrrrr3r4r5rlrrvr|rDrrr`rarrrr,) rrr6r;rZappendtoZqstringZ inner_valueZ semi_validr trrrr get_parameterk s                                             rc Csjt}|rfzt|\}}||Wntjk r}zd}|dtkrVt|\}}|sp|||WYxS|ddkr|dk r|||jtdn@t |\}}|r|g|dd<|||jtd |W5d}~XYnX|rD|ddkrD|d}d|_ t |\}}| ||jtd ||r|t dd |d d}q|S) a! parameter *( ";" parameter ) That BNF is meant to indicate this routine should only be called after finding and handling the leading ';'. There is no corresponding rule in the formal RFC grammar, but it is more convenient for us for the set of parameters to be treated as its own TokenList. This is 'parse' routine because it consumes the remaining value, but it would never be called to parse a full header. Instead it is called to parse everything after the non-parameter value of a specific MIME header. Nrr]zparameter entry with no contentzinvalid parameter {!r}rrz)parameter with invalid trailing text {!r}rr)rrrhrrr3r4rrrmr*rDr4r)rZmime_parametersr6rbr;rrrrparse_mime_parameters sJ               rcCs|rV|ddkrV|dtkr>|t|dd|dd}qt|\}}||q|s^dS|tdd|t|dddS)zBDo our best to find the parameters in an invalid MIME header rr]rFrNr)r=rhrr?r)Z tokenlistrr6rrr_find_mime_parameters- s   rc Cst}d}|s$|jtd|Szt|\}}Wn<tjk rp|jtd|t |||YSX|||r|ddkr|jtd|rt |||S|j |_ |tdd|dd }zt|\}}Wn>tjk r*|jtd |t |||YSX|||j |_|sP|S|dd kr|jtd ||` |`t |||S|td d |t|dd |S)z maintype "/" subtype *( ";" parameter ) The maintype and substype are tokens. Theoretically they could be checked against the official IANA list + x-token, but we don't do that. Fz"Missing content type specificationz(Expected content maintype but found {!r}rrzInvalid content typezcontent-type-separatorrNz'Expected content subtype but found {!r}r]zt| } | jd krt | t @rd }z| ||} Wn6t k rt d d | jDrd } nd} d }YnX| jdkrt| |||q>|r|s| jspd}d}| jrp| j|ddt|j } |j| krpt| |t|dkr^t|}|||d| 7<q>t| dst| | } nt| |||| j| }d}q>t| |t|dkr|d| 7<q>| jrt| d|krt|}|s| r||| d}q>t| dsNt| }| jsD|d7}|||| } q>| jrn|sn| d| d }q>t|}|s| r||| q>|d| 7<q>|j||jS)zLReturn string of contents of parse_tree folded according to RFC rules. utf-8rrNrFwrap_as_ew_blockedrrTcss|]}t|tjVqdSr)rrrr rrrr# sz%_refold_parse_tree.. unknown-8bitrr7rrC)Zmax_line_lengthsysmaxsizeutf8rrrr rDrr:rCrrZr-_fold_mime_parametersr1rHr;rrrrhrE _fold_as_ewrIr0insertr%)Z parse_treer8maxlenrrlast_ewrZ want_encodingZend_ew_not_allowedrr2tstrr`Z encoded_partnewlineZnewpartsrrrr9 s              r9cCs|dk r<|rFold TokenList 'part' into the 'lines' list as mime parameters. Using the decoded list of parameters and values, format them according to the RFC rules, including using RFC2231 encoding if the value cannot be expressed in 'encoding' and/or the parameter+value is too long to fit within 'maxlen'. rr]strictFTrrrr)Zsaferz {}*={}''{}rrrNrrz''rNNz {}*{}*={}{})rrrrCrrrrrror*rrrhr )r2rrrrrr`Z error_handlerZencoding_requiredZ encoded_valuerrZ extra_chromerZ splitpointZmaxcharspartialrrrrr sn       r)rrerrstringroperatorrZemailrrrrrrr3r:r6rr=Z TSPECIALSrrZ ASPECIALSrwr}rcompileVERBOSE MULTILINEr$rrrLrRrUrWrXrZr\r]rbrmrnrqr{rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rrrrrrrrRrSr*r%rr rmatchr.findallr rortr{r rrr"r(r+r,r0r1r2r4r5r7r8r9r<r?rErBrGrKrMrNrPrTrWrXrYr[r\r^r_r`rarcrdrfrgrlrmrprsrvryr|r~rrrrrrrrrr9rrrrrrs.E           C  "   !*$ V +         1C+ "&'/'&).9%7ED49/gA