3 \&^@sdZdddgZddlZddlZddlZddlZddlmZddlm Z e j Z dZ d Z d ZdZd Zd ZdZe dZe dZejdejejBejBZejdZejdZejjZddZdddZGdddZ GdddZ!Gddde"Z#dS)z+Header encoding and decoding functionality.Header decode_header make_headerN)HeaderParseError)charset   Nz zus-asciizutf-8ai =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qb]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the encoded string \?= # literal ?= z[\041-\176]+:$z \n[^ \t]+:c Cst|drdd|jDStj|s.|dfgSg}x|jD]}tj|}d}xp|r|jd}|rn|j}d}|r|j|ddf|rP|jdj }|jdj }|jd}|j|||fqPWqMsz!decode_header..NTrFqbz===zBase64 decoding errorzUnexpected encoding: zraw-unicode-escape)hasattrr ecresearch splitlinessplitpoplstripappendlower enumerateisspacereversedemail quoprimimeZ header_decodelenZ base64mimedecodebinasciiErrorrAssertionError isinstancerbytesBSPACE)headerZwordslinepartsfirstZ unencodedrencodingZencodedZdroplistnwdZ decoded_wordsZencoded_stringZwordZpaderrZ collapsedZ last_word last_charsetrrrr=sz       4           cCsLt|||d}x8|D]0\}}|dk r8t|t r8t|}|j||qW|S)aCreate a Header from a sequence of pairs as returned by decode_header() decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the string name of the character set. This function takes one of those sequence of pairs and returns a Header instance. Optional maxlinelen, header_name, and continuation_ws are as in the Header constructor. ) maxlinelen header_namecontinuation_wsN)rr-Charsetr!)Z decoded_seqr9r:r;hsrrrrrs c@sJeZdZdddZddZdd Zdd d Zd d ZdddZddZ dS)rNrstrictcCs||dkrt}nt|ts t|}||_||_g|_|dk rH|j||||dkrTt}||_|dkrjd|_ nt |d|_ dS)aDCreate a MIME-compliant header that can contain many character sets. Optional s is the initial header value. If None, the initial header value is not set. You can later append to the header with .append() method calls. s may be a byte string or a Unicode string, but see the .append() documentation for semantics. Optional charset serves two purposes: it has the same meaning as the charset argument to the .append() method. It also sets the default character set for all subsequent .append() calls that omit the charset argument. If charset is not provided in the constructor, the us-ascii charset is used both as s's initial charset and as the default for subsequent .append() calls. The maximum line length can be specified explicitly via maxlinelen. For splitting the first line to a shorter value (to account for the field header which isn't included in s, e.g. `Subject') pass in the name of the field in header_name. The default maxlinelen is 78 as recommended by RFC 2822. continuation_ws must be RFC 2822 compliant folding whitespace (usually either a space or a hard tab) which will be prepended to continuation lines. errors is passed through to the .append() call. Nrr) USASCIIr-r<r_continuation_wsr r! MAXLINELEN _maxlinelen _headerlenr()selfr>rr9r:r;errorsrrr__init__s zHeader.__init__c Cs|jg}d}d}x|jD]\}}|}|tjkrJ|jdd}|jdd}|r|o^|j|d}|dkr|d kr| r|jtd}n|d kr| r|jt|o|j|d }|}|j|qWt j |S) z&Return the string value of the header.Nasciisurrogateescapereplacerus-asciir)NrK)NrK)NrK) _normalizer r UNKNOWN8BITencoder) _nonctextr!SPACE EMPTYSTRINGjoin) rEZuchunkslastcs lastspacerrZnextcsZoriginal_byteshasspacerrr__str__s*     zHeader.__str__cCs |t|kS)N)r)rEotherrrr__eq__sz Header.__eq__c Cs|dkr|j}nt|ts"t|}t|tsZ|jp4d}|tjkrN|jdd}n |j||}|jpbd}|tjkry|j||Wn"t k r|dkrt }YnX|j j ||fdS)a.Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is false), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In either case, when producing an RFC 2822 compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded to the output codec, a UnicodeError will be raised. Optional `errors' is passed as the errors argument to the decode call if s is a byte string. Nzus-asciirI) rr-r<rZ input_codecrNr)Z output_codecrOUnicodeEncodeErrorUTF8r r!)rEr>rrFZ input_charsetZoutput_charsetrrrr! s$        z Header.appendcCs|jp|dkS)z=True if string s is not a ctext character of RFC822. ()\)r\r]r^)r$)rEr>rrrrP4szHeader._nonctext;, rcCs|j|dkr|j}|dkr"d}t|j||j|}d}d}}x4|jD](\}} |dk r|ol|j|d}|d kr| s| d kr|jn| d kr| r|j|o|j|d }| }d}|j} | r|j d| d| n|j dd| xr| ddD]b} |j | j dk r,|j |jd| j | n.| j } | dt | t | } |j | | | qWt | dkrJ|j qJW|jr|j|j|}tj|rtd j||S)aEncode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. Optional maxlinelen specifies the maximum length of each generated line, exclusive of the linesep string. Individual lines may be longer than maxlinelen if a folding point cannot be found. The first line will be shorter by the length of the header name plus ": " if a header name was specified at Header construction time. The default value for maxlinelen is determined at header construction time. Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822's `higher level syntactic breaks': split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 encoded lines. Optional linesep is a string to be used to separate the lines of the value. The default value is the most useful for typical Python applications, but it can be set to \r\n to produce RFC-compliant line separators when needed. Nri@Bus-asciirFr rz8header value appears to contain an embedded header: {!r})Nr`)Nr`)Nr`rL)rMrC_ValueFormatterrDrAr rPadd_transitionrfeednewlineheader_encodingr r(_str_embedded_headerrrformat)rE splitcharsr9linesepZ formatterrTrVrUrrlinesr1ZslinefwsvaluerrrrO9sR!       z Header.encodecCs|g}d}g}xL|jD]B\}}||kr0|j|q|dk rL|jtj||f|g}|}qW|rr|jtj||f||_dS)N)r r!rQrS)rEZchunksr8Z last_chunkrrrrrrMs zHeader._normalize)NNNNrr?)Nr?)r_Nr) __name__ __module__ __qualname__rGrWrYr!rPrOrMrrrrrs -  + Pc@sTeZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ dS)racCs0||_||_t||_||_g|_t||_dS)N)_maxlenrAr(_continuation_ws_len _splitchars_lines _Accumulator _current_line)rEZ headerlenmaxlenr;rirrrrGs  z_ValueFormatter.__init__cCs|j|j|jS)N)rdrSrt)rErjrrrrfsz_ValueFormatter._strcCs |jtS)N)rfNL)rErrrrWsz_ValueFormatter.__str__cCsp|jj}|dkr|jj|t|jdkrb|jjrP|jdt|j7<n|jjt|j|jjdS)Nrr rr)rr rL) rvrpushr( is_onlywsrtrr!reset)rEZ end_of_linerrrrds   z_ValueFormatter.newlinecCs|jjdddS)Nrr )rvry)rErrrrbsz_ValueFormatter.add_transitioncCs|jdkr|j|||jdS|j||j}y|jd}Wntk rPdSX|dk rf|j||y |j}Wntk rdSX|j|j j |j |x|D]}|j j |j |qWdS)Nr)re _ascii_splitrsZheader_encode_lines _maxlengthsr IndexError _append_chunkrdrvryrArtr!)rErlrrZ encoded_linesZ first_line last_liner1rrrrcs$    z_ValueFormatter.feedccs*|jt|jVx|j|jVqWdS)N)rqr(rvrr)rErrrr}sz_ValueFormatter._maxlengthscCsjtjdtd||}|dr0dg|dd<n |jdx*tt|gdD]\}}|j||qNWdS)Nz([z]+)rr r)rerFWSrzipiterr)rErlrrir2partrrrr|s  z_ValueFormatter._ascii_splitcCs |jj||t|j|jkrx|jD]t}xlt|jjdddD]P}|jrp|j|d}|rp|d|krpP|j|dd}|rD|d|krDPqDWq(Pq(W|jj\}}|jj dkr|j |sd}|jj||dS|jj |}|j j t|j|jj|dS)NrrrrLrL)rvryr(rqrsrange part_countr$r _initial_sizerdpop_fromrtr!rr{)rErlrZchiZprevpartrZ remainderrrrrs.   z_ValueFormatter._append_chunkN) rnrorprGrfrWrdrbrcr}r|rrrrrras %racsjeZdZdfdd ZddZdddZfdd Zd d Zd d ZdddZ ddZ fddZ Z S)rurcs||_tjdS)N)rsuperrG)rEZ initial_size) __class__rrrGsz_Accumulator.__init__cCs|j||fdS)N)r!)rErlrrrrry#sz_Accumulator.pushcCs||d}g||d<|S)Nr)rErZpoppedrrrr&s  z_Accumulator.pop_fromcs|jdkrdStjS)Nrr )r r )rrr)rE)rrrr+s z_Accumulator.popcCstdd|D|jS)Ncss"|]\}}t|t|VqdS)N)r()rrlrrrr 1sz'_Accumulator.__len__..)sumr)rErrr__len__0sz_Accumulator.__len__cCstjdd|DS)Ncss |]\}}tj||fVqdS)N)rRrS)rrlrrrrr5sz'_Accumulator.__str__..)rRrS)rErrrrW4s z_Accumulator.__str__NcCs"|dkr g}||dd<d|_dS)Nr)r)rEZstartvalrrrr{8s z_Accumulator.resetcCs|jdko| pt|jS)Nr)rrr$)rErrrrz>sz_Accumulator.is_onlywscs tjS)N)rr)rE)rrrrAsz_Accumulator.part_count)r)r)N) rnrorprGryrrrrWr{rzr __classcell__rr)rrrus   ruz )NNr)$__doc____all__rr*Zemail.quoprimimer&Zemail.base64mimeZ email.errorsrrrr<rxrQr/ZSPACE8rRrBrr@r[compileVERBOSE IGNORECASE MULTILINErZfcrergr'Z _max_appendrrrralistrurrrrs@    _ k