HEX
Server: Apache
System: Linux scp1.abinfocom.com 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
User: confeduphaar (1010)
PHP: 8.1.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //lib/python3/dist-packages/twisted/mail/__pycache__/imap4.cpython-38.pyc
U

��W[=9�(@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Zddlm
Z
ddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZmZddlmZmZ m!Z"m#Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-dd
lm.Z.ddl/m0Z0ddl1m2Z2m3Z3ddl4m5Z5m6Z6m7Z8m9Z:m;Z<m=Z>m?Z@mAZBmCZDmEZFmGZHmIZJddlKmLZLmMZMmNZNmOZOmPZPddlQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZaebeceddd�d�e���Zfdd�Zgdd�ZhGdd�dei�ZjGdd�d�ZkGdd�d�ZlGd d!�d!�ZmGd"d#�d#�Znd$Zod%�pd&d'�e
edd(�edd)d*��D��Zqd+eoeqZre,�rzer�sd,�ZtnerZte�ud-etd.�Zvd%�pd/d'�ewedd*��D��ZxeeJ�Gd0d1�d1ejyejz��Z{e�|�Z}eeJ�Gd2d3�d3ejyejz��Z~d�d4d5�Zd6Z�d7Z�e�Z�d�d8d9�Z�d:d;�Z�d<d=�Z�d�d>d?�Z�d@dA�Z�dBdC�Z�dDdE�Z�d�dFdG�Z�dHdI�Z�dJdK�Z�GdLdM�dM�Z�dNZ�dOdP�Z�dQdR�Z�dSdT�Z�dUdV�Z�dWdX�Z�ee8�GdYdZ�dZei��Z�ee6�Gd[d\�d\e���Z�d]d^d_d`dadb�Z�dcdd�Z�dedf�Z�dgdh�Z�didj�Z�dkdl�Z�dmdn�Z�dodp�Z�Gdqdr�drei�Z�Gdsdt�dte��Z�Gdudv�dve��Z�Gdwdx�dxe��Z�Gdydz�dze��Z�d�d|d}�Z�d~d�Z�d�d��Z�d�d��Z�Gd�d��d��Z�Gd�d��d��Z�Gd�d��d��Z�d�d��Z�e�e�d�d�d���Z�d�d��Z�d�d��Z�d�d�d��Z�d�d�d��Z�Gd�d��d�ej��Z�Gd�d��d�ej��Z�e��e�e�e�e��Z�d�d��Z�e��e��d1d3d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d9d=d;d\ddg(Z�dS)�a�
An IMAP4 protocol implementation

@author: Jp Calderone

To do::
  Suspend idle timeout while server is processing
  Use an async message parser instead of buffering in memory
  Figure out a way to not queue multi-message client requests (Flow? A simple callback?)
  Clarify some API docs (Query, etc)
  Make APPEND recognize (again) non-existent mailboxes before accepting the literal
�N)�chain)�BytesIO)�implementer)�basic)�policies)�defer)�error)�
maybeDeferred)�log�text)
�	_bytesChr�unichr�_b64decodebytes�_b64encodebytes�
intToBytes�	iterbytes�long�nativeString�
networkString�unicode�_matchingString�_PY3�_get_async_param)�
interfaces)�credentials)�UnauthorizedLogin�UnhandledCredentials)�IClientAuthentication�INamespacePresenter�IAccountIMAP�IMessageIMAPPart�IMessageIMAP�IMessageIMAPFile�ISearchableIMAPMailbox�IMessageIMAPCopier�IMailboxIMAPInfo�IMailboxIMAP�ICloseableMailboxIMAP�IMailboxIMAPListener)�CramMD5ClientAuthenticator�LOGINAuthenticator�LOGINCredentials�PLAINAuthenticator�PLAINCredentials)�IMAP4Exception�IllegalClientResponse�IllegalOperation�MailboxException�IllegalMailboxEncoding�MailboxCollision�
NoSuchMailbox�ReadOnlyMailbox�UnhandledResponse�NegativeResponse�NoSupportedAuthentication�IllegalIdentifierError�IllegalQueryError�MismatchedNesting�MismatchedQuoting�IllegalServerResponse��
z/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov DeccCs||kr|S|S)z�
    Swap C{this} with C{that} if C{this} is C{ifIs}.

    @param this: The object that may be replaced.

    @param that: The object that may replace C{this}.

    @param ifIs: An object whose identity will be compared to
        C{this}.
    �)�this�that�ifIsr@r@�4/usr/lib/python3/dist-packages/twisted/mail/imap4.py�_swapTsrEcs��fdd�|D�S)a�
    Swap each element in each pair in C{of} with C{that} it is
    C{ifIs}.

    @param of: A list of 2-L{tuple}s, whose members may be the object
        C{that}
    @type of: L{list} of 2-L{tuple}s

    @param ifIs: An object whose identity will be compared to members
        of each pair in C{of}

    @return: A L{list} of 2-L{tuple}s with all occurences of C{ifIs}
        replaced with C{that}
    cs(g|] \}}t|���t|���f�qSr@)rE)�.0�first�second�rCrBr@rD�
<listcomp>qs�z!_swapAllPairs.<locals>.<listcomp>r@)ZofrBrCr@rIrD�
_swapAllPairsbs�rKc@s�eZdZdZgZed�Zeefdd�Zdd�Ze	e��Zefdd�Z
d	d
�Zdd�Zd
d�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!S)"�
MessageSeta


    A set of message identifiers usable by both L{IMAP4Client} and
    L{IMAP4Server} via L{IMailboxIMAP.store} and
    L{IMailboxIMAP.fetch}.

    These identifiers can be either message sequence numbers or unique
    identifiers.  See Section 2.3.1, "Message Numbers", RFC 3501.

    This represents the C{sequence-set} described in Section 9,
    "Formal Syntax" of RFC 3501:

        - A L{MessageSet} can describe a single identifier, e.g.
          C{MessageSet(1)}

        - A L{MessageSet} can describe C{*} via L{None}, e.g.
          C{MessageSet(None)}

        - A L{MessageSet} can describe a range of identifiers, e.g.
          C{MessageSet(1, 2)}.  The range is inclusive and unordered
          (see C{seq-range} in RFC 3501, Section 9), so that
          C{Message(2, 1)} is equivalent to C{MessageSet(1, 2)}, and
          both describe messages 1 and 2.  Ranges can include C{*} by
          specifying L{None}, e.g. C{MessageSet(None, 1)}.  In all
          cases ranges are normalized so that the smallest identifier
          comes first, and L{None} always comes last; C{Message(2, 1)}
          becomes C{MessageSet(1, 2)} and C{MessageSet(None, 1)}
          becomes C{MessageSet(1, None)}

        - A L{MessageSet} can describe a sequence of single
          identifiers and ranges, constructed by addition.
          C{MessageSet(1) + MessageSet(5, 10)} refers the message
          identified by C{1} and the messages identified by C{5}
          through C{10}.

    B{NB: The meaning of * varies, but it always represents the
    largest number in use}.

    B{For servers}: Your L{IMailboxIMAP} provider must set
    L{MessageSet.last} to the highest-valued identifier (unique or
    message sequence) before iterating over it.

    B{For clients}: C{*} consumes ranges smaller than it, e.g.
    C{MessageSet(1, 100) + MessageSet(50, None)} is equivalent to
    C{1:*}.

    @type getnext: Function taking L{int} returning L{int}
    @ivar getnext: A function that returns the next message number,
        used when iterating through the L{MessageSet}.  By default, a
        function returning the next integer is supplied, but as this
        can be rather inefficient for sparse UID iterations, it is
        recommended to supply one when messages are requested by UID.
        The argument is provided as a hint to the implementation and
        may be ignored if it makes sense to do so (eg, if an iterator
        is being used that maintains its own state, it is guaranteed
        that it will not be called out-of-order).
    �infcCsX|j|_g|_dd�|_||jkr&dSt|t�rH|dd�|_|��n|�||�dS)z�
        Create a new MessageSet()

        @type start: Optional L{int}
        @param start: Start of range, or only message number

        @type end: Optional L{int}
        @param end: End of range.
        cSs|dS�Nr>r@��xr@r@rD�<lambda>��z%MessageSet.__init__.<locals>.<lambda>N)�_empty�_last�ranges�getnext�
isinstance�list�clean�add��self�start�endr@r@rD�__init__�s




zMessageSet.__init__cCs dd�}dd�}d}||d|fS)NcSsv|j|jk	rtd��||_t|j�D]D\}\}}|dkr<|}|dkrH|}||krZ||}}||f|j|<q$|��dS)Nzlast already set)rTrS�
ValueError�	enumeraterUrY)r\�value�i�l�hr@r@rD�_setLast�s
z!MessageSet.last.<locals>._setLastcSs|jS�N)rT�r\r@r@rD�_getLast�sz!MessageSet.last.<locals>._getLasta+
              Replaces all occurrences of "*".  This should be the
              largest number in use.  Must be set before attempting to
              use the MessageSet as a container.

              @raises: L{ValueError} if a largest value has already
                  been set.
              r@)rfri�docr@r@rD�last�szMessageSet.lastcCst||jkr|}|j|jk	r6|dkr(|j}|dkr6|j}t||gtjt|jdd�d�\}}|j�	||f�|�
�dS)z�
        Add another range

        @type start: L{int}
        @param start: Start of range, or only message number

        @type end: Optional L{int}
        @param end: End of range.
        N�rBrC)�key)rSrTrk�sorted�	functools�partialrE�	_infinityrU�appendrYr[r@r@rDrZ�s

�
zMessageSet.addcCsrt|t�r|j|j}t|�St|j�}|j|jk	r<|j|_z|j|�Wntk
rh|�|�YnX|SdSrg)rWrLrUrkrSrZ�	TypeError)r\�otherrU�resr@r@rD�__add__s

zMessageSet.__add__cCsTt|t�r"|j�|j�|��n.z|j|�Wntk
rN|�|�YnX|S)z�
        Extend our messages with another message or set of messages.

        @param other: The messages to include.
        @type other: L{MessageSet}, L{tuple} of two L{int}s, or a
            single L{int}
        )rWrLrU�extendrYrZrs�r\rtr@r@rDrws

zMessageSet.extendcCs�tt|j|jdd��}td�td�fg}|D]H\}}|d\}}||dkr\|�||f�q,t||�t||�f|d<q,t|dd�d|jd�|_dS)z>
        Clean ranges list, combining adjacent ranges
        Nrlz-inf���r>)rnrKrUrq�floatrr�min�max)r\rUZmergedRanges�low�highZpreviousLowZpreviousHighr@r@rDrY's"��
�zMessageSet.cleancCs|jdddkS)a�
        Is there a L{None} in our ranges?

        L{MessageSet.clean} merges overlapping or consecutive ranges.
        None is represents a value larger than any number.  There are
        thus two cases:

            1. C{(x, *) + (y, z)} such that C{x} is smaller than C{y}

            2. C{(z, *) + (x, y)} such that C{z} is larger than C{y}

        (Other cases, such as C{y < x < z}, can be split into these
        two cases; for example C{(y - 1, y)} + C{(x, x) + (z, z + 1)})

        In case 1, C{* > y} and C{* > z}, so C{(x, *) + (y, z) = (x,
        *)}

        In case 2, C{z > x and z > y}, so the intervals do not merge,
        and the ranges are sorted as C{[(x, y), (z, *)]}.  C{*} is
        represented as C{(*, *)}, so this is the same as 2.  but with
        a C{z} that is greater than everything.

        The result is that there is a maximum of two L{None}s, and one
        of them has to be the high element in the last tuple in
        C{self.ranges}.  That means checking if C{self.ranges[-1][-1]}
        is L{None} suffices to check if I{any} element is L{None}.

        @return: L{True} if L{None} is in some range in ranges and
            L{False} if otherwise.
        ryN)rUrhr@r@rD�
_noneInRangesBszMessageSet._noneInRangescCsB|��rtd��|jD]&\}}||kr2|krnqdSqdS)z�
        May raise TypeError if we encounter an open-ended range

        @param value: Is this in our ranges?
        @type value: L{int}
        z.Can't determine membership; last value not setTF)rrsrU)r\rbr}r~r@r@rD�__contains__ds�zMessageSet.__contains__ccs<|jD]0\}}|�|d�}||kr|V|�|�}qqdSrN)rUrV)r\rdrer@r@rD�	_iteratorws
zMessageSet._iteratorcCs|��rtd��|��S)Nz!Can't iterate; last value not set)rrsr�rhr@r@rD�__iter__szMessageSet.__iter__cCsLd}|jD]<\}}|dkr$|d7}q
|dkr6td��q
|||d7}q
|S)Nrr>z%Can't size object; last value not set)rUrs)r\rurdrer@r@rD�__len__�s

zMessageSet.__len__cCsvg}|jD]`\}}||kr>|dkr.|�d�qj|�t|��q
|dkrX|�d|f�q
|�d||f�q
d�|�S)N�*z%d:*z%d:%d�,)rUrr�str�join)r\�pr}r~r@r@rD�__str__�szMessageSet.__str__cCsdt|�fS)Nz<MessageSet %s>�r�rhr@r@rD�__repr__�szMessageSet.__repr__cCst|t�r|j|jkSdS�NF)rWrLrUrxr@r@rD�__eq__�s
zMessageSet.__eq__cCs|�|�Srg)r�rxr@r@rD�__ne__�szMessageSet.__ne__N)�__name__�
__module__�__qualname__�__doc__rSrzrqr_rk�propertyrZrvrwrYrr�r�r�r�r�r�r�r�r@r@r@rDrLus&8
"
rLc@s$eZdZdd�Zdd�Zdd�ZdS)�
LiteralStringcCs||_g|_||_dSrg)�size�datar�r\r�Zdeferedr@r@rDr_�szLiteralString.__init__cCsl|jt|�8_d}|jdkr.|j�|�n:|jrT|d|j�||jd�}}nd}|rh|j�|�|S�NrrR)r��lenr�rr�r\r��passonr@r@rD�write�s
 zLiteralString.writecCs|j�d�|j�|f�dS)�:
        Call deferred with data and rest of line
        rRN)r�callbackr�r��r\�liner@r@rDr��szLiteralString.callbackN)r�r�r�r_r�r�r@r@r@rDr��sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�LiteralFile��cCs.||_||_||jkr"t��|_nt�|_dSrg)r�r�_memoryFileLimit�tempfile�
TemporaryFiler�rr�r@r@rDr_�s

zLiteralFile.__init__cCsl|jt|�8_d}|jdkr.|j�|�n:|jrT|d|j�||jd�}}nd}|rh|j�|�|Sr�)r�r�r�r�r�r@r@rDr��s
 zLiteralFile.writecCs$|j�dd�|j�|j|f�dS)r�rN)r��seekrr�r�r@r@rDr��szLiteralFile.callbackN)r�r�r�r�r_r�r�r@r@r@rDr��s	r�c@s*eZdZdZd
dd�Zdd�Zdd�Zd	S)�WriteBufferzU
    Buffer up a bunch of writes before sending them all to a transport at once.
    � cCs||_||_d|_g|_dS�Nr)�
bufferSize�	transport�_length�_writes)r\r�r�r@r@rDr_�szWriteBuffer.__init__cCs6|jt|�7_|j�|�|j|jkr2|��dSrg)r�r�r�rrr��flush�r\�sr@r@rDr��szWriteBuffer.writecCs$|jr |j�|j�g|_d|_dSr�)r�r�Z
writeSequencer�rhr@r@rDr�szWriteBuffer.flushN)r�)r�r�r�r�r_r�r�r@r@r@rDr��s
r�c@s>eZdZdZdZdZdZddd�Zdd	�Zd
d�Z	dd
�Z
dS)�Command)�
CAPABILITY�FLAGS�LIST�LSUB�STATUS�SEARCH�	NAMESPACE)�EXISTS�EXPUNGE�FETCH�RECENT)�UIDVALIDITY�UNSEEN�
READ-WRITE�	READ-ONLY�UIDNEXT�PERMANENTFLAGSNr@cs.||_||_||_���fdd�|_g|_dS)Ncs�|f����Srgr@rO��contArgs�contKw�continuationr@rDrQrRz"Command.__init__.<locals>.<lambda>)�command�args�wantResponser��lines)r\r�r�r�r�r�r�r@r�rDr_s
zCommand.__init__cCsd�|j|j|j|j|j�S)Nz(<imap4.Command {!r} {!r} {!r} {!r} {!r}>)�formatr�r�r�r�r�rhr@r@rDr�s�zCommand.__repr__cCs.|jdkrd�||jf�Sd�||j|jf�S�N� )r�r�r��r\�tagr@r@rDr�"s
zCommand.formatc	Cs�g}g}|jD]�}t|�}t|�}|dkr8|d|jks�|dkrN|d|jks�|dkr�|ddkr�t|dt�r�|dd|jkr�|�|�q|�|�q|j	d}|_	|�
||f�|r�||�dS)Nr>r��OK)r��parseNestedParensr��_1_RESPONSES�_2_RESPONSESrWrX�
_OK_RESPONSESrrrr�)	r\ZlastLineZunusedCallback�sendZunuse�L�names�N�dr@r@rD�finish(s0
���
���zCommand.finish)Nr@N)r�r�r�r�r�r�rr_r�r�r�r@r@r@rDr�s�
	r�r�rRccs|]}t|�VqdSrg)r�rFZchr@r@rD�	<genexpr>Asr��!��s	]\\(){%*"�charmap�[�]ccs"|]}t|�tkrt|�VqdSrg)r�
_nonAtomCharsr�r@r@rDr�Psc@s�eZdZdZdZdZdZdZdZdZ	dZ
dZdZdZ
dZdZdZedd	d
g�ZdZdZ�dOd
d�Zdd�Zdd�Zdd�Zdd�Zdd�ZdZdd�Zdd�Zdd�Zdd �Z�dPd!d"�Z d#d$�Z!d%d&�Z"d'd(�Z#d)d*�Z$d+d,�Z%d-d.�Z&d/d0�Z'�dQd1d2�Z(e)�*d3e)�+e,�d4�Z-d5d6�Z.d7d8�Z/d9d:�Z0d;d<�Z1d=d>�Z2d?d@�Z3dAdB�Z4dCdD�Z5dEdF�Z6dGdH�Z7dIdJ�Z8dKdL�Z9�dRdNdO�Z:�dSdPdQ�Z;�dTdRdS�Z<�dUdTdU�Z=�dVdWdX�Z>dYdZ�Z?d[d\�Z@d]d^�ZAeAfZBeBZCeBZDeBZEd_d`�ZFeFfZGeGZHeGZIeGZJdadb�ZKeKfZLeLZMeLZNeLZOdcdd�ZPePe.fZQdedf�ZRdgdh�ZSdidj�ZTdkdl�ZUdmdn�ZVdodp�ZWdqdr�ZXeXfZYdsdt�ZZeZe(e'fZ[dudv�Z\dwdx�Z]dydz�Z^d{d|�Z_e_fZ`e`Zad}d~�Zbdd��Zcd�d��Zdebe(d�d�fZeeeZfebe(d�d�fZgegZhd�d��Zid�d��ZjeifZkekZld�d��Zmeme'fZnenZod�d��Zpepe'fZqeqZrd�d��Zsese(e'fZtetZud�d��Zveve'fZwewZxd�d��Zyeye'fZzezZ{d�d��Z|d�d��Z}d�d��Z~e|e(e(d�d�fZeZ�e|e(e(d�d�fZ�e�Z�d�d��Z�d�d��Z�d�d��Z�e�e(e/fZ�e�Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�e�e(e6e7e0fZ�e�Z�d�d��Z�d�d��Z�d�d��Z�e�fZ�d�d��Z�d�d��Z�d�d��Z�d�d��Z�e�fZ�d�d��Z�d�d��Z�d�d��Z�e�fZ�d�d„Z�d�dĄZ��dWd�dƄZ�e�e8e1fZ�d�dȄZ��dXd�dʄZ�d�d̄Z�d�d΄Z�d�dЄZ�d�d҄Z�d�dԄZ�d�dքZ�d�d؄Z�d�dڄZ�d�d܄Z�d�dބZ�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d��d�Z��d�d�Z��d�d�Z��d�d�Z��d�d�Z��d	�d
�Z��d�d�Zd
�d�ZÐd�d�ZĐd�d�ZŐd�d�ZƐd�d�ZǐdY�d�d�Z�e�e2e3fZɐd�d�Zʐd�d�ZːdZ�d�d�Z̐d[�d�d �Z͐d\�d!�d"�Zΐd]�d#�d$�Zϐd^�d%�d&�ZАd_�d'�d(�Zѐd`�d)�d*�ZҐda�d+�d,�ZӐdb�d-�d.�ZԐdc�d/�d0�ZՐd1�d2�Z֐d3�d4�Zאdd�d5�d6�Z�e�e2e.e4fZِd7�d8�Zڐd9�d:�Zېde�d;�d<�Z�e�e2e'fZݐd=�d>�Zސd?�d@�ZߐdA�dB�Z�dC�dD�Z�dE�dF�Z�dG�dH�Z�e�e.e5fZ�dI�dJ�Z�dK�dL�Z�dM�dN�Z�dS(f�IMAP4Serverz�
    Protocol implementation for an IMAP4rev1 server.

    The server can be in any of four states:
        - Non-authenticated
        - Authenticated
        - Selected
        - Logout
    sTwisted IMAP4rev1 Ready�<iFNisORsNOTsUID�unauthr�cCs4|dkri}||_||_|dkr$t}||_g|_dSrg)�challengers�ctx�iterateInReactor�
_scheduler�_queuedAsync)r\�chal�contextFactory�	schedulerr@r@rDr_�szIMAP4Server.__init__cCsZdt|j���i}|jrF|jrF|jsFt�|jd�dkrFd|d<d|d<d|d<d|d<|S)N�AUTH�
LOGINDISABLED�STARTTLSr�sIDLE)	rXr��keysr��canStartTLS�
startedTLSr�
ISSLTransportr�)r\�capr@r@rD�capabilities�szIMAP4Server.capabilitiescCs2i|_t�|jd�dk	|_|�|j�|��dSrg)�tagsr�
ITLSTransportr�r��
setTimeout�timeOut�sendServerGreetingrhr@r@rD�connectionMade�szIMAP4Server.connectionMadecCs"|�d�|jr|��d|_dSrg)r��	_onLogout)r\�reasonr@r@rD�connectionLost�s
zIMAP4Server.connectionLostcCs\|�d�|j��|jrR|j�|�t|jd�}|dk	rLt|j��t	j
�d|_d|_dS)Ns** BYE Autologout; connection idle too long�timeout)�sendLiner��loseConnection�mbox�removeListener�ICloseableMailboxr	�close�
addErrbackr
�err�state)r\�cmbxr@r@rD�timeoutConnection�s

zIMAP4Server.timeoutConnectioncCs*|��|j�|�}|dk	r&|�|�dSrg)�resetTimeout�_pendingLiteralr��setLineModer�r@r@rD�rawDataReceived�szIMAP4Server.rawDataReceivedcCsF|j}d|_|r,|jdkr,|�|�d��q|jdk	rB|j�|�dSr�)�blocked�lineReceived�poprw)r\Zcommandsr@r@rD�_unblock�s
zIMAP4Server._unblockc
Cs�|jdk	r|j�|�dS|��t|d|j�}z||�Wn@tk
r~}z"|�dtt|���t	�
�W5d}~XYnXdS)NZparse_sBAD Server error: )rrrr�getattr�
parseState�	Exception�sendUntaggedResponserr�r
r
)r\r��f�er@r@rDr�s
zIMAP4Server.lineReceivedc
Cs>|�dd�}d}t|�dkr(|\}}}nJt|�dkr>|\}}n4t|�dkrb|d}|�|d�dS|�dd�dS|��}z|�|||�WStk
r�}z|�|dtt|���W5d}~XYnvtk
�r�}z|�	|dtt|���W5d}~XYn<t
k
�r8}z|�	|d	tt|���W5d}~XYnXdS)
Nr��r>rsMissing commandsNull command�Illegal syntax: �Illegal operation: �Illegal mailbox name: )�splitr��sendBadResponse�upper�dispatchCommandr/rr�r0�sendNegativeResponser2)r\r�r��restr��cmdrr@r@rD�
parse_command�s*
((zIMAP4Server.parse_commandcCs |j}d|_d|_|�|�dS)Nr�)rrr�)r\r�r�r@r@rD�
parse_pending�szIMAP4Server.parse_pendingcCsL|�|�}|r<|d}|dd�}|�||||g|||�n|�|d�dS)Nrr>sUnsupported command)�
lookupCommand�_IMAP4Server__doCommandr!)r\r�r&r%�uidr�fn�	parseargsr@r@rDr#�s
zIMAP4Server.dispatchCommandcCs t|d�|jt|���f�d�S)N�_)rr�rrr")r\r&r@r@rDr)szIMAP4Server.lookupCommandc		Cs�t|�D]X\}}t|�rV||dd�}t|||��|j|||||��|j|�dS|�|�q|rvtdt	|���|dk	r�||d|i�n||�dS)Nr>z Too many arguments for command: r+)
ra�callabler	�addCallback�_IMAP4Server__cbDispatchr	�_IMAP4Server__ebDispatchrrr/�repr)	r\r�Zhandlerr�r-r�r+rc�argr@r@rDZ__doCommands*��zIMAP4Server.__doCommandc	Cs*|\}}|�|�|�||||||�dSrg)rrr*)	r\�resultr�r,r�r-r+r4r%r@r@rDZ__cbDispatch!s
zIMAP4Server.__cbDispatchcCs�|�t�r&|�|dtt|j���np|�t�rL|�|dtt|j���nJ|�t�rr|�|dtt|j���n$|�|dtt|j���t	�
|�dS)Nrrr�Server error: )�checkr/r!rr�rbr0r$r2r
r
�r\�failurer�r@r@rDZ__ebDispatch's

�
�zIMAP4Server.__ebDispatchcCsR||jkrtd|jf��t��}d|_t||�|_|�td|��|�	�|S)Nz,Literal too long! I accept at most %d octets�pendingzReady for %d octets of text)
�_literalStringLimitr/r�Deferredrr�r�sendContinuationRequestr�
setRawMode�r\r�r�r@r@rD�_stringLiteral5s
��
�zIMAP4Server._stringLiteralcCs8t��}d|_t||�|_|�td|��|��|S)Nr:zReady for %d octets of data)rr<rr�rr=rr>r?r@r@rD�_fileLiteralCs
�zIMAP4Server._fileLiteralcCs|j|dd�S)a
        Parse an astring from line that represents a command's final
        argument.  This special case exists to enable parsing empty
        string literals.

        @param line: A line that contains a string literal.
        @type line: L{bytes}

        @return: A 2-tuple containing the parsed argument and any
            trailing data, or a L{Deferred} that fires with that
            2-tuple
        @rtype: L{tuple} of (L{bytes}, L{bytes}) or a L{Deferred}

        @see: https://twistedmatrix.com/trac/ticket/9207
        T)�final)�arg_astringr�r@r@rD�arg_finalastringMszIMAP4Server.arg_finalastringc	Cs.|��}|std��d}d\}}|dd�dkrrz"|�dd�\}}}|dd�}Wntk
rntd��YnXn�|dd�d	kr�|d
d�dkr�td��zt|dd
��}Wn,tk
r�td
t|dd
����YnX|r�|s�dS|�|�}n,|�dd�}t|�dk�r|�d�|\}}|�p,||fS)a�
        Parse an astring from the line, return (arg, rest), possibly
        via a deferred (to handle literals)

        @param line: A line that contains a string literal.
        @type line: L{bytes}

        @param final: Is this the final argument?
        @type final L{bool}

        @return: A 2-tuple containing the parsed argument and any
            trailing data, or a L{Deferred} that fires with that
            2-tuple
        @rtype: L{tuple} of (L{bytes}, L{bytes}) or a L{Deferred}

        �Missing argumentN)NNrr>�"r�zUnmatched quotes�{ry�}�Malformed literalzBad literal size: )rRrRr�rR)	�stripr/r r`�intr3r@r�rr)r\r�rBr�r4r%�spamr�r@r@rDrC`s8�

zIMAP4Server.arg_astrings
(?P<atom>[s]+)( (?P<rest>.*$)|$)cCs<|std��|j�|�}|r0|�d�|�d�fStd��dS)z-
        Parse an atom from the line
        rE�atomr%zMalformed ATOMN)r/�atomre�match�group)r\r��mr@r@rD�arg_atom�szIMAP4Server.arg_atomcCs`|std��|dd�dkr$td��|�d�}|dkr>td��t|d|�d	�||d
d�fS)zG
        Parse a (non-nested) parenthesised list from the line
        rENr>�(zMissing parenthesis�)ry�Mismatched parenthesisrr�)r/�findr�)r\r�rcr@r@rD�	arg_plist�s
zIMAP4Server.arg_plistc	Cs�|std��|dd�dkr$td��|dd�dkr<td��zt|dd��}Wn*tk
rztd	�|dd����YnX|�|�S)
z/
        Parse a literal from the line
        rENr>rGzMissing literalryrHrIzBad literal size: {!r})r/rKr`r�rA)r\r�r�r@r@rD�arg_literal�s�
zIMAP4Server.arg_literalcCst|�}|dfS)z
        searchkeys
        rR)r�)r\r��queryr@r@rD�arg_searchkeys�szIMAP4Server.arg_searchkeysc
Csrd}|�dd�}t|�dkr$|d}|d}zt|�|fWStk
rl}ztdt|���W5d}~XYnXdS)z
        sequence-set
        rRr�r>r�rzBad message number N)r r��parseIdListr9r/r�)r\r�r%r4rr@r@rD�
arg_seqset�szIMAP4Server.arg_seqsetcCst�}|�|�|jdfS)z
        fetch-att
        rR)�_FetchParser�parseStringr5)r\r�r�r@r@rD�arg_fetchatt�s
zIMAP4Server.arg_fetchattcCs�g}|dd�dkr8|dd�dkr,td��|dd�}|r�|j�|�}|sTtd��|dd�d	kr�|��dkr�|�d	|�d
��n&|��dkr�|�|�d
��ntd��|�d�}q8|dfS)
z-
        Flag part of store-att-flag
        rr>rSryNrTrUzMalformed flag�\rMr%rR)r/rN�searchr]rrrP)r\r��flagsrQr@r@rD�arg_flaglist�s zIMAP4Server.arg_flaglistcCs|dfS)z-
        Command line of UID command
        rRr@r�r@r@rD�arg_lineszIMAP4Server.arg_linecCs |�d�r|�|�Sd|fSdS)z-
        Optional parenthesised list
        rSN)�
startswithrWr�r@r@rD�	opt_plists

zIMAP4Server.opt_plistcCsZ|�d�rNz|�dd�\}}}Wntk
r<td��YnX||dd�fSd|fSdS)z+
        Optional date-time string
        rFr�zMalformed date-timer>N)rer r`r/)r\r�rL�dater%r@r@rD�opt_datetimes
zIMAP4Server.opt_datetimecCsh|dd���dkr\|�dd�}t|�dkr4td��t|�dkrJ|�d�|\}}}||fSd|fSdS)	z4
        Optional charset of SEARCH command
        N�sCHARSETr�r�r>zMissing charset identifierrR)r"r r�r/rr)r\r�r4rLr%r@r@rD�opt_charset#s

zIMAP4Server.opt_charsetcCs,dd�|���d|j}|j|d�dS)Ns[CAPABILITY r��] )�message)r��listCapabilities�IDENT�sendPositiveResponse�r\�msgr@r@rDr�3s�zIMAP4Server.sendServerGreetingrRcCs|�d||�dS)N�BAD��_respond�r\r�rlr@r@rDr!9szIMAP4Server.sendBadResponsecCs|�d||�dS)Nr�rsrur@r@rDro=sz IMAP4Server.sendPositiveResponsecCs|�d||�dS)N�NOrsrur@r@rDr$Asz IMAP4Server.sendNegativeResponsecKs:t|f|�}|r|jdkr*|�|dd�n|j�|�dSrg)rrrtr�rr)r\rl�isAsync�kwargsr@r@rDrEsz IMAP4Server.sendUntaggedResponse�!Ready for additional command textcCs"|r|�d|�n
|�d�dS)Ns+ �+�rrpr@r@rDr=Msz#IMAP4Server.sendContinuationRequestcCsn|dkr2|jr2|j}g|_|D]}|�|dd�q|s:d}|rV|�d�|||f��n|�d�||f��dS)N)r�rvrr�*r�)r�rtrr�)r\rr�rlr�rqr@r@rDrtTszIMAP4Server._respondcsTdg}|����D]<\�}|dkr.|���qt|�r|��fdd�|D��q|S)Ns	IMAP4rev1csg|]}�d|�qS)�=r@)rFr���cr@rDrJhsz0IMAP4Server.listCapabilities.<locals>.<listcomp>)r��itemsrrr�rw)r\�caps�vr@r~rDrmbszIMAP4Server.listCapabilitiescCs(|�dd�|����|�|d�dS)NsCAPABILITY r�sCAPABILITY completed)rr�rmror�r@r@rD�
do_CAPABILITYlszIMAP4Server.do_CAPABILITYcCs$|�d�|�|d�|j��dS)NsBYE Nice talking to yousLOGOUT successful)rror�rr�r@r@rD�	do_LOGOUTvs
zIMAP4Server.do_LOGOUTcCs|�|d�dS)NsNOOP No operation performed�ror�r@r@rD�do_NOOP�szIMAP4Server.do_NOOPcCs<|����}||jkr$|�|d�n|�|j|�|�dS)NsAUTHENTICATE method unsupported)r"rJr�r$�authenticate)r\r�r�r@r@rD�do_AUTHENTICATE�s
zIMAP4Server.do_AUTHENTICATEcCs*|jdkr|�|d�dS|�||�dS)Ns Temporary authentication failure)�portalr$�_setupChallenge)r\r�r�r@r@rDr��s
zIMAP4Server.authenticatec
Cs�z|��}Wn:tk
rF}z|�|dtt|���W5d}~XYnNXt|�dd�}d|_t��|_	|�
|�|j	�|j||�|j	�
|j|�dS)Nr6ryr:)ZgetChallengerr!rr��encodebytesrrr<rr=r0�_IMAP4Server__cbAuthChunkr	�_IMAP4Server__ebAuthChunk)r\r�r�Z	challengerZcodedr@r@rDr��s*

zIMAP4Server._setupChallengecCsxzt|�}Wntjk
r*td��YnX|�|�|��rL|�||�n(|j�|dt	��
|j|j|fd|fd�dS)NzMalformed Response - not base64)
�decodebytes�binascii�Errorr/ZsetResponseZmoreChallengesr�r��login�IAccount�addCallbacks�_IMAP4Server__cbAuthResp�_IMAP4Server__ebAuthResp)r\r5r�r�Zuncodedr@r@rDZ
__cbAuthChunk�s
�zIMAP4Server.__cbAuthChunkcCsH|\}}}|tkstd��||_d|_||_|�|d�|�|j�dS)Nz(IAccount is the only supported interface�authsAuthentication successful)r��AssertionError�accountrr�ror��POSTAUTH_TIMEOUT�r\r5r�ZifaceZavatar�logoutr@r@rDZ__cbAuthResp�s
zIMAP4Server.__cbAuthRespcCsJ|�t�r|�|d�n.|�t�r0|�|d�n|�|d�t�|�dS)Ns#Authentication failed: unauthorizeds+Authentication failed: server misconfigureds'Server error: login failed unexpectedly)r7rr$rr!r
r
r8r@r@rDZ__ebAuthResp�s

zIMAP4Server.__ebAuthRespcCs|�|dtt|j���dS)NsAuthentication failed: )r$rr�rbr8r@r@rDZ
__ebAuthChunk�szIMAP4Server.__ebAuthChunkcCs�|jr|�|d�nn|jrv|jrv|�|d�|j�|j�d|_|j��|_d|jkr`t	|jd<d|jkr�t
|jd<n|�|d�dS)NsTLS already negotiatedsBegin TLS negotiation nowT�LOGINsPLAINsTLS not available)r�r$r�r�ror��startTLSr��copyr+r-r�r@r@rD�do_STARTTLS�s


zIMAP4Server.do_STARTTLScCsBd|��kr|�|d�dSt|j||��|j|��|j|�dS)Nr�s!LOGIN is disabled before STARTTLS)r�r!r	�authenticateLoginr0�_IMAP4Server__cbLoginr	�_IMAP4Server__ebLogin)r\r��user�passwdr@r@rD�do_LOGIN�s��zIMAP4Server.do_LOGINcCs(|jr|j�t�||�dt�St��dS)a�
        Lookup the account associated with the given parameters

        Override this method to define the desired authentication behavior.

        The default behavior is to defer authentication to C{self.portal}
        if it is not None, or to deny the login otherwise.

        @type user: L{str}
        @param user: The username to lookup

        @type passwd: L{str}
        @param passwd: The password to login with
        N)r�r�rZUsernamePasswordr�r)r\r�r�r@r@rDr��s
�zIMAP4Server.authenticateLogincCs^|\}}}|tk	r0|�|d�t�d|f�n*||_||_|�|d�d|_|�|j	�dS)Ns-Server error: login returned unexpected valuez+__cbLogin called with %r, IAccount expectedsLOGIN succeededr�)
r�r!r
r
r�r�rorr�r�r�r@r@rDZ	__cbLogin	s
zIMAP4Server.__cbLogincCs@|�t�r|�|d�n$|�|dtt|j���t�|�dS)NsLOGIN failedr6)	r7rr$r!rr�rbr
r
r8r@r@rDZ	__ebLogins
zIMAP4Server.__ebLogincCs`d}}}t|jd�}|dk	r8|��}|��}|��}|�dt|||g��|�|d�dS)Ns
NAMESPACE sNAMESPACE command completed)rr��getPersonalNamespaces�getSharedNamespacesr�collapseNestedListsro)r\r�ZpersonalZpublicZsharedZnpr@r@rD�do_NAMESPACEszIMAP4Server.do_NAMESPACEcCs||jrD|j�|�t|jd�}|dk	r8t|j��tj�d|_d|_t	|�}t|j
jt	|�|��|j
||��|j||�dS)Nr�)rrrr	rr	r
r
r�
_parseMboxr��selectr0�
_cbSelectWork�
_ebSelectWork)r\r��name�rw�cmdNamerr@r@rD�_selectWork,s"��zIMAP4Server._selectWorkcCs|�||d�t�|�dS)Ns failed: Server error�r!r
r
)r\r9r�r�r@r@rDr�<szIMAP4Server._ebSelectWorkcCs�|dkr|�|d�dSddd�|��D�kr>|�|d�dSdd�|��D�}|�t|���d�|�t|���d�|�d	d
�|�d�|�ddt|���d
�|�	�r�dp�d}|�
|�|�|d|d|d�d|_||_dS)NsNo such mailboxz	\noselectcSsg|]}|���qSr@)�lower�rFr�r@r@rDrJEsz-IMAP4Server._cbSelectWork.<locals>.<listcomp>zMailbox cannot be selectedcSsg|]}t|��qSr@�r�rF�flagr@r@rDrJIs� EXISTS� RECENT�FLAGS (r�rTs
[UIDVALIDITY �]r�r��[rks successfulr�)
r$�getFlagsrr�getMessageCount�getRecentCountr�ro�getUIDValidity�isWriteableZaddListenerrr)r\rr�r�rbr�r@r@rDr�As 
zIMAP4Server._cbSelectWorkr>�SELECTr�EXAMINEcCs"|�d�||_|j|_d|_dS)NZidle)r=�parseTagr�	lastStater�r@r@rD�do_IDLE\s
zIMAP4Server.do_IDLEcGs"|j|_|`|�|jd�|`dS)NsIDLE terminated)r�rror�)r\r�r@r@rD�
parse_idlecszIMAP4Server.parse_idlec
Cs�t|�}z|j�|�}WnTtk
rN}z|�|tt|���W5d}~XYn>|�|d�t�	�Yn X|r�|�
|d�n|�|d�dS)Ns/Server error encountered while creating mailboxsMailbox createdsMailbox not created)r�r��creater1r$rr�r!r
r
ro)r\r�r�r5rr@r@rD�	do_CREATEms$zIMAP4Server.do_CREATEc
Cs�t|�}|��dkr$|�|d�dSz|j�|�WnVtk
rl}z|�|t|��d��W5d}~XYn,|�|d�t	�
�YnX|�|d�dS)N�inboxsYou cannot delete the inbox�imap4-utf-7s/Server error encountered while deleting mailboxsMailbox deleted)r�r�r$r��deleter1r��encoder!r
r
ro�r\r�r�rQr@r@rD�	do_DELETE�s&zIMAP4Server.do_DELETEc
Cs�dd�||fD�\}}|��dks.|��dkr>|�|d�dSz|j�||�Wnrtk
rp|�|d�Yn`tk
r�}z|�|tt|���W5d}~XYn,|�|d�t	�
�YnX|�|d�dS)NcSsg|]}t|��qSr@)r�)rF�nr@r@rDrJ�sz)IMAP4Server.do_RENAME.<locals>.<listcomp>r�s@You cannot rename the inbox, or rename another mailbox to inbox.sInvalid command syntaxs/Server error encountered while renaming mailboxsMailbox renamed)r�r$r��renamersr!r1rr�r
r
ro)r\r��oldname�newnamerQr@r@rD�	do_RENAME�s$zIMAP4Server.do_RENAMEc
Cs~t|�}z|j�|�WnTtk
rN}z|�|tt|���W5d}~XYn,|�|d�t�	�YnX|�
|d�dS)Ns5Server error encountered while subscribing to mailboxs
Subscribed)r�r��	subscriber1r$rr�r!r
r
ror�r@r@rD�do_SUBSCRIBE�s$zIMAP4Server.do_SUBSCRIBEc
Cs~t|�}z|j�|�WnTtk
rN}z|�|tt|���W5d}~XYn,|�|d�t�	�YnX|�
|d�dS)Ns9Server error encountered while unsubscribing from mailboxsUnsubscribed)r�r��unsubscriber1r$rr�r!r
r
ror�r@r@rD�do_UNSUBSCRIBE�s$zIMAP4Server.do_UNSUBSCRIBEcCs<t|�}t|�}t|jj||��|j|||��|j|�dSrg)r�r	r��
listMailboxesr0�_cbListWorkr	�_ebListWork)r\r��refr�subr�r@r@rD�	_listWork�s��zIMAP4Server._listWorkc
Cs||D]b\}}|r|j�|�rdd�|��D�}|���d�}t|�tt|�||�d�f}	|�t|	��q|�	||d�dS)NcSsg|]}t|��qSr@r�r�r@r@rDrJ�sz+IMAP4Server._cbListWork.<locals>.<listcomp>r�s
 completed)
r��isSubscribedr�ZgetHierarchicalDelimiterr��DontQuoteMe�maprr�ro)
r\�	mailboxesr�r�r�r��boxrb�delim�respr@r@rDr��szIMAP4Server._cbListWorkcCs|�|d�t�|�dS)Ns1Server error encountered while listing mailboxes.r�r8r@r@rDr��szIMAP4Server._ebListWorkr�r�cCsPg}|D]}|�t|��qt|�}t|jj|d��|j|||��|j	|�dSr�)
rrrr�r	r�r�r0�_cbStatusGotMailboxr	�_ebStatusGotMailbox)r\r��mailboxr�ZnativeNamesr�r@r@rD�	do_STATUS�s��zIMAP4Server.do_STATUScCs>|r.t|j|��|j|j||fd||fd�n|�|d�dS)NsCould not open mailbox)r	Z
requestStatusr��_IMAP4Server__cbStatus�_IMAP4Server__ebStatusr$)r\rr�r�r�r@r@rDr��s�zIMAP4Server._cbStatusGotMailboxcCs|�|d�t�|�dS�Ns/Server error encountered while opening mailbox.r�r8r@r@rDr��szIMAP4Server._ebStatusGotMailboxcCsLtd�dd�|��D���}|�d|�d�d|d�|�|d�dS)	N� cSsg|]}d|�qS)z%s %sr@�rFrPr@r@rDrJsz*IMAP4Server.__cbStatus.<locals>.<listcomp>�STATUS r�� (rTsSTATUS complete)rr�r�rr�ro)r\�statusr�r�r�r@r@rD�
__cbStatuss zIMAP4Server.__cbStatuscCs&|�|d|dtt|j���dS)Nr�s	 failed: �r!rr�rb)r\r9r�r�r@r@rDZ
__ebStatuss�zIMAP4Server.__ebStatuscCs4t|�}t|jj|��|j||||��|j|�dSrg)r�r	r�r�r0�_cbAppendGotMailboxr	�_ebAppendGotMailbox)r\r�r�rbrgrlr@r@rD�	do_APPENDs��zIMAP4Server.do_APPENDcCsR|s|�|d�dSdd�|D�}|�|||�}|�|j||�|�|j|�dS)NzRYCREATE] No such mailboxcSsg|]}t|��qSr@�rr�r@r@rDrJsz3IMAP4Server._cbAppendGotMailbox.<locals>.<listcomp>)r$�
addMessager0�_IMAP4Server__cbAppendr	�_IMAP4Server__ebAppend)r\rr�rbrgrlZdecodedFlagsr�r@r@rDr�szIMAP4Server._cbAppendGotMailboxcCs|�|d�t�|�dSr�r�r8r@r@rDr�$szIMAP4Server._ebAppendGotMailboxcCs&|�t|���d�|�|d�dS)Nr�sAPPEND complete)rrr�ro)r\r5r�rr@r@rDZ
__cbAppend-szIMAP4Server.__cbAppendcCs|�|dtt|j���dS)NsAPPEND failed: r�r8r@r@rDZ
__ebAppend2s�zIMAP4Server.__ebAppendcCs<|��}|dkr|�d|�n|j|j|j|f|fd�dS)N)�callbackArgsZerrbackArgs)�
checkpoint�_IMAP4Server__cbCheckr��_IMAP4Server__ebCheck�r\r�r�r@r@rD�do_CHECK7s�zIMAP4Server.do_CHECKcCs|�|d�dS)NsCHECK completedr��r\r5r�r@r@rDZ	__cbCheckEszIMAP4Server.__cbCheckcCs|�|dtt|j���dS)NsCHECK failed: r�r8r@r@rDZ	__ebCheckIs�zIMAP4Server.__ebCheckcCsdS)ah
        Called when the client issues a CHECK command.

        This should perform any checkpoint operations required by the server.
        It may be a long running operation, but may not block.  If it returns
        a deferred, the client will only be informed of success (or failure)
        when the deferred's callback (or errback) is invoked.
        Nr@rhr@r@rDr�Ns	zIMAP4Server.checkpointcs�d}|j��rt|jj�}t|jd���dk	rT|dk	rJ|��fdd��n
t�j�}|dk	rz|�|j|j	|fd|fd�n|�d|�dS)Ncs���Srg)r)r5�rr@rDrQarRz&IMAP4Server.do_CLOSE.<locals>.<lambda>)
rr�r	�expungerr0rr��_IMAP4Server__cbClose�_IMAP4Server__ebCloser�r@rrD�do_CLOSEZs

zIMAP4Server.do_CLOSEcCs(|�|d�|j�|�d|_d|_dS)NsCLOSE completedr�)rorrrrr@r@rDZ	__cbCloselszIMAP4Server.__cbClosecCs|�|dtt|j���dS)NsCLOSE failed: r�r8r@r@rDZ	__ebClosess�zIMAP4Server.__ebClosecCs@|j��r0t|jj��|j|j|fd|fd�n|�|d�dS)Ns$EXPUNGE ignored on read-only mailbox)rr�r	rr��_IMAP4Server__cbExpunge�_IMAP4Server__ebExpunger$r�r@r@rD�
do_EXPUNGExs
�zIMAP4Server.do_EXPUNGEcCs,|D]}|�t|�d�q|�|d�dS)Ns EXPUNGEsEXPUNGE completed)rrro)r\r5r�rr@r@rD�__cbExpunge�szIMAP4Server.__cbExpungecCs(|�|dtt|j���t�|�dS)NsEXPUNGE failed: �r!rr�rbr
r
r8r@r@rDZ__ebExpunge�s�zIMAP4Server.__ebExpungecCszt|jd�}|dk	r@t|j||d��|j||j|��|j|�n6td�}t|jj	||d��|j
||j||��|j|�dS)N�r+s1:*)�ISearchableMailboxrr	rar0�_IMAP4Server__cbSearchr	�_IMAP4Server__ebSearchr[�fetch�_IMAP4Server__cbManualSearch)r\r��charsetrYr+Zsmr�r@r@rD�	do_SEARCH�s,����zIMAP4Server.do_SEARCHcCsF|rt|j|�}td�dd�|D���}|�d|�|�|d�dS)Nr�cSsg|]}t|��qSr@r��rFrcr@r@rDrJ�sz*IMAP4Server.__cbSearch.<locals>.<listcomp>�SEARCH �SEARCH completed)r��getUIDrr�rro)r\r5r�rr+�idsr@r@rD�
__cbSearch�s
zIMAP4Server.__cbSearchc

Cs�|dkrg}d}|o|dd}|o2|dd��}	tttd�|��D]J\}\}
}|�t�|�|
|||	�rF|r�|�t|����qF|�t|
��qF|dkr�ddl	m
}|�d|jt|dd��|||||�n$|r�|�
dd	�|��|�|d
�dS)aL
        Apply the search filter to a set of messages. Send the response to the
        client.

        @type result: L{list} of L{tuple} of (L{int}, provider of
            L{imap4.IMessage})
        @param result: A list two tuples of messages with their sequence ids,
            sorted by the ids in descending order.

        @type tag: L{str}
        @param tag: A command tag.

        @type mbox: Provider of L{imap4.IMailbox}
        @param mbox: The searched mailbox.

        @type query: L{list}
        @param query: A list representing the parsed form of the search query.

        @param uid: A flag indicating whether the search is over message
            sequence numbers or UIDs.

        @type searchResults: L{list}
        @param searchResults: The search results so far or L{None} if no
            results yet.
        Nrryr>����reactorrr�r)rrX�zip�range�
_searchFilterr��deepcopyrrr�twisted.internetr�	callLaterrrr�ro)
r\r5r�rrYr+Z
searchResultsrc�lastSequenceId�
lastMessageId�msgIdrqrr@r@rDZ__cbManualSearch�s8��zIMAP4Server.__cbManualSearchcCs |r|�|||||�sdSqdS)a�
        Pop search terms from the beginning of C{query} until there are none
        left and apply them to the given message.

        @param query: A list representing the parsed form of the search query.

        @param id: The sequence number of the message being checked.

        @param msg: The message being checked.

        @type lastSequenceId: L{int}
        @param lastSequenceId: The highest sequence number of any message in
            the mailbox being searched.

        @type lastMessageId: L{int}
        @param lastMessageId: The highest UID of any message in the mailbox
            being searched.

        @return: Boolean indicating whether all of the query terms match the
            message.
        FT��_singleSearchStep)r\rY�idrqr$r%r@r@rDr �s
�zIMAP4Server._searchFiltercCs�|�d�}t|t�r,|�|||||�s�dSn�|��}|dd���sVt||�}||kSt|dt|�d�}	|	dkr�t	dt|���||j
kr�|	|||||f�}
n|	|||�}
|
s�dSdS)a�
        Pop one search term from the beginning of C{query} (possibly more than
        one element) and return whether it matches the given message.

        @param query: A list representing the parsed form of the search query.

        @param msgId: The sequence number of the message being checked.

        @param msg: The message being checked.

        @param lastSequenceId: The highest sequence number of any message in
            the mailbox being searched.

        @param lastMessageId: The highest UID of any message in the mailbox
            being searched.

        @return: Boolean indicating whether the query term matched the message.
        rFNr>Zsearch_zInvalid search command %sT)rrWrXr r"�isalphar[rrr:�_requiresLastMessageInfo)r\rYr&rqr$r%�qrZ
messageSetrr5r@r@rDr(�s,


�


�zIMAP4Server._singleSearchStepcCsdS)aS
        Returns C{True} if the message matches the ALL search key (always).

        @type query: A L{list} of L{str}
        @param query: A list representing the parsed query string.

        @type id: L{int}
        @param id: The sequence number of the message being checked.

        @type msg: Provider of L{imap4.IMessage}
        Tr@�r\rYr)rqr@r@rD�
search_ALL/szIMAP4Server.search_ALLcCsd|��kS)aA
        Returns C{True} if the message has been answered.

        @type query: A L{list} of L{str}
        @param query: A list representing the parsed query string.

        @type id: L{int}
        @param id: The sequence number of the message being checked.

        @type msg: Provider of L{imap4.IMessage}
        �	\Answered�r�r-r@r@rD�search_ANSWERED>szIMAP4Server.search_ANSWEREDcCs0|�dd��dd�}|���|�d����dkS)aR
        Returns C{True} if the message has a BCC address matching the query.

        @type query: A L{list} of L{str}
        @param query: A list whose first element is a BCC L{str}

        @type id: L{int}
        @param id: The sequence number of the message being checked.

        @type msg: Provider of L{imap4.IMessage}
        F�bcc�rry��
getHeaders�getr�rVr)r\rYr)rqr2r@r@rD�
search_BCCMszIMAP4Server.search_BCCcCs&t|�d��}tj�t|����|kSr�)�	parseTimer�email�utils�	parsedater�getInternalDate�r\rYr)rqrgr@r@rD�
search_BEFORE]szIMAP4Server.search_BEFOREcCs |�d���}t�||��d�S�NrF�rr�rZstrFile�getBodyFile�r\rYr)rq�bodyr@r@rD�search_BODYbszIMAP4Server.search_BODYcCs0|�dd��dd�}|���|�d����dkS)NF�ccr3rryr4)r\rYr)rqrEr@r@rD�	search_CCgszIMAP4Server.search_CCcCsd|��kS�Nz\Deletedr0r-r@r@rD�search_DELETEDlszIMAP4Server.search_DELETEDcCsd|��kS�Nz\Draftr0r-r@r@rD�search_DRAFTpszIMAP4Server.search_DRAFTcCsd|��kS�Nz\Flaggedr0r-r@r@rD�search_FLAGGEDtszIMAP4Server.search_FLAGGEDcCs0|�dd��dd�}|���|�d����dkS)NF�fromr3rryr4)r\rYr)rqZfmr@r@rD�search_FROMxszIMAP4Server.search_FROMcCs>|�d���}|�d|��|d�}|���|�d����dkS)NrFr3ry)rr�r5r6rV)r\rYr)rqZhdrr@r@rD�
search_HEADER}szIMAP4Server.search_HEADERcCs|�d�dSr?�rr-r@r@rD�search_KEYWORD�s
zIMAP4Server.search_KEYWORDcCst|�d��|��kSr��rKr�getSizer-r@r@rD�
search_LARGER�szIMAP4Server.search_LARGERcCsd|��kod|��kS)N�\Recent�\Seenr0r-r@r@rD�
search_NEW�szIMAP4Server.search_NEWcCs|\}}|�|||||�S)a�
        Returns C{True} if the message does not match the query.

        @type query: A L{list} of L{str}
        @param query: A list representing the parsed form of the search query.

        @type id: L{int}
        @param id: The sequence number of the message being checked.

        @type msg: Provider of L{imap4.IMessage}
        @param msg: The message being checked.

        @type lastIDs: L{tuple}
        @param lastIDs: A tuple of (last sequence id, last message id).
        The I{last sequence id} is an L{int} containing the highest sequence
        number of a message in the mailbox.  The I{last message id} is an
        L{int} containing the highest UID of a message in the mailbox.
        r')r\rYr)rq�lastIDsr$r%r@r@rD�
search_NOT�s

�zIMAP4Server.search_NOTcCsd|��kS�NrUr0r-r@r@rD�
search_OLD�szIMAP4Server.search_OLDcCs"t|�d��}tj�|���|kSr��r8rr9r:r;r<r=r@r@rD�	search_ON�szIMAP4Server.search_ONc	Cs4|\}}|�|||||�}|�|||||�}|p2|S)a�
        Returns C{True} if the message matches any of the first two query
        items.

        @type query: A L{list} of L{str}
        @param query: A list representing the parsed form of the search query.

        @type id: L{int}
        @param id: The sequence number of the message being checked.

        @type msg: Provider of L{imap4.IMessage}
        @param msg: The message being checked.

        @type lastIDs: L{tuple}
        @param lastIDs: A tuple of (last sequence id, last message id).
        The I{last sequence id} is an L{int} containing the highest sequence
        number of a message in the mailbox.  The I{last message id} is an
        L{int} containing the highest UID of a message in the mailbox.
        r')	r\rYr)rqrXr$r%�a�br@r@rD�	search_OR�s
�
�zIMAP4Server.search_ORcCsd|��kSrZr0r-r@r@rD�
search_RECENT�szIMAP4Server.search_RECENTcCsd|��kS�NrVr0r-r@r@rD�search_SEEN�szIMAP4Server.search_SEENcCs2|�dd��dd�}tj�|�}|t|�d��kS)a�
        Returns C{True} if the message date is earlier than the query date.

        @type query: A L{list} of L{str}
        @param query: A list whose first element starts with a stringified date
            that is a fragment of an L{imap4.Query()}. The date must be in the
            format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.

        @type id: L{int}
        @param id: The sequence number of the message being checked.

        @type msg: Provider of L{imap4.IMessage}
        Frgr3r�r5r6r9r:r;r8rr=r@r@rD�search_SENTBEFORE�szIMAP4Server.search_SENTBEFOREcCsB|�dd��dd�}tj�|�}|dd�t|�d��dd�kS)a�
        Returns C{True} if the message date is the same as the query date.

        @type query: A L{list} of L{str}
        @param query: A list whose first element starts with a stringified date
            that is a fragment of an L{imap4.Query()}. The date must be in the
            format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.

        @type msg: Provider of L{imap4.IMessage}
        Frgr3Nrrrdr=r@r@rD�
search_SENTON�szIMAP4Server.search_SENTONcCs2|�dd��dd�}tj�|�}|t|�d��kS)a�
        Returns C{True} if the message date is later than the query date.

        @type query: A L{list} of L{str}
        @param query: A list whose first element starts with a stringified date
            that is a fragment of an L{imap4.Query()}. The date must be in the
            format 'DD-Mon-YYYY', for example '03-March-2003' or '03-Mar-2003'.

        @type msg: Provider of L{imap4.IMessage}
        Frgr3rrdr=r@r@rD�search_SENTSINCE�szIMAP4Server.search_SENTSINCEcCs"t|�d��}tj�|���|kSr�r\r=r@r@rD�search_SINCEszIMAP4Server.search_SINCEcCst|�d��|��kSr�rRr-r@r@rD�search_SMALLER
szIMAP4Server.search_SMALLERcCs0|�dd��dd�}|���|�d����dkS)NF�subjectr3rryr4)r\rYr)rqZsubjr@r@rD�search_SUBJECTszIMAP4Server.search_SUBJECTcCs |�d���}t�||��d�Sr?r@rBr@r@rD�search_TEXTszIMAP4Server.search_TEXTcCs0|�dd��dd�}|���|�d����dkS)NF�tor3rryr4)r\rYr)rqrmr@r@rD�	search_TOszIMAP4Server.search_TOc	Cs(|\}}|�d�}t||�}|��|kS)al
        Returns C{True} if the message UID is in the range defined by the
        search query.

        @type query: A L{list} of L{bytes}
        @param query: A list representing the parsed form of the search
            query. Its first element should be a L{str} that can be interpreted
            as a sequence range, for example '2:4,5:*'.

        @type id: L{int}
        @param id: The sequence number of the message being checked.

        @type msg: Provider of L{imap4.IMessage}
        @param msg: The message being checked.

        @type lastIDs: L{tuple}
        @param lastIDs: A tuple of (last sequence id, last message id).
        The I{last sequence id} is an L{int} containing the highest sequence
        number of a message in the mailbox.  The I{last message id} is an
        L{int} containing the highest UID of a message in the mailbox.
        r)rr[r)	r\rYr)rqrXr$r%rrQr@r@rD�
search_UID!s

zIMAP4Server.search_UIDcCsd|��kS)Nr/r0r-r@r@rD�search_UNANSWERED=szIMAP4Server.search_UNANSWEREDcCsd|��kSrGr0r-r@r@rD�search_UNDELETEDAszIMAP4Server.search_UNDELETEDcCsd|��kSrIr0r-r@r@rD�search_UNDRAFTEszIMAP4Server.search_UNDRAFTcCsd|��kSrKr0r-r@r@rD�search_UNFLAGGEDIszIMAP4Server.search_UNFLAGGEDcCs|�d�dSr?rPr-r@r@rD�search_UNKEYWORDMs
zIMAP4Server.search_UNKEYWORDcCsd|��kSrbr0r-r@r@rD�
search_UNSEENRszIMAP4Server.search_UNSEENcCs(|�|dtt|j���t�|�dS)NsSEARCH failed: rr8r@r@rDZ
__ebSearchVs�zIMAP4Server.__ebSearchcCsR|rB|�d�|_t|jj||d��t��|j|||��|j	|�n|�
|d�dS)NrsFETCH complete)r��_oldTimeoutr	rrr0�iter�_IMAP4Server__cbFetchr	�_IMAP4Server__ebFetchro)r\r��messagesrYr+r@r@rD�do_FETCH\s���zIMAP4Server.do_FETCHcs��jdkrg�_zt��\}}Wn8tk
rX���j��`���d����Yn0X��||���������fdd���	�j
�dS)NsFETCH completedcs�������Srg)rx�r.�rY�resultsr\r�r+r@rDrQ�rRz'IMAP4Server.__cbFetch.<locals>.<lambda>)r�next�
StopIterationr�rvror�spewMessager0r	�_IMAP4Server__ebSpewMessage)r\r~r�rYr+r)rqr@r}rDZ	__cbFetchjs
��zIMAP4Server.__cbFetchcCst�|�|j��dSrg)r
r
r�r�r\r9r@r@rDZ__ebSpewMessage�s
zIMAP4Server.__ebSpewMessagecCs*|dkr|jj}|dtt|�g��dS)Ns	ENVELOPE )r�r�r��getEnvelope�r\r)rq�_w�_fr@r@rD�
spew_envelope�szIMAP4Server.spew_envelopecCs<|dkr|jj}dd�|��D�}|dd�|�d�dS)NcSsg|]}t|��qSr@r�r�r@r@rDrJ�sz*IMAP4Server.spew_flags.<locals>.<listcomp>r�r�rT)r�Zwritenr�r�)r\r)rqr�r��encodedFlagsr@r@rD�
spew_flags�szIMAP4Server.spew_flagsc
Cs�|dkr|jj}|��}tj�t|��}|dkrLt�d|||f�t	d��t
�d|dd��}t|t
|df�}|ddkr�|d}nP|ddkr�d}	nd	}	||	tt|d�d
dt|d�d
d��d
�}|dt|��dS)Nz$%d:%r: unpareseable internaldate: %rz(Internal failure generating INTERNALDATEz%d-%%s-%Y %H:%M:%S �	r>s+0000rrz�-i�dr�rs
INTERNALDATE )r�r�r<r9r:Zparsedate_tzrr
rqr.�time�strftimer�_MONTH_NAMESr�abs�zfill�_quote)
r\r)rqr�r�ZidateZttupZstrdateZodateZsignr@r@rD�spew_internaldate�s,
���zIMAP4Server.spew_internaldatecCs2|dkr|jj}t|�d��}|dt|��dS)NTsRFC822.HEADER )r�r��_formatHeadersr5�_literal)r\r)rqr�r��hdrsr@r@rD�spew_rfc822header�szIMAP4Server.spew_rfc822headercCs2|dkr|jj}|d�|�t|����|j�S)NsRFC822.TEXT )r�r��FileProducerrA�beginProducingr�r@r@rD�spew_rfc822text�s�zIMAP4Server.spew_rfc822textcCs(|dkr|jj}|dt|����dS)NsRFC822.SIZE )r�r�rrSr�r@r@rD�spew_rfc822size�szIMAP4Server.spew_rfc822sizecCsZ|dkr|jj}|d�|�t|d�}|dk	rDt|����|j�St|d|j��|j�S)NsRFC822 )r�r��IMessageFiler��openr��MessageProducerr�)r\r)rqr�r��mfr@r@rD�spew_rfc822�s
��zIMAP4Server.spew_rfc822cCs(|dkr|jj}|dt|����dS)NsUID )r�r�rrr�r@r@rD�spew_uid�szIMAP4Server.spew_uidcCs|dtt|d�g��dS)NsBODYSTRUCTURE T)r��getBodyStructurer�r@r@rD�spew_bodystructure�szIMAP4Server.spew_bodystructurec	Csr|dkr|jj}|jD](}|��r.|�|�}q|dkrtd��q|jr�|j|jjf|jj	��}t
|�}||��dt|��n�|j
r�||��d�|�t|����|j�S|jr�t
|�d��}||��dt|��n�|j�rX||��d�|�|j�rt|����|j�St|d�}|dk	�r@t|����|j�St|d|j��|j�Sn|dtt|�g��dS)Nrz*Requested subpart of non-multipart messager�TsBODY )r�r��part�isMultipart�
getSubPartrs�headerr5�negate�fieldsr��	__bytes__r�rr�rAr��mime�emptyr�r�r�r�r�r�)	r\r�r)rqr�r�r�r�r�r@r@rD�	spew_body�s@

��

zIMAP4Server.spew_bodyc
sft�j�}|j�	|j���	fdd���	fdd���	fdd������������	f
dd�}��|��S)	Ncs�dt��d�dS)Ns* s FETCH ()rr@)r)r�r@rDr]	sz&IMAP4Server.spewMessage.<locals>.startcs�d�dS)Ns)
r@r@�r�r@rDr�	sz'IMAP4Server.spewMessage.<locals>.finishcs�d�dSr�r@r@r�r@rD�space	sz&IMAP4Server.spewMessage.<locals>.spacec3s�d}���D]d}|jdkr d}|jdkr@��|���	��Vn t�d|j�}|���	��V|�dk	r��q�r�|s��������	��V����dS)NFr+TrCZspew_ry)�typer�rr�)ZseenUIDr�r�
r�r�r)rqrYr\r�r]r+r�r@rD�spew"	s 

z%IMAP4Server.spewMessage.<locals>.spew)r�r�r�r�r�)r\r)rqrYr+Zwbufr�r@r�rDr�	s
zIMAP4Server.spewMessagecCs8|�|j�|`t�|�|�|dtt|j���dS)NsFETCH failed: )r�rvr
r
r!rr�rbr8r@r@rDZ	__ebFetch7	s
�zIMAP4Server.__ebFetchcCs~|��}|�d�}|�d�r"d}n|�d�r2d}nd}dd�|D�}t|jj||||d	��|j|j||j||fd|fd�dS)
NsSILENTrzr>r�ryrcSsg|]}t|��qSr@r�r�r@r@rDrJI	sz(IMAP4Server.do_STORE.<locals>.<listcomp>r)	r"�endswithrer	r�storer��_IMAP4Server__cbStore�_IMAP4Server__ebStore)r\r�rz�moderbr+�silentr@r@rD�do_STORE?	s 


�zIMAP4Server.do_STOREc
Cs||rl|sl|��D]Z\}}|r0dt|�|��}nd}dd�|D�}	|�t|�dd�|	�d|d�q|�|d�dS)	Ns UID rRcSsg|]}t|��qSr@r�r�r@r@rDrJY	sz)IMAP4Server.__cbStore.<locals>.<listcomp>� FETCH (FLAGS (r�rTsSTORE completed)r�rrrr�ro)
r\r5r�rr+r��kr�Zuidstrrbr@r@rDZ	__cbStoreQ	s(������zIMAP4Server.__cbStorecCs|�|dtt|j���dS�Nr6r�r8r@r@rDZ	__ebStorea	s�zIMAP4Server.__ebStorecCs6|�|�}t|jj|��|j||||��|j|�dSrg)r�r	r�r�r0�_cbCopySelectedMailboxr	�_ebCopySelectedMailbox)r\r�rzr�r+r@r@rD�do_COPYf	s
��zIMAP4Server.do_COPYcCsL|s|�|d|�n2t|jj||��|j||��|j||��|j|�dS)NzNo such mailbox: )	r$r	rrr0�_IMAP4Server__cbCopy�_IMAP4Server__cbCopiedr	�_IMAP4Server__ebCopy)r\rr�rzr�r+r@r@rDr�o	s���z"IMAP4Server._cbCopySelectedMailboxcCs|�|dtt|j���dSr�r�r8r@r@rDr�z	s�z"IMAP4Server._ebCopySelectedMailboxcs�g}t�d�}|D]�\}}|dk	r:t|j|�}|�|�q|��}	|��}
t|d�}|dk	rv|��}t�j||	|
�}n<dd��t	�
�}
t||
|j��
d��|
|	|
f��fdd�	�}|�|�qt�|�S)NcSs|�d�|Sr�)r��rr@r@rD�rewind�	s
z$IMAP4Server.__cbCopy.<locals>.rewindcs���|�||�Srg)r�)r.r_rr��rr�r@rDrQ�	rRz&IMAP4Server.__cbCopy.<locals>.<lambda>)�IMessageCopierr	r�rrr�r<r�r�r�r�r�r�r�r�r0rZDeferredList)r\rzr�rZaddedDeferredsZfastCopyMboxr)rqr�rbrgrCZbodyFile�bufferr@r�rDZ__cbCopy	s,


��zIMAP4Server.__cbCopycCsTg}g}|D]$\}}|r$|�|�q|�|j�q|rD|�|d�n|�|d�dS)Nz%[ALERT] Some messages were not copiedsCOPY completed)rrrbr$ro)r\ZdeferredIdsr�rrZfailuresr�r5r@r@rDZ
__cbCopied�	szIMAP4Server.__cbCopiedcCs(|�|dtt|j���t�|�dS)NsCOPY failed:rr8r@r@rDZ__ebCopy�	s�zIMAP4Server.__ebCopycCs.|��}|dkrt|��|j|||dd�dS)N)�COPYr��STOREr�r>r)r"r/r#)r\r�r�r�r@r@rD�do_UID�	szIMAP4Server.do_UIDcCs&|r|jddd�n|jddd�dS)Ns[READ-WRITE]T)rlrws[READ-ONLY])r�r\Z	writeabler@r@rD�modeChanged�	szIMAP4Server.modeChangedcCsL|��D]>\}}dd�|D�}t|�dd�|�d}|j|dd�qdS)NcSsg|]}t|��qSr@r�r�r@r@rDrJ�	sz,IMAP4Server.flagsChanged.<locals>.<listcomp>r�r�s))T�rw)r�rr�r)r\�newFlags�mIdrbr�rqr@r@rD�flagsChanged�	s�zIMAP4Server.flagsChangedcCs@|dk	r|jt|�ddd�|dk	r<|jt|�ddd�dS)Nr�Tr�r�)rr�r\�exists�recentr@r@rD�newMessages�	s
�
�zIMAP4Server.newMessages)NNN)N)F)NrR)NrR)NrR)N)ry)r)N)r)NN)NN)NN)NN)NN)NN)NN)NN)NN)NN)r)r)�r�r�r�r�rnr�r�r�r�r�r�r�r�rrr;r��setr+rrr_r�r�rr
rrrrr'r(r#r)r*r1r2r@rArDrC�re�compile�escape�
_atomCharsrNrRrWrXrZr\r_rcrdrfrhrjr�r!ror$rr=rtrmr�Zunauth_CAPABILITYZauth_CAPABILITYZselect_CAPABILITYZlogout_CAPABILITYr�Z
unauth_LOGOUTZauth_LOGOUTZ
select_LOGOUTZ
logout_LOGOUTr�Zunauth_NOOPZ	auth_NOOPZselect_NOOPZlogout_NOOPr�Zunauth_AUTHENTICATEr�r�r�r�r�r�r�Zunauth_STARTTLSr�Zunauth_LOGINr�r�r�r�Zauth_NAMESPACEZselect_NAMESPACEr�r�r�Zauth_SELECTZ
select_SELECTZauth_EXAMINEZselect_EXAMINEr�r�Zselect_IDLEZ	auth_IDLEr�Zauth_CREATEZ
select_CREATEr�Zauth_DELETEZ
select_DELETEr�Zauth_RENAMEZ
select_RENAMEr�Zauth_SUBSCRIBEZselect_SUBSCRIBEr�Zauth_UNSUBSCRIBEZselect_UNSUBSCRIBEr�r�r�Z	auth_LISTZselect_LISTZ	auth_LSUBZselect_LSUBr�r�r�Zauth_STATUSZ
select_STATUSr�r�r�r�r�Zauth_APPENDZ
select_APPENDr�r�rZselect_CHECKr�r�r�rZselect_CLOSErrr	Zselect_EXPUNGErrrZ
select_SEARCHrrr r(r.r1r7r>rDrFrHrJrLrNrOrQrTrWrYr[r]r`rarcrerfrgrhrirkrlrnrorprqrrrsrtrurr{Zselect_FETCHrxr�r�r�r�r�r�r�r�r�r�r�r�ryr�Zselect_STOREr�r�r�Zselect_COPYr�r�r�r�r�r�Z
select_UIDr�r�r�r@r@r@rDr�Rs�
	

0

	








	



�
	�
81

$	
) 
"
	r�c@s6eZdZdZdZdZdZdZdZdZ	dZ
dZdZdZ
dZeeed�ZdZd�d	d
�Zdd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Z d'd(�Z!d)d*�Z"d+d,�Z#d�d-d.�Z$d/d0�Z%d1d2�Z&d3d4�Z'd5d6�Z(d7d8�Z)d�d9d:�Z*d;d<�Z+d=d>�Z,d?d@�Z-dAdB�Z.dCdD�Z/dEdF�Z0dGdH�Z1dIdJ�Z2dKdL�Z3dMdN�Z4dOdP�Z5dQdR�Z6dSdT�Z7dUdV�Z8dWdX�Z9dYdZ�Z:d[d\�Z;d]d^�Z<d_d`�Z=dadb�Z>dcdd�Z?dedf�Z@dgdh�ZAdidj�ZBdkdl�ZCdmdn�doD�ZDdpdq�ZEdrds�ZFd�dudv�ZGdwdx�ZHdydz�ZId{d|�ZJd}d~�ZKdd��ZLd�d��ZMd�d��ZNd�d��ZOd�d�d��ZPd�d�d��ZQd�d�d��ZRd�d�d��ZSd�d�d��ZTd�d�d��ZUd�d�d��ZVd�d�d��ZWd�d�d��ZXd�d�d��ZYd�d�d��ZZd�d�d��Z[d�d�d��Z\d�d��Z]d�d��Z^d�d�d��Z_d�d�d��Z`d�d�d��Zad�d�d��Zbd�d�d��Zcd�d��Zdd�d��Zed�d��Zfd�d��Zgd�d��ZhdS)��IMAP4ClientzIMAP4 client protocol implementation

    @ivar state: A string representing the state the connection is currently
    in.
    Nr>Frr�)ZOKZNOZBADZPREAUTHZBYE)�MESSAGES�RECENT�UNSEENcCs.i|_g|_i|_||_d|_d|_d|_dSrg)r��queued�authenticators�context�_tag�_parts�_lastCmd)r\r�r@r@rDr_
szIMAP4Client.__init__cCs||j|����<dS)a�
        Register a new form of authentication

        When invoking the authenticate() method of IMAP4Client, the first
        matching authentication scheme found will be used.  The ordering is
        that in which the server lists support authentication schemes.

        @type auth: Implementor of C{IClientAuthentication}
        @param auth: The object to use to perform the client
        side of this authentication scheme.
        N)r�ZgetNamer")r\r�r@r@rD�registerAuthenticator
sz!IMAP4Client.registerAuthenticatorcCs�|jdkr|��|jt|�8_|jdkr<|j�|�nvd}|jdkrh|d|j�||jd�}}|j�|�|j}d|_d|_|�dd�|j�|�	��|�
|�d��dS)NrrR�
)rr�_pendingSizer��_pendingBufferr�r�r�rr�readr�lstrip)r\r�r�r%r@r@rDr
s


zIMAP4Client.rawDataReceivedcCsD|�|�|_||_|jdkr(|dg|_n|j�|dg�|��dS)Nr�)�messageFiler�r�r�rwr>)r\r%�octetsr@r@rD�_setupForLiteral7
s
zIMAP4Client._setupForLiteralcCs|jdkr|�|j�dSr�)rr�rhr@r@rDr�A
s
zIMAP4Client.connectionMadecCs�|jdkr|�d�|jdk	r@|j}d|_|D]}|j�|�q.|jdk	r�|j}d|_|��D]"}|dk	r^|jdk	r^|j�|�q^dS)z,
        We are no longer connected
        rN)rr�r�r�errbackr��values)r\rr�r&r�r@r@rDrF
s



zIMAP4Client.connectionLostcCs�|jdkr|��|�d�}|dkr�||dd�}|�d�r�zt|dd��}Wntk
rnt|��YnX|jdkr�|�dd�\|_	}n|}|�
||�dS|jdkr�|�|�n8|j�|�|j	d�
|j�}}d|_	|_|�||�dS)aF
        Attempt to parse a single line from the server.

        @type line: L{bytes}
        @param line: The line from the server, without the line delimiter.

        @raise IllegalServerResponse: If the line or some part of the line
            does not represent an allowed message from the server at this time.
        rrGryr>NrHrR)rr�rfindr�rKr`r=r�r r�r��_regularDispatchrrr�r#)r\r�ZlastPartr��partsr�r%r@r@rDrY
s*




zIMAP4Client.lineReceivedcCsp|jr.|jjdk	r.|jjd}|j_|�t�|jrb|jD]&}|jdk	r:|j|}|_|�t�q:|j��dSrg)r�rr��
TIMEOUT_ERRORr�r�r)r\r�r&r@r@rDr
�
s


zIMAP4Client.timeoutConnectioncCs:|�dd�}t|�dkr"|�d�|\}}|�||�dS)Nr>r�rR)r r�rrr#)r\r�r�r�r%r@r@rDr��
s

zIMAP4Client._regularDispatchcCs||jkrt��St�SdS)a8
        Create a file to which an incoming message may be written.

        @type octets: L{int}
        @param octets: The number of octets which will be written to the file

        @rtype: Any object which implements C{write(string)} and
        C{seek(int, int)}
        @return: A file-like object
        N)r�r�r�r)r\r�r@r@rDr��
s
zIMAP4Client.messageFilecCs"d|j�d�}|jd7_|S)Nz%0.4X�asciir>)�tagIDr�r�r@r@rD�makeTag�
szIMAP4Client.makeTagcCs�|jdkr|j}nt|d|j��d�}|r\z|||�Wq|t��|j��Yq|Xn t�d|j||f�|j��dS)NZ	response_zCannot dispatch: %s, %r, %r)r�response_UNAUTHrr"r
r
r�r)r\r�r%rr@r@rDr#�
s
zIMAP4Client.dispatchCommandcCs�|jdkr�|�dd�\}}|��dkr.d|_n.|��dkrBd|_n|j��t|d|��|�d�|�d�}}|d	kr�|d	kr�|�|�t	||d|��gdf��q�|�d�n|�
||�dS)
Nr>r�r�sPREAUTHr�r�r�r�ry)rr r"r�rr=rV�serverGreeting�_IMAP4Client__cbCapabilitiesr��_defaultHandler)r\r�r%r�r_rr@r@rDr��
s"

��zIMAP4Client.response_UNAUTHcCs|�||�dSrg)r�)r\r�r%r@r@rD�
response_AUTH�
szIMAP4Client.response_AUTHcCs�|dks|dkrV|js(|�t|�g�q�|j|j}|dkrH|�|�q�|j�|�n�z|j|}Wn.tk
r�|j�	�t
|d|��YnPX|�dd�\}}|dkr�|�||j�n|j
�t|��|j|=d|_|��dS)Nr|rzr�r>r�)�waiting�
_extraInfor�r�r�r�rr�KeyErrorr�rr=r r�rr�r.�_flushQueue)r\r�r%r&r�r�r@r@rDr��
s&
zIMAP4Client._defaultHandlercCs>|jr:|j�d�}|��}||j|<|�|�|��||_dSr�)r�rr�r�rr�r��r\r&�tr@r@rDr��
s
zIMAP4Client._flushQueuec
Cs8i}d}}|D]�}t|�}|dkr>|ddgkr>|�d�q|dkr`|ddgkr`|�d�q|dkr�|ddkr�t|d�}q|dkr�|dd	kr�t|d�}q|d
kr�|ddkr�t|d�}|�|d�\}}	|�|g��|�dd
��qt�d|f�q|�r|�	|�|dk	�s(|dk	�r4|�
||�dS)Nr>rr�Fr�Tr�r�r�rr��FLAGSr@z"Unhandled unsolicited response: %s)r�r�rK�_parseFetchPairs�
setdefaultrwr6r
rqr�r�)
r\r�rbr�r�Zresponse�elementsr�r�r.r@r@rDr�s*
zIMAP4Client._extraInfocCsVt��|_|jr"|j�|�|jS|��}||j|<|�|�|��||_||_	|jSrg)
rr<r�r�rrr�r�rr�r�rr@r@rD�sendCommand s

zIMAP4Client.sendCommandcCsD|r|jdk	rt�|j�Sd}d}|�t||d��}|�|j�|S)av
        Request the capabilities available on this server.

        This command is allowed in any state of connection.

        @type useCache: C{bool}
        @param useCache: Specify whether to use the capability-cache or to
        re-retrieve the capabilities from the server.  Server capabilities
        should never change, so for normal use, this flag should never be
        false.

        @rtype: L{Deferred}
        @return: A deferred whose callback will be invoked with a
        dictionary mapping capability types to lists of supported
        mechanisms, or to None if a support list is not applicable.
        Nr�)r��r�)�	_capCacher�succeedrr�r0r�)r\ZuseCacher&r�r�r@r@rD�getCapabilities-szIMAP4Client.getCapabilitiesc
Cs�|\}}i}|D]X}|dd�D]F}|�dd�}t|�dkrL|dd}}	n|\}}	|�|g��|	�q q|D]}||dgkrnd||<qn||_|S)Nr>r}r)r r�rrrr)
r\r5r��tagliner�r%r�r��categoryrbr@r@rDZ__cbCapabilitiesGs
zIMAP4Client.__cbCapabilitiescCs"|�tddd��}|�|j�|S)a*
        Inform the server that we are done with the connection.

        This command is allowed in any state of connection.

        @rtype: L{Deferred}
        @return: A deferred whose callback will be invoked with None
        when the proper server acknowledgement has been received.
        sLOGOUT)sBYEr)rr�r0�_IMAP4Client__cbLogout�r\r�r@r@rDr�]s
zIMAP4Client.logoutcCs|\}}|j��dSrg)r�r�r\r5r�rr@r@rDZ
__cbLogoutls
zIMAP4Client.__cbLogoutcCs|�td��}|�|j�|S)a
        Perform no operation.

        This command is allowed in any state of connection.

        @rtype: L{Deferred}
        @return: A deferred whose callback will be invoked with a list
        of untagged status updates the server responds with.
        sNOOP)rr�r0�_IMAP4Client__cbNooprr@r@rD�noopss
zIMAP4Client.noopcCs|\}}|Srgr@rr@r@rDZ__cbNoop�szIMAP4Client.__cbNoopcs��jrtd��|dkr���}|dkr4t�td��Sd�jkrLt�td��St��j	d�}|dkrpt�td��S��
td��}|��j
|�|��fdd��|S)	a:
        Initiates a 'STARTTLS' request and negotiates the TLS / SSL
        Handshake.

        @param contextFactory: The TLS / SSL Context Factory to
        leverage.  If the contextFactory is None the IMAP4Client will
        either use the current TLS / SSL Context Factory or attempt to
        create a new one.

        @type contextFactory: C{ssl.ClientContextFactory}

        @return: A Deferred which fires when the transport has been
        secured according to the given contextFactory, or which fails
        if the transport cannot be secured.
        z5Client and Server are currently communicating via TLSNzEIMAP4Client requires a TLS context to initiate the STARTTLS handshaker�z:Server does not support secure communication via TLS / SSLzAIMAP4Client transport does not implement interfaces.ITLSTransportcs���Srg�r
r|rhr@rDrQ�rRz&IMAP4Client.startTLS.<locals>.<lambda>)r�r��_getContextFactoryr�failr.rrr�r�rr�r0�_startedTLS)r\r�Ztlsr�r@rhrDr��s(�
��zIMAP4Client.startTLScCs2|jdkr|��}nt�|j�}|�|j|�|S)a2
        Attempt to enter the authenticated state with the server

        This command is allowed in the Non-Authenticated state.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked if the authentication
        succeeds and whose errback will be invoked otherwise.
        N)rr
rr	r0�_IMAP4Client__cbAuthenticate)r\�secretr�r@r@rDr��s



zIMAP4Client.authenticatecs�|�dd���D]4}|���jkrtd|d�j||�}��|�Sq�jrbt�t	��j�
���S��fdd�}���}|�|�|�
�fdd��|�
�j|�|SdS)Nr�r@�AUTHENTICATEcs |�t�t�t��j����Srg)Ztrapr.rrr8r�r�)r
��authsr\r@rD�
ebStartTLS�s

�z0IMAP4Client.__cbAuthenticate.<locals>.ebStartTLScs���Srgrr|rhr@rDrQ�rRz.IMAP4Client.__cbAuthenticate.<locals>.<lambda>)r6r"r�r��_IMAP4Client__cbContinueAuthrr�rrr8r�r�r	r0�_IMAP4Client__cbAuthTLS)r\r�r�schemer&rr�r@rrDZ__cbAuthenticate�s(��
zIMAP4Client.__cbAuthenticatecCsfzt|d�}Wn(tjk
r8|�d�t|��Yn*X|j|}|�||�}|�t|����dS)N�
r|)	r�r�r�rr=r�ZchallengeResponser�rJ)r\r%rrr�r�r@r@rDZ__cbContinueAuth�s

zIMAP4Client.__cbContinueAuthcCsZ|�dd�}|D]4}|��|jkrtd|d|j||�}|�|�Sqt||j����dS)Nr�r@r)r6r"r�r�rrr8r�)r\r�rrrr&r@r@rDZ__cbAuthTLS�s�zIMAP4Client.__cbAuthTLScCst|j�}|�|j||�|S)a�
        Authenticate with the server using a username and password

        This command is allowed in the Non-Authenticated state.  If the
        server supports the STARTTLS capability and our transport supports
        TLS, TLS is negotiated before the login command is issued.

        A more secure way to log in is to use C{startTLS} or
        C{authenticate} or both.

        @type username: L{str}
        @param username: The username to log in with

        @type password: L{str}
        @param password: The password to log in with

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked if login is successful
        and whose errback is invoked otherwise.
        )r	r
r0�_IMAP4Client__cbLoginCaps)r\�username�passwordr�r@r@rDr��s
zIMAP4Client.logincCsdS)z�
        Called when the server has sent us a greeting.

        @type caps: C{dict}
        @param caps: Capabilities the server advertised in its greeting.
        Nr@)r\r�r@r@rDr�szIMAP4Client.serverGreetingcCsR|jdk	r|jSzddlm}Wntk
r6YdSX|��}|jj|_|SdS)Nr)�ssl)r�r"r#�ImportErrorZClientContextFactoryZSSLZTLSv1_METHOD�method)r\r#r�r@r@rDrs

zIMAP4Client._getContextFactoryc	Cs�d|k}t�|jd�dk	}t�|jd�dk}|jsb|rb|rb|rb|��}|j|j|j||fd�|S|rpt	�
d�d�t|�t|�f�}|�
td|��SdS)Nr�)r�z5Server has no TLS support. logging in over cleartext!r�r�)rr�r�r�r�r�r��_IMAP4Client__cbLoginTLS�_IMAP4Client__ebLoginTLSr
rqr�r�rr�)	r\r�r!r"ZtryTLSZtlsableTransportZnontlsTransportr�r�r@r@rDZ
__cbLoginCaps&s�
zIMAP4Client.__cbLoginCapscCs|j�|�d|_d|_|S)NT)r�r�rr�)r\r5r�r@r@rDr@szIMAP4Client._startedTLScCs&d�t|�t|�f�}|�td|��S)Nr�r�)r�r�rr�)r\r5r!r"r�r@r@rDZ__cbLoginTLSGszIMAP4Client.__cbLoginTLScCst�|�|Srg)r
r
r�r@r@rDZ__ebLoginTLSLs
zIMAP4Client.__ebLoginTLScCs*d}d}|�t||d��}|�|j�|S)a�
        Retrieve information about the namespaces available to this account

        This command is allowed in the Authenticated and Selected states.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with namespace
        information.  An example of this information is::

            [[['', '/']], [], []]

        which indicates a single personal namespace called '' with '/'
        as its hierarchical delimiter, and no shared or user namespaces.
        r�)r�r)rr�r0�_IMAP4Client__cbNamespace�r\r&r�r�r@r@rD�	namespaceQs
zIMAP4Client.namespacecsr|\}}trdd��ndd��|D]:}t|�dkr"|ddkr"�fdd�|d	d�D�Sq"t�d
�ggggS)NcSsdd�|D�S)NcSsg|]}|�d��qS)r�)�decode)rF�elementr@r@rDrJvszSIMAP4Client.__cbNamespace.<locals>._prepareNamespaceOrDelimiter.<locals>.<listcomp>r@)Z
namespaceListr@r@rD�_prepareNamespaceOrDelimiterus�z?IMAP4Client.__cbNamespace.<locals>._prepareNamespaceOrDelimitercSs|Srgr@)r,r@r@rDr-zsrrr�cs*g|]"}|dkrgn�fdd�|D��qS)Ncsg|]}�|��qSr@r@)rFrb�r-r@rDrJ�s�z8IMAP4Client.__cbNamespace.<locals>.<listcomp>.<listcomp>r@)rFZ
pairOrNoner.r@rDrJs��
�z-IMAP4Client.__cbNamespace.<locals>.<listcomp>r>z*No NAMESPACE response to NAMESPACE command)rr�r
r
)r\r5r�rkr�r@r.rDZ
__cbNamespacegs


�	
zIMAP4Client.__cbNamespacecCs6d}t|�}d}|�t|||d��}|�|jd�|S)a�
        Select a mailbox

        This command is allowed in the Authenticated and Selected states.

        @type mailbox: L{str}
        @param mailbox: The name of the mailbox to select

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with mailbox
        information if the select is successful and whose errback is
        invoked otherwise.  Mailbox information consists of a dictionary
        with the following L{str} keys and values::

                FLAGS: A list of strings containing the flags settable on
                        messages in this mailbox.

                EXISTS: An integer indicating the number of messages in this
                        mailbox.

                RECENT: An integer indicating the number of "recent"
                        messages in this mailbox.

                UNSEEN: The message sequence number (an integer) of the
                        first unseen message in the mailbox.

                PERMANENTFLAGS: A list of strings containing the flags that
                        can be permanently set on messages in this mailbox.

                UIDVALIDITY: An integer uniquely identifying this mailbox.
        r�)r�EXISTSr�r��PERMANENTFLAGS�UIDVALIDITYrr>��_prepareMailboxNamerr�r0�_IMAP4Client__cbSelect�r\r�r&r�r�r�r@r@rDr��s zIMAP4Client.selectcCs6d}t|�}d}|�t|||d��}|�|jd�|S)a�
        Select a mailbox in read-only mode

        This command is allowed in the Authenticated and Selected states.

        @type mailbox: L{str}
        @param mailbox: The name of the mailbox to examine

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with mailbox
        information if the examine is successful and whose errback
        is invoked otherwise.  Mailbox information consists of a dictionary
        with the following keys and values::

            'FLAGS': A list of strings containing the flags settable on
                        messages in this mailbox.

            'EXISTS': An integer indicating the number of messages in this
                        mailbox.

            'RECENT': An integer indicating the number of "recent"
                        messages in this mailbox.

            'UNSEEN': An integer indicating the number of messages not
                        flagged \Seen in this mailbox.

            'PERMANENTFLAGS': A list of strings containing the flags that
                        can be permanently set on messages in this mailbox.

            'UIDVALIDITY': An integer uniquely identifying this mailbox.
        r�)r�r�r�r�r�r�rrr2r5r@r@rD�examine�s zIMAP4Client.examinecCs,z
t|�WStk
r&t|��YnXdS)z�
        Parse C{value} as an integer and return the result or raise
        L{IllegalServerResponse} with C{phrase} as an argument if C{value}
        cannot be parsed as an integer.
        N)rKr`r=)r\rb�phraser@r@rD�_intOrRaise�s
zIMAP4Client._intOrRaisec	Cs�|\}}d|i}|�t|��|D�]�}t|�dk�r&|d��dk�r&|d}t|t�rd|d}n|}|��}|dkr�d|d<n�|dkr�d|d<n�|d	kr�|�|d|�|d
<nr|dkr�|�|d|�|d<nT|d
kr�|�|d|�|d<n6|dk�rtdd�|dD��|d<nt�	d|f�q"t|�dk�r�|d��dk�rbtdd�|dD��|d<n�t|dt
��r�|d��dk�r�|�|d|�|d<n8|d��dk�r�|�|d|�|d<nt�	d|f�nt�	d|f�q"t�	d|f�q"|S)zy
        Handle lines received in response to a SELECT or EXAMINE command.

        See RFC 3501, section 6.3.1.
        z
READ-WRITErr�r>r�Fr�Tr�r1r�r�r��UIDNEXTr�css|]}t|�VqdSrgr�r�r@r@rDr�
sz)IMAP4Client.__cbSelect.<locals>.<genexpr>r0z!Unhandled SELECT response (2): %sr�r�css|]}t|�VqdSrgr�r�r@r@rDr�
srr�r/r�r�z!Unhandled SELECT response (0): %sz!Unhandled SELECT response (1): %sz!Unhandled SELECT response (4): %s)rrr�r�r"rWrXr8�tupler
r
�bytes)	r\r5r�r�rZdatumr �contentrmr@r@rDZ
__cbSelect�sN
 




��zIMAP4Client.__cbSelectcCs|�tdt|���S)a|
        Create a new mailbox on the server

        This command is allowed in the Authenticated and Selected states.

        @type name: L{str}
        @param name: The name of the mailbox to create.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked if the mailbox creation
        is successful and whose errback is invoked otherwise.
        sCREATE�rr�r3�r\r�r@r@rDr�%
s
zIMAP4Client.createcCs|�tdt|���S)ak
        Delete a mailbox

        This command is allowed in the Authenticated and Selected states.

        @type name: L{str}
        @param name: The name of the mailbox to delete.

        @rtype: L{Deferred}
        @return: A deferred whose calblack is invoked if the mailbox is
        deleted successfully and whose errback is invoked otherwise.
        sDELETEr=r>r@r@rDr�5
s
zIMAP4Client.deletecCs*t|�}t|�}|�tdd�||f���S)a�
        Rename a mailbox

        This command is allowed in the Authenticated and Selected states.

        @type oldname: L{str}
        @param oldname: The current name of the mailbox to rename.

        @type newname: L{str}
        @param newname: The new name to give the mailbox.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked if the rename is
        successful and whose errback is invoked otherwise.
        sRENAMEr�)r3rr�r�)r\r�r�r@r@rDr�E
szIMAP4Client.renamecCs|�tdt|���S)a�
        Add a mailbox to the subscription list

        This command is allowed in the Authenticated and Selected states.

        @type name: L{str}
        @param name: The mailbox to mark as 'active' or 'subscribed'

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked if the subscription
        is successful and whose errback is invoked otherwise.
        s	SUBSCRIBEr=r>r@r@rDr�Z
s
zIMAP4Client.subscribecCs|�tdt|���S)a{
        Remove a mailbox from the subscription list

        This command is allowed in the Authenticated and Selected states.

        @type name: L{str}
        @param name: The mailbox to unsubscribe

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked if the unsubscription
        is successful and whose errback is invoked otherwise.
        sUNSUBSCRIBEr=r>r@r@rDr�j
s
zIMAP4Client.unsubscribecCs@d}d||f�d�}d}|�t|||d��}|�|jd�|S)ap
        List a subset of the available mailboxes

        This command is allowed in the Authenticated and Selected
        states.

        @type reference: L{str}
        @param reference: The context in which to interpret
            C{wildcard}

        @type wildcard: L{str}
        @param wildcard: The pattern of mailbox names to match,
            optionally including either or both of the '*' and '%'
            wildcards.  '*' will match zero or more characters and
            cross hierarchical boundaries.  '%' will also match zero
            or more characters, but is limited to a single
            hierarchical level.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a list of
            L{tuple}s, the first element of which is a L{tuple} of
            mailbox flags, the second element of which is the
            hierarchy delimiter for this mailbox, and the third of
            which is the mailbox name; if the command is unsuccessful,
            the deferred's errback is invoked instead.  B{NB}: the
            delimiter and the mailbox name are L{str}s.
        r�z	"%s" "%s"r�)r�r)r�rr�r0�_IMAP4Client__cbList)r\�	reference�wildcardr&r�r�r�r@r@rDrXz
szIMAP4Client.listc	CsVd}|�d�}|�d�}d�d|d|dg�}d}|�t|||d��}|�|jd�|S)	aa
        List a subset of the subscribed available mailboxes

        This command is allowed in the Authenticated and Selected states.

        The parameters and returned object are the same as for the L{list}
        method, with one slight difference: Only mailboxes which have been
        subscribed can be included in the resulting list.
        r�r�r�rRrFs" ")r�r)r�r�rr�r0r?)	r\r@rAr&ZencodedReferenceZencodedWildcardr�r�r�r@r@rD�lsub�
s


�zIMAP4Client.lsubcCs�|\}}g}|D]t}t|�dkr|d|krtdd�|dD��|d<trn|d�d�|d<|d�d�|d<|�t|dd���q|S)	Nrrcss|]}t|�VqdSrgr�r�r@r@rDr��
sz'IMAP4Client.__cbList.<locals>.<genexpr>r>r�r�r)r�r:rr+rr)r\r5r�r�rkr~r�r@r@rDZ__cbList�
szIMAP4Client.__cbListcCsi|]}||�d��qS)r��r��rFr�r@r@rD�
<dictcomp>�
szIMAP4Client.<dictcomp>�r�r�r9r1r�c	s�d}t|�}zd��fdd�|D��}Wn0tk
rXtd�t|�t�j����YnXd�|d|dg�}d	}��t|||d
��}|�	�j
�|S)a9
        Retrieve the status of the given mailbox

        This command is allowed in the Authenticated and Selected states.

        @type mailbox: L{str}
        @param mailbox: The name of the mailbox to query

        @type *names: L{bytes}
        @param *names: The status names to query.  These may be any number of:
            C{'MESSAGES'}, C{'RECENT'}, C{'UIDNEXT'}, C{'UIDVALIDITY'}, and
            C{'UNSEEN'}.

        @rtype: L{Deferred}
        @return: A deferred which fires with the status information if the
            command is successful and whose errback is invoked otherwise.  The
            status information is in the form of a C{dict}.  Each element of
            C{names} is a key in the dictionary.  The value for each key is the
            corresponding response from the server.
        r�r�c3s|]}�j|VqdSrg)�_statusNamesrDrhr@rDr��
sz%IMAP4Client.status.<locals>.<genexpr>zUnknown names: {!r}rRr�rT)r�r)r3r�r�r`r�r�rGrr�r0�_IMAP4Client__cbStatus)r\r�r�r&ZpreparedMailboxr�r�r�r@rhrDr��
s"��zIMAP4Client.statusc
s|\}}i}|D]v}|ddkr|d��fdd�tdt��d�D���D]:\}}z||t|�<WqJtk
r�tt����YqJXqJq|��D]r}|j�|�}|r�z|||�||<Wq�t	k
�r}	z(td|d||dt
|	���W5d}	~	XYq�Xq�|S)	Nrr�r�csg|]}�||d��qS)r�r@r�r�r@rDrJ
sz*IMAP4Client.__cbStatus.<locals>.<listcomp>�(r�z): )rr�r�UnicodeDecodeErrorr=r3r��STATUS_TRANSFORMATIONSr6rr�)
r\r5r�rkr�r�r�r�rrr@rIrDr�s&8zIMAP4Client.__cbStatusr@c	
Cs�|�dd�|��}|�dd�|r6tdt|��}nd}dd�|D�}d�t|�dd�|�d	|d
t|�dg�}|�td|d
|j	|��}|S)a�
        Add the given message to the given mailbox.

        This command is allowed in the Authenticated and Selected states.

        @type mailbox: L{str}
        @param mailbox: The mailbox to which to add this message.

        @type message: Any file-like object opened in B{binary mode}.
        @param message: The message to add, in RFC822 format.  Newlines
        in this file should be \r\n-style.

        @type flags: Any iterable of L{str}
        @param flags: The flags to associated with this message.

        @type date: L{str}
        @param date: The date to associate with this message.  This should
        be of the format DD-MM-YYYY HH:MM:SS +/-HHMM.  For example, in
        Eastern Standard Time, on July 1st 2004 at half past 1 PM,
        "01-07-2004 13:30:00 -0500".

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked when this command
        succeeds or whose errback is invoked if it fails.
        rr�z "%s"rRcSsg|]}t|��qSr@r�r�r@r@rDrJ<sz&IMAP4Client.append.<locals>.<listcomp>r�r�rTs {rHsAPPENDr@)
r��tellrrr�r3rrr��_IMAP4Client__cbContinueAppend)	r\r�rlrbrgr�r�r&r�r@r@rDrrs&�zIMAP4Client.appendcCs t��}|�||jd��|j�Srg)rZ
FileSenderZbeginFileTransferr�r0�_IMAP4Client__cbFinishAppend)r\r�rlr�r@r@rDZ__cbContinueAppendIs�zIMAP4Client.__cbContinueAppendcCs|�d�dS�NrRr{)r\Zfoor@r@rDZ__cbFinishAppendOszIMAP4Client.__cbFinishAppendcCs|�td��S)a
        Tell the server to perform a checkpoint

        This command is allowed in the Selected state.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked when this command
        succeeds or whose errback is invoked if it fails.
        sCHECK�rr�rhr@r@rDr7Ss
zIMAP4Client.checkcCs|�td��S)a�
        Return the connection to the Authenticated state.

        This command is allowed in the Selected state.

        Issuing this command will also remove all messages flagged \Deleted
        from the selected mailbox if it is opened in read-write mode,
        otherwise it indicates success by no messages are removed.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked when the command
        completes successfully or whose errback is invoked if it fails.
        sCLOSErQrhr@r@rDr`szIMAP4Client.closecCs*d}d}|�t||d��}|�|j�|S)a�
        Return the connection to the Authenticate state.

        This command is allowed in the Selected state.

        Issuing this command will perform the same actions as issuing the
        close command, but will also generate an 'expunge' response for
        every message deleted.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a list of the
        'expunge' responses when this command is successful or whose errback
        is invoked otherwise.
        r�)r�r)rr�r0�_IMAP4Client__cbExpunger)r@r@rDrqs
zIMAP4Client.expungecCsH|\}}g}|D]2}t|�dkr|ddkr|�|�|d|��q|S)Nr�r>r�r)r�rrr8)r\r5r�rkrr�r@r@rDr
�szIMAP4Client.__cbExpungecOsVtrdd�|D�}|�d�r"d}nd}d�|�}|�t|||fd��}|�|j�|S)a�
        Search messages in the currently selected mailbox

        This command is allowed in the Selected state.

        Any non-zero number of queries are accepted by this method, as returned
        by the C{Query}, C{Or}, and C{Not} functions.

        @param uid: if true, the server is asked to return message UIDs instead
            of message sequence numbers.  (This is a keyword-only argument.)
        @type uid: L{bool}

        @rtype: L{Deferred}
        @return: A deferred whose callback will be invoked with a list of all
            the message sequence numbers return by the search, or whose errback
            will be invoked if there is an error.
        cSsg|]}|�d��qS)r�rC)rFrYr@r@rDrJ�sz&IMAP4Client.search.<locals>.<listcomp>r+s
UID SEARCHr�r�r)rr6r�rr�r0�_IMAP4Client__cbSearch)r\Zqueries�kwargr&r�r�r@r@rDra�s

zIMAP4Client.searchcsT|\}}g}|D]>�t��dkr�ddkr|���fdd��dd�D��q|S)Nrr�csg|]}��|���qSr@)r8�rFr��r�r\r@rDrJ�sz*IMAP4Client.__cbSearch.<locals>.<listcomp>r>)r�rw)r\r5r�r^rr@rVrDr�s$zIMAP4Client.__cbSearchcCs|j||dd�S)aV
        Retrieve the unique identifier for one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message sequence numbers to unique message identifiers, or whose
        errback is invoked if there is an error.
        r>)�useUIDr+��_fetch�r\rzr+r@r@rD�fetchUID�szIMAP4Client.fetchUIDcCs|j||dd�S)aH
        Retrieve the flags for one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: The messages for which to retrieve flags.

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to lists of flags, or whose errback is invoked if
        there is an error.
        r>)rWrbrXrZr@r@rD�
fetchFlags�szIMAP4Client.fetchFlagscCs|j||dd�S)a�
        Retrieve the internal date associated with one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: The messages for which to retrieve the internal date.

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to date strings, or whose errback is invoked
        if there is an error.  Date strings take the format of
        "day-month-year time timezone".
        r>)rW�internaldaterXrZr@r@rD�fetchInternalDate�szIMAP4Client.fetchInternalDatecCs|j||dd�S)a�
        Retrieve the envelope data for one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: The messages for which to retrieve envelope
            data.

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of
            message numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict
            mapping message numbers to envelope data, or whose errback
            is invoked if there is an error.  Envelope data consists
            of a sequence of the date, subject, from, sender,
            reply-to, to, cc, bcc, in-reply-to, and message-id header
            fields.  The date, subject, in-reply-to, and message-id
            fields are L{str}, while the from, sender, reply-to, to,
            cc, and bcc fields contain address data as L{str}s.
            Address data consists of a sequence of name, source route,
            mailbox name, and hostname.  Fields which are not present
            for a particular address may be L{None}.
        r>)rW�enveloperXrZr@r@rD�
fetchEnvelope�szIMAP4Client.fetchEnvelopecCs|j||dd�S)a�
        Retrieve the structure of the body of one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: The messages for which to retrieve body structure
        data.

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to body structure data, or whose errback is invoked
        if there is an error.  Body structure data describes the MIME-IMB
        format of a message and consists of a sequence of mime type, mime
        subtype, parameters, content id, description, encoding, and size.
        The fields following the size field are variable: if the mime
        type/subtype is message/rfc822, the contained message's envelope
        information, body structure data, and number of lines of text; if
        the mime type is text, the number of lines of text.  Extension fields
        may also be included; if present, they are: the MD5 hash of the body,
        body disposition, body language.
        r>)rW�
bodystructurerXrZr@r@rD�fetchBodyStructureszIMAP4Client.fetchBodyStructurecCs|j||dd�S)a�
        Retrieve the simplified body structure of one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: C{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to body data, or whose errback is invoked
        if there is an error.  The simplified body structure is the same
        as the body structure, except that extension fields will never be
        present.
        r>)rWrCrXrZr@r@rD�fetchSimplifiedBody6szIMAP4Client.fetchSimplifiedBodycCs|j||dd�S)a)
        Retrieve one or more entire messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: C{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}

        @return: A L{Deferred} which will fire with a C{dict} mapping message
            sequence numbers to C{dict}s giving message data for the
            corresponding message.  If C{uid} is true, the inner dictionaries
            have a C{'UID'} key mapped to a L{str} giving the UID for the
            message.  The text of the message is a L{str} associated with the
            C{'RFC822'} key in each dictionary.
        r>)rW�rfc822rXrZr@r@rD�fetchMessageMszIMAP4Client.fetchMessagecCs|j||dd�S)a<
        Retrieve headers of one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to dicts of message headers, or whose errback is
        invoked if there is an error.
        r>)rW�rfc822headerrXrZr@r@rD�fetchHeadersfszIMAP4Client.fetchHeaderscCs|j||dd�S)aL
        Retrieve body text of one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to file-like objects containing body text, or whose
        errback is invoked if there is an error.
        r>)rW�
rfc822textrXrZr@r@rD�	fetchBody{szIMAP4Client.fetchBodycCs|j||dd�S)a6
        Retrieve the size, in octets, of one or more messages

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to sizes, or whose errback is invoked if there is
        an error.
        r>)rW�
rfc822sizerXrZr@r@rD�	fetchSize�szIMAP4Client.fetchSizec	Cs|j||dddddd�S)aV
        Retrieve several different fields of one or more messages

        This command is allowed in the Selected state.  This is equivalent
        to issuing all of the C{fetchFlags}, C{fetchInternalDate},
        C{fetchSize}, C{fetchEnvelope}, and C{fetchSimplifiedBody}
        functions.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to dict of the retrieved data values, or whose
        errback is invoked if there is an error.  They dictionary keys
        are "flags", "date", "size", "envelope", and "body".
        r>)rWrbr]rjr_rCrXrZr@r@rD�	fetchFull�s�zIMAP4Client.fetchFullcCs|j||ddddd�S)a.
        Retrieve several different fields of one or more messages

        This command is allowed in the Selected state.  This is equivalent
        to issuing all of the C{fetchFlags}, C{fetchInternalDate},
        C{fetchSize}, and C{fetchEnvelope} functions.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to dict of the retrieved data values, or whose
        errback is invoked if there is an error.  They dictionary keys
        are "flags", "date", "size", and "envelope".
        r>)rWrbr]rjr_rXrZr@r@rD�fetchAll�s�zIMAP4Client.fetchAllcCs|j||dddd�S)a
        Retrieve several different fields of one or more messages

        This command is allowed in the Selected state.  This is equivalent
        to issuing all of the C{fetchFlags}, C{fetchInternalDate}, and
        C{fetchSize} functions.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a dict mapping
        message numbers to dict of the retrieved data values, or whose
        errback is invoked if there is an error.  They dictionary keys are
        "flags", "date", and "size".
        r>)rWrbr]rjrXrZr@r@rD�	fetchFast�s�zIMAP4Client.fetchFastc
s2tr�fdd��ndd��i}g}t|�}zt|�}Wntk
rPY�q*YnXzt|�}Wntk
r|td|��YnX|dkr�d}n>t|t�s�d}n.t|�dkr�d}n|r�t|dt�r�d}nd	}t|�}|�	|�|�rt|�dk�rd
d�|D�}|�	|�|t
|�f}n<t|d�}dd�|d
D�}	|�	||	g�||t
|	�ff}zt|�}Wn tk
�r~td|��YnX|�d��r|�d��rzt
|d
d��Wntk
�r�YnLXt|�}|�	|�||f}zt|�}Wn tk
�rtd|��YnX�|�}|�	|�|||<q*||fS)a�
        Given the result of parsing a single I{FETCH} response, construct a
        L{dict} mapping response keys to response values.

        @param fetchResponseList: The result of parsing a I{FETCH} response
            with L{parseNestedParens} and extracting just the response data
            (that is, just the part that comes after C{"FETCH"}).  The form
            of this input (and therefore the output of this method) is very
            disagreeable.  A valuable improvement would be to enumerate the
            possible keys (representing them as structured objects of some
            sort) rather than using strings and tuples of tuples of strings
            and so forth.  This would allow the keys to be documented more
            easily and would allow for a much simpler application-facing API
            (one not based on looking up somewhat hard to predict keys in a
            dict).  Since C{fetchResponseList} notionally represents a
            flattened sequence of pairs (identifying keys followed by their
            associated values), collapsing such complex elements of this
            list as C{["BODY", ["HEADER.FIELDS", ["SUBJECT"]]]} into a
            single object would also greatly simplify the implementation of
            this method.

        @return: A C{dict} of the response data represented by C{pairs}.  Keys
            in this dictionary are things like C{"RFC822.TEXT"}, C{"FLAGS"}, or
            C{("BODY", ("HEADER.FIELDS", ("SUBJECT",)))}.  Values are entirely
            dependent on the key with which they are associated, but retain the
            same structured as produced by L{parseNestedParens}.
        cs4t|t�r|�d�St|t�r0�fdd�|D�SdS)Nr�csg|]}�|��qSr@r@)rFZsubthing��nativeStringResponser@rDrJs�zNIMAP4Client._parseFetchPairs.<locals>.nativeStringResponse.<locals>.<listcomp>)rWr;r+rX��thingror@rDrps



�z:IMAP4Client._parseFetchPairs.<locals>.nativeStringResponsecSs|Srgr@rqr@r@rDrp!ssNot enough arguments)�BODYs	BODY.PEEKFr�rTcSsg|]}t|��qSr@r��rFr�r@r@rDrJfsz0IMAP4Client._parseFetchPairs.<locals>.<listcomp>cSsg|]}t|��qSr@r�rtr@r@rDrJlsr>�<�>ry)rrwrr�r=rWrXr�rrrr:rer�rKr`)
r\ZfetchResponseListr�ZunstructuredZ
responsePartsrmrbZ
hasSectionZ	valueHeadZ	valueTailr@rorDr�s~&�



�


�


zIMAP4Client._parseFetchPairscCs�|\}}i}|D]Z}t|�dkr|ddkr|�|d|�}||krT|dg||<q||d�|d�qi}	i}
|��D]D\}}|�|d�\}
}|
�|gg�d�|�|	�|i��|
�q||
}i}t|	���D]�}|	|}t|���D]~}||kr�|dkr�|d||<t	t||d��D]8}||d|dk�r"||d||d�=�q\�q"|d=|s�|	|=q�q�|�r�|�
|�|�r�|	S|SdS)Nrr>r�rr�r)r�r8rwr�rr�updaterXr�rr�)r\r5ZrequestedPartsZ
structuredr�rk�infor�r)r~ZdecodedInfoZ	messageIdr�Z
structuredMapZunstructuredListZflagChangesr�rcr@r@rD�_cbFetch�sB


zIMAP4Client._cbFetchc	Cs�d}	|dkrd}
n$t|t�r&t|�}
nd�tt|��}
|dkrDd}n|
rRd|}n|}|r�|dkr�|dk	rzdd�|�}q�d}nd}|dkr�d}
nd	||f}
|r�d
p�d}|	||r�dp�d|
|||
f}tr�|�d
�}|�t||dd��}|�	|j
dd�|S)a^
        Retrieve a specific section of one or more messages

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
            numbers or of unique message IDs.

        @type headerType: L{str}
        @param headerType: If specified, must be one of HEADER, HEADER.FIELDS,
            HEADER.FIELDS.NOT, MIME, or TEXT, and will determine which part of
            the message is retrieved.  For HEADER.FIELDS and HEADER.FIELDS.NOT,
            C{headerArgs} must be a sequence of header names.  For MIME,
            C{headerNumber} must be specified.

        @type headerNumber: L{int} or L{int} sequence
        @param headerNumber: The nested rfc822 index specifying the entity to
            retrieve.  For example, C{1} retrieves the first entity of the
            message, and C{(2, 1, 3}) retrieves the 3rd entity inside the first
            entity inside the second entity of the message.

        @type headerArgs: A sequence of L{str}
        @param headerArgs: If C{headerType} is HEADER.FIELDS, these are the
            headers to retrieve.  If it is HEADER.FIELDS.NOT, these are the
            headers to exclude from retrieval.

        @type peek: C{bool}
        @param peek: If true, cause the server to not set the \Seen flag on
            this message as a result of this command.

        @type offset: L{int}
        @param offset: The number of octets at the beginning of the result to
            skip.

        @type length: L{int}
        @param length: The number of octets to retrieve.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a mapping of message
            numbers to retrieved data, or whose errback is invoked if there is
            an error.
        z%s BODY%s[%s%s%s]%sNr3�.)z
HEADER.FIELDSzHEADER.FIELDS.NOTz (%s)r�z ()z<%d.%d>�	UID FETCHr�z.PEEKr��r�rr@F)rWrKr�r�r�rr�rr�r0ry)r\rzr+Z
headerTypeZheaderNumberZ
headerArgs�peek�offset�length�fmtZnumberr�ZpayloadZextrarr&r�r@r@rD�
fetchSpecific�s4/



zIMAP4Client.fetchSpecificcKs�t|��d�}|rdpd}d|kr0|d=d|d<d|krF|d=d|d<d	|kr\|d	=d|d
<dd�|D�}|d
d�dd�|D��d}|�t||dd��}|�|jdd�|��D�d�|S)Nr�r{r�rhT�rfc822.textrj�rfc822.sizerf�
rfc822.headercSsg|]}t|��qSr@r�r�r@r@rDrJsz&IMAP4Client._fetch.<locals>.<listcomp>r�r�cSsg|]}|���qSr@�r"r�r@r@rDrJ srTr|rcSsg|]}|���qSr@r�)rFrr@r@rDrJ$s)r�r�r�rr�r0ryr�)r\rzrWZtermsrZencodedTermsr&r�r@r@rDrY
s(
��zIMAP4Client._fetchcCs|�|d|||�S)a
        Set the flags for one or more messages.

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type flags: Any iterable of L{str}
        @param flags: The flags to set

        @type silent: L{bool}
        @param silent: If true, cause the server to suppress its verbose
        response.

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a list of the
        server's responses (C{[]} if C{silent} is true) or whose
        errback is invoked if there is an error.
        r���_store�r\rzrbr�r+r@r@rD�setFlags(szIMAP4Client.setFlagscCs|�|d|||�S)a
        Add to the set flags for one or more messages.

        This command is allowed in the Selected state.

        @type messages: C{MessageSet} or L{str}
        @param messages: A message sequence set

        @type flags: Any iterable of L{str}
        @param flags: The flags to set

        @type silent: C{bool}
        @param silent: If true, cause the server to suppress its verbose
        response.

        @type uid: C{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a list of the
        server's responses (C{[]} if C{silent} is true) or whose
        errback is invoked if there is an error.
        s+FLAGSr�r�r@r@rD�addFlagsDszIMAP4Client.addFlagscCs|�|d|||�S)a
        Remove from the set flags for one or more messages.

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type flags: Any iterable of L{str}
        @param flags: The flags to set

        @type silent: L{bool}
        @param silent: If true, cause the server to suppress its verbose
        response.

        @type uid: L{bool}
        @param uid: Indicates whether the message sequence set is of message
        numbers or of unique message IDs.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a list of the
        server's responses (C{[]} if C{silent} is true) or whose
        errback is invoked if there is an error.
        s-FLAGSr�r�r@r@rD�removeFlags`szIMAP4Client.removeFlagscCs�t|��d�}dd�|D�}|r(|d}|r0dp2d}d�||dd�|�d	f�}|�t||d
d��}	d}
|srd
}
|	�|j|
d�|	S)Nr�cSsg|]}t|��qSr@r�r�r@r@rDrJ~sz&IMAP4Client._store.<locals>.<listcomp>s.SILENTs	UID STOREr�r�rSrTr|rr@)rT)r�r�r�rr�r0ry)r\rzr&r�rbr+r�r�r�r�Zexpectedr@r@rDr�|szIMAP4Client._storecCs>t|��d�}|rd}nd}d�|t|�g�}|�t||��S)a�
        Copy the specified messages to the specified mailbox.

        This command is allowed in the Selected state.

        @type messages: L{MessageSet} or L{str}
        @param messages: A message sequence set

        @type mailbox: L{str}
        @param mailbox: The mailbox to which to copy the messages

        @type uid: C{bool}
        @param uid: If true, the C{messages} refers to message UIDs, rather
        than message sequence numbers.

        @rtype: L{Deferred}
        @return: A deferred whose callback is invoked with a true value
        when the copy is successful, or whose errback is invoked if there
        is an error.
        r�sUID COPYr�r�)r�r�r�r3rr�)r\rzr�r+r&r�r@r@rDr��szIMAP4Client.copycCsdS�zOverride meNr@r�r@r@rDr��szIMAP4Client.modeChangedcCsdSr�r@)r\r�r@r@rDr��szIMAP4Client.flagsChangedcCsdSr�r@r�r@r@rDr��szIMAP4Client.newMessages)N)r>)N)r@N)r)r)r)r)r)r)r)r)r)r)r)r)r)rNNNNNN)r)r>r)r>r)r>r)ir�r�r�r�r�r�r�r�rr�rrr�r�ZSTATUS_CODESrKrLr�r_r�rr�r�rrr
r�r�r�r#r�r�r�r�r�rr
r�r�r
rrr�r�rrrr�r�rr rr&r'r*r(r�r6r8r4r�r�r�r�r�rXrBr?rGr�rHrrrNrOr7rrrRrarSr[r\r^r`rbrcrergrirkrlrmrnrryr�rYr�r�r�r�r�r�r�r�r@r@r@rDr��	s��

+	

*	
%+(:$�
'
/
	!	












+�
T



 r�c	CsRt�}|�d�}|D�]6}d|kr�|�dd�\}}z�|dkrBd}nt|�}|dkrXd}nt|�}||krtdkr�nnt|��|dk	r�|dks�|dk	r�|dkr�t|��|p�|}|p�|}|�||�Wntk
r�t|��YnXqz6|dkr�d}nt|�}|dk	�r|dk�rt|��Wntk
�r:t|��YqX|�|�pH|�q|S)a�
    Parse a message set search key into a C{MessageSet}.

    @type s: L{bytes}
    @param s: A string description of an id list, for example "1:3, 4:*"

    @type lastMessageId: L{int}
    @param lastMessageId: The last message sequence id or UID, depending on
        whether we are parsing the list in UID or sequence id context. The
        caller should pass in the correct value.

    @rtype: C{MessageSet}
    @return: A C{MessageSet} that contains the ids defined in the list
    �,�:r>r|Nr)rLr rKr9rZr`rw)r�r%rur�r�r}r~r@r@rDr[�sF

��r[)ZALLZANSWEREDZDELETEDZDRAFTZFLAGGEDZNEWZOLDr�ZSEENZ
UNANSWEREDZ	UNDELETEDZUNDRAFTZ	UNFLAGGEDr�)ZLARGERZSMALLER�UIDcKsFg}|��}|rt|�}|D]�}||}|��}|tkrH|rH|�|�q|dkrr|�|t|d�t|d�g�q|dks�|dkr�t�d|�}|�||g�q|t	kr�t
|t�r�d}nt
|t�r�d}nd}|�|||fg�qt
|t��r|�|d	|fg�q|�|d
|fg�qt
|�dk�r8dd�|�d
Sd�|�SdS)a
    Create a query string

    Among the accepted keywords are::

        all         : If set to a true value, search all messages in the
                      current mailbox

        answered    : If set to a true value, search messages flagged with
                      \Answered

        bcc         : A substring to search the BCC header field for

        before      : Search messages with an internal date before this
                      value.  The given date should be a string in the format
                      of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

        body        : A substring to search the body of the messages for

        cc          : A substring to search the CC header field for

        deleted     : If set to a true value, search messages flagged with
                      \Deleted

        draft       : If set to a true value, search messages flagged with
                      \Draft

        flagged     : If set to a true value, search messages flagged with
                      \Flagged

        from        : A substring to search the From header field for

        header      : A two-tuple of a header name and substring to search
                      for in that header

        keyword     : Search for messages with the given keyword set

        larger      : Search for messages larger than this number of octets

        messages    : Search only the given message sequence set.

        new         : If set to a true value, search messages flagged with
                      \Recent but not \Seen

        old         : If set to a true value, search messages not flagged with
                      \Recent

        on          : Search messages with an internal date which is on this
                      date.  The given date should be a string in the format
                      of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

        recent      : If set to a true value, search for messages flagged with
                      \Recent

        seen        : If set to a true value, search for messages flagged with
                      \Seen

        sentbefore  : Search for messages with an RFC822 'Date' header before
                      this date.  The given date should be a string in the format
                      of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

        senton      : Search for messages with an RFC822 'Date' header which is
                      on this date  The given date should be a string in the format
                      of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

        sentsince   : Search for messages with an RFC822 'Date' header which is
                      after this date.  The given date should be a string in the format
                      of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

        since       : Search for messages with an internal date that is after
                      this date..  The given date should be a string in the format
                      of 'DD-Mon-YYYY'.  For example, '03-Mar-2003'.

        smaller     : Search for messages smaller than this number of octets

        subject     : A substring to search the 'subject' header for

        text        : A substring to search the entire message for

        to          : A substring to search the 'to' header for

        uid         : Search only the messages in the given message set

        unanswered  : If set to a true value, search for messages not
                      flagged with \Answered

        undeleted   : If set to a true value, search for messages not
                      flagged with \Deleted

        undraft     : If set to a true value, search for messages not
                      flagged with \Draft

        unflagged   : If set to a true value, search for messages not
                      flagged with \Flagged

        unkeyword   : Search for messages without the given keyword set

        unseen      : If set to a true value, search for messages not
                      flagged with \Seen

    @type sorted: C{bool}
    @param sorted: If true, the output will be sorted, alphabetically.
    The standard does not require it, but it makes testing this function
    easier.  The default is zero, and this should be acceptable for any
    application.

    @rtype: L{str}
    @return: The formatted query string
    ZHEADERrr>ZKEYWORDZ	UNKEYWORDr3z"%s"z"%d"z%dz%srJr��)N)r��_sortedr"�_SIMPLE_BOOLrrrwr��
_nonAtomREr��
_NO_QUOTESrWrLrKr�r�)rnrTr&r�r�r�r�r@r@rD�Query�s6n"

r�cGsJt|�dkrt|��n0t|�dkr*d|Sd|dt|dd��fSdS)z0
    The disjunction of two or more queries
    r�z
(OR %s %s)rr>N)r�r:�Or)r�r@r@rDr��s

r�cCs
d|fS)zThe negation of a queryz(NOT %s)r@)rYr@r@rD�Not�sr�cCsF|�dd�}|dkr"|�dd�}n|�ddt�|��}t�|tj�S)Nr�z(?:.*?)�%z(?:(?:[^%s])*?))�replacer�r�r��I)rAr�r@r@rD�wildcardToRegexp�s
r�cCs�|��}g}g}d}}td|�}td|�}td|�}td|�}tt|��D]�\}	}
|
|kr�|	r�||	d|	�|kr�|��|�|�n"|s�d}nd}|�|�|��g}qL|s�|s�|
|tj�	d�kr�d}|�|
�qL|�r*|�s*|
tj�	d�k�r*|�|�}||k�r|�d	�n
|�|�g}d}qL|�s4|rL|�|
�qL|�rNt
|��|�r~|�|�}||k�rt|�d	�n
|�|�|S)
a�
    Split a string into whitespace delimited tokens

    Tokens that would otherwise be separated but are surrounded by "
    remain as a single token.  Any token that is not quoted and is
    equal to "NIL" is tokenized as L{None}.

    @type s: L{bytes}
    @param s: The string to be split

    @rtype: L{list} of L{bytes}
    @return: A list of the resulting tokens

    @raise MismatchedQuoting: Raised if an odd number of quotes are present
    F�"�\r3ZNILr>Tr�N)rJrrarrrrr��string�
whitespacer�r<)r�r5Zword�inQuoteZinWord�qu�escr�Znilrcr�wr@r@rD�splitQuoted�sV



���






r�cCszg}||d�}|dg}|dd�D]<}||�}||krX|�|||��|g}|}q&|�|�q&|�|||��|S�Nrr>)rwrr)ZsequenceZ	predicateZtransformersr5r�Ztmprr�r@r@rD�splitOn�s
r�cCs�g}d}dd�}dd�dd�d�}t|�D]T\}}t|t�rr|dk	rb|�t|||�||��d}|�t|��q*|dkr*|}q*|dk	r�|�t||d�||��|S)a{
    Turns a list of length-one strings and lists into a list of longer
    strings and lists.  For example,

    ['a', 'b', ['c', 'd']] is returned as ['ab', ['cd']]

    @type results: L{list} of L{bytes} and L{list}
    @param results: The list to be collapsed

    @rtype: L{list} of L{bytes} and L{list}
    @return: A new list which is the collapsed form of C{results}
    NcSs
t|t�Srg)rWr:�rr@r@rDrQrRz!collapseStrings.<locals>.<lambda>cSstd�|��SrP)r�r�r�r@r@rDrQ
rRcSsd�dd�|D��gS)NrRcSsg|]}|d�qS)rr@rr@r@rDrJsz5collapseStrings.<locals>.<lambda>.<locals>.<listcomp>)r�r�r@r@rDrQrR)rr>)rarWrXrwr�rr�collapseStrings)r~r�ZbegunZpredZtranrcrr@r@rDr��s"
�
r�c	Cs�|��}d}gg}�z�d}t|�}||k�r�|||d�}|r�|dkrn|d�|||d��|d7}q"n|dkr||}|d�|�|d7}q"|dkr�|d�|�|}|d7}q"|�r,|dk�r,|�d|�}|dkr�td	��t||d|��}|d�||d
|d
|�f�|d
|}q"|dk�s@|dk�rT|�g�|d7}q"|d
k�sh|dk�r�|d�|���|d7}q"|d�|�|d7}q"Wntk
�r�t|��YnXt|�dk�r�t|��t	|d�S)ak
    Parse an s-exp-like string into a more useful data structure.

    @type s: L{bytes}
    @param s: The s-exp-like string to parse

    @rtype: L{list} of L{bytes} and L{list}
    @return: A list containing the tokens present in the input.

    @raise MismatchedNesting: Raised if the number or placement
    of opening or closing parenthesis is invalid.
    rr>r`ryr�rFrGrHrIrrSr�rTr����)
rJr�rrrVr`rKr�
IndexErrorr;r�)	r�Z
handleLiteralr�ZcontentStackrcr�rr^ZliteralSizer@r@rDr�sR



$


r�cCs8td|�}td|�}||�|||��|||�|S)Nr�r�)rr�)r�r�r�r@r@rDr�Ys

r�cCsdtt|��d|S)NrG�}
)rr��r�r@r@rDr�`sr�c@seZdZdd�Zdd�ZdS)r�cCs
||_dSrg)rb)r\rbr@r@rDr_fszDontQuoteMe.__init__cCs
t|j�Srg)r�rbrhr@r@rDr�jszDontQuoteMe.__str__N)r�r�r�r_r�r@r@r@rDr�esr�s(){ %*"cCsB|dkrdSt|�D](}|dks(|dkr.dS|tkrdSqdS)NrRr>r��r)r�_ATOM_SPECIALS)r�rr@r@rD�_needsQuotepsr�cCs<t|t�r|Sz|�d�WSt��t|��YnXdS�Nr�)rWrr+r
r
r2�r�r@r@rDr�|s
r�cCs2t|t�s|�d�}|�d�}t|�r.t|�S|S)Nr�r�)rWrr+r�r�r�r�r@r@rDr3�s


r3cCs0td|�}td|�}||kp.||kp.t|�dkS)N�
�
i�)rr�)r�ZcrZlfr@r@rD�
_needsLiteral�s

r�c	Cs&g}|D�]}t|t�r"|�d�}|dkr:|�ddg�qt|ttf�r`|�dtt|��g�qt|t�r||�d|j	g�qt|t
�r�t|�r�|�ddtt
|��dtj|g�n|�dt|�g�qt|d�r�|��}|�ddtt
|��dtj|g�q|�ddt|�d	g�qd
�|dd��S)a�
    Turn a nested list structure into an s-exp-like string.

    Strings in C{items} will be sent as literals if they contain CR or LF,
    otherwise they will be quoted.  References to None in C{items} will be
    translated to the atom NIL.  Objects with a 'read' attribute will have
    it called on them with no arguments and the returned string will be
    inserted into the output as a literal.  Integers will be converted to
    strings and inserted into the output unquoted.  Instances of
    C{DontQuoteMe} will be converted to strings and inserted into the output
    unquoted.

    This function used to be much nicer, and only quote things that really
    needed to be quoted (and C{DontQuoteMe} did not exist), however, many
    broken IMAP4 clients were unable to deal with this level of sophistication,
    forcing the current behavior to be adopted for practical reasons.

    @type items: Any iterable

    @rtype: L{str}
    r�Nr�sNILrGrHr�rSrTrRr>)rWrr�rwrKrrr�r�rbr;r�rr�r�Z	delimiterr��hasattrr�r�r�)r��piecesrcr�r@r@rDr��s2




�
�r�c@s�eZdZdZdZdZdd�Zdd�Zddd�Zd	d
�Z	dd�Z
ddd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�ZdS) �MemoryAccountWithoutNamespacesNrcCs||_i|_g|_dSrg)r�r��
subscriptionsr>r@r@rDr_�sz'MemoryAccountWithoutNamespaces.__init__cCs|j}|jd7_|SrN)�top_id)r\r)r@r@rD�
allocateID�sz)MemoryAccountWithoutNamespaces.allocateIDcCsDt|���}||jkrt|��|dkr6|�||���}||j|<dSrN)r�r"r�r3�
_emptyMailboxr�)r\r�rr@r@rD�
addMailbox�s

z)MemoryAccountWithoutNamespaces.addMailboxc	Cs�dd�|�d�D�}tdt|��D]6}z|�d�|d|���Wq"tk
rVYq"Xq"z|�d�|��Wn$tk
r�|�d�s�YdSYnXdS)NcSsg|]}|r|�qSr@r@)rF�pathr@r@rDrJ�sz9MemoryAccountWithoutNamespaces.create.<locals>.<listcomp>�/r>FT)r rr�r�r�r3r�)r\Zpathspec�pathsZaccumr@r@rDr��s
z%MemoryAccountWithoutNamespaces.createcCst�dSrg)�NotImplementedError)r\r�r)r@r@rDr��sz,MemoryAccountWithoutNamespaces._emptyMailboxr>cCs|j�t|����Srg)r�r6r�r")r\r�Z	readwriter@r@rDr�sz%MemoryAccountWithoutNamespaces.selectcCs�t|���}|j�|�}|s$td��d|��krZ|j��D]}||kr:|�|�r:td��q:|��t	|�
|��dkr�td|f��|j|=dS)NzNo such mailboxz	\Noselectz<Hierarchically inferior mailboxes exist and \Noselect is setr>z)Name "%s" has inferior hierarchical names)r�r"r�r6r1r�r�reZdestroyr��_inferiorNames)r\r�rZothersr@r@rDr�s
�z%MemoryAccountWithoutNamespaces.deletecs�t�����t������|jkr*t���|���}��fdd�|D�}|D]\}}||jkrLt|��qL|D] \}}|j||j|<|j|=qldS)Ncsg|]}||���d�f�qS�r>)r�)rF�o�r�r�r@rDrJ"sz9MemoryAccountWithoutNamespaces.rename.<locals>.<listcomp>)r�r"r�r4r�r3)r\r�r��	inferiors�old�newr@r�rDr�s



z%MemoryAccountWithoutNamespaces.renamecCs,g}|j��D]}|�|�r|�|�q|Srg)r�r�rerr)r\r�r�Zinfnamer@r@rDr�-s

z-MemoryAccountWithoutNamespaces._inferiorNamescCst|���|jkSrg)r�r"r�r>r@r@rDr�5sz+MemoryAccountWithoutNamespaces.isSubscribedcCs&t|���}||jkr"|j�|�dSrg)r�r"r�rrr>r@r@rDr�9s
z(MemoryAccountWithoutNamespaces.subscribecCs4t|���}||jkr$td|f��|j�|�dS)NzNot currently subscribed to %s)r�r"r�r1�remover>r@r@rDr�?s
z*MemoryAccountWithoutNamespaces.unsubscribecs0��t|����}t�d����fdd�|D�S)Nr�cs$g|]}��|�r|�j|f�qSr@)rOr�r�r\rAr@rDrJIs
z@MemoryAccountWithoutNamespaces.listMailboxes.<locals>.<listcomp>)r�r�r"r�)r\r�rAr@r�rDr�Fs
z,MemoryAccountWithoutNamespaces.listMailboxes)N)r>)r�r�r�r�r�r�r_r�r�r�r�r�r�r�r�r�r�r�r�r@r@r@rDr��s 	


r�c@s$eZdZdd�Zdd�Zdd�ZdS)�
MemoryAccountcCs
ddggS)NrR�/r@rhr@r@rDr�Qsz#MemoryAccount.getPersonalNamespacescCsdSrgr@rhr@r@rDr�Usz!MemoryAccount.getSharedNamespacescCsdSrgr@rhr@r@rD�getOtherNamespacesYsz MemoryAccount.getOtherNamespacesN)r�r�r�r�r�r�r@r@r@rDr�Lsr�r�r�Z
getUIDNextr�ZgetUnseenCountrFcCs*i}|D]}t|t|����||<q|Srg)r�_statusRequestDictr")rr��rr�r@r@rD�statusRequestHelperfsr�cCs*|dkrdgStj�|g�}dd�|D�S)N)NNNcSs&g|]\}}|pddg|�d��qS)N�@�r )rFr,Zaddressr@r@rDrJrszparseAddr.<locals>.<listcomp>)r9r:Zgetaddresses)Zaddrr@r@rD�	parseAddrnsr�c
Cs�|�d�}|�d�}|�d�}|�d�}|�d|�}|�d|�}|�d�}|�d�}|�d	�}	|�d
�}
|�d�}||t|�t|�|o�t|�|o�t|�|o�t|�|	o�t|	�|
|f
S)NTrgrjrM�senderzreply-tormrEr2zin-reply-toz
message-id)r5r6r�)rq�headersrgrjZfrom_r�Zreply_tormrEr2Zin_reply_toZmidr@r@rDr�vs&












�r�cCsd}|��D]}|d7}q|Sr�)rA)rqr�r.r@r@rD�getLineCount�s
r�cCs0|d|dkrdkr,nn|dd�S|S)Nrryr�r>r@r�r@r@rD�unquote�s r�cCs�d}|�dd��dd�}d�|���}|r�|�d�}|d�dd�}t|�dkr^|d}d}n|\}}td	d
�|dd�D��}nd}}|||fS)zJ
    Return a two-tuple of the main and subtype of the given message.
    NF�content-typer3�;rr�r>css"|]}|�����dd�VqdS)�=r>N)rJr�r r�r@r@rDr��sz"_getContentType.<locals>.<genexpr>)r5r6r��
splitlinesr r��dict)rq�attrsZmmZmimetyper��major�minorr@r@rD�_getContentType�s
r�cCs�t|�\}}}|dk	r|��}|dk	r.|��}|dkrBt|||�S||fdkr\t||||�S|dkrrt||||�St||||�SdS)aE
    Construct an appropriate type of message structure object for the given
    message object.

    @param message: A L{IMessagePart} provider

    @return: A L{_MessageStructure} instance of the most specific type available
        for the given message, determined by inspecting the MIME type of the
        message.
    NZ	multipart)rlrdr)r�r��_MultipartMessageStructure�_RFC822MessageStructure�_TextMessageStructure�_SinglepartMessageStructure)rl�main�subtyper�r@r@rD�_getMessageStructure�sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_MessageStructurez�
    L{_MessageStructure} is a helper base class for message structure classes
    representing the structure of particular kinds of messages, as defined by
    their MIME type.
    cCs||_||_dS)z�
        @param message: An L{IMessagePart} provider which this structure object
            reports on.

        @param attrs: A C{dict} giving the parameters of the I{Content-Type}
            header of the message.
        N)rlr�)r\rlr�r@r@rDr_�sz_MessageStructure.__init__cCsj|rb|�d�}t|�dkr,|d��df}n2t|�dkr^dd�|dd�D�}|d��|g}|SdSdS)a
        Parse a I{Content-Disposition} header into a two-sequence of the
        disposition and a flattened list of its parameters.

        @return: L{None} if there is no disposition header value, a L{list} with
            two elements otherwise.
        z; r>rNcSs"g|]}|�dd�D]}|�qqS�r�r>r�)rFZparamrPr@r@rDrJ�sz2_MessageStructure._disposition.<locals>.<listcomp>)r r�r�)r\ZdispZparamsr@r@rD�_disposition�s
z_MessageStructure._dispositioncCs0|jr,dd�|j��D�}dd�t|�D�SdS)z�
        @return: The I{Content-Type} parameters, unquoted, as a flat list with
            each Nth element giving a parameter name and N+1th element giving
            the corresponding parameter value.
        cSsg|]\}}|t|�f�qSr@)r��rFr�r�r@r@rDrJ�sz4_MessageStructure._unquotedAttrs.<locals>.<listcomp>cSsg|]}|D]}|�qqSr@r@)rFrP�yr@r@rDrJ�sN)r�r�rn)r\Zunquotedr@r@rD�_unquotedAttrs�sz _MessageStructure._unquotedAttrsN)r�r�r�r�r_r�r�r@r@r@rDr��sr�c@s:eZdZdZdddgZdd�Zdd�Zd	d
�Zdd�Zd
S)r�zn
    L{_SinglepartMessageStructure} represents the message structure of a
    non-I{multipart/*} message.
    �
content-id�content-description�content-transfer-encodingcCs$t�|||�||_||_||_dS)a�
        @param message: An L{IMessagePart} provider which this structure object
            reports on.

        @param main: A L{str} giving the main MIME type of the message (for
            example, C{"text"}).

        @param subtype: A L{str} giving the MIME subtype of the message (for
            example, C{"plain"}).

        @param attrs: A C{dict} giving the parameters of the I{Content-Type}
            header of the message.
        N)r�r_r�r�r�)r\rlr�r�r�r@r@rDr_sz$_SinglepartMessageStructure.__init__cCsV|jjd|j��}|j��}|j|j}}|��}||||�d�|�d�|�d�|gS)zN
        Return a list of the basic fields for a single-part message.
        Fr�r�r�)F)rlr5�_HEADERSrSr�r�r�r6)r\r�r�r�r�Z
unquotedAttrsr@r@rD�_basicFieldss
�z(_SinglepartMessageStructure._basicFieldscCs|��}|r|�|���|S)z�
        Construct and return a list of the basic and extended fields for a
        single-part message.  The list suitable to be encoded into a BODY or
        BODYSTRUCTURE response.
        )r�rw�	_extended�r\�extendedr5r@r@rDr�3sz"_SinglepartMessageStructure.encodecCsbg}|j�ddddd�}|�|�d��|�|�|�d���|�|�d��|�|�d��|S)aw
        The extension data of a non-multipart body part are in the
        following order:

          1. body MD5

             A string giving the body MD5 value as defined in [MD5].

          2. body disposition

             A parenthesized list with the same content and function as
             the body disposition for a multipart body part.

          3. body language

             A string or parenthesized list giving the body language
             value as defined in [LANGUAGE-TAGS].

          4. body location

             A string list giving the body content URI as defined in
             [LOCATION].

        Fzcontent-md5�content-disposition�content-language�content-location)rlr5rrr6r��r\r5r�r@r@rDr�?s�z%_SinglepartMessageStructure._extendedN)	r�r�r�r�r�r_r�r�r�r@r@r@rDr��s�r�c@seZdZdZdd�ZdS)r�z_
    L{_TextMessageStructure} represents the message structure of a I{text/*}
    message.
    cCs0t�|�}|�t|j��|r,|�|���|S)a
        A body type of type TEXT contains, immediately after the basic
        fields, the size of the body in text lines.  Note that this
        size is the size in its content transfer encoding and not the
        resulting size after any decoding.
        )r�r�rrr�rlrwr�r�r@r@rDr�ks

z_TextMessageStructure.encodeN�r�r�r�r�r�r@r@r@rDr�fsr�c@seZdZdZdd�ZdS)r�zi
    L{_RFC822MessageStructure} represents the message structure of a
    I{message/rfc822} message.
    cCsHt�||�}|j�d�}|�t|��|�t|d��|�t|��|S)z�
        A body type of type MESSAGE and subtype RFC822 contains,
        immediately after the basic fields, the envelope structure,
        body structure, and size in text lines of the encapsulated
        message.
        rF)r�r�rlr�rrr�r�r�)r\r�r5Z	containedr@r@rDr�sz_RFC822MessageStructure.encodeNr�r@r@r@rDr�zsr�c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)r�zi
    L{_MultipartMessageStructure} represents the message structure of a
    I{multipart/*} message.
    cCst�|||�||_dS)aR
        @param message: An L{IMessagePart} provider which this structure object
            reports on.

        @param subtype: A L{str} giving the MIME subtype of the message (for
            example, C{"plain"}).

        @param attrs: A C{dict} giving the parameters of the I{Content-Type}
            header of the message.
        N)r�r_r�)r\rlr�r�r@r@rDr_�sz#_MultipartMessageStructure.__init__ccsBd}z|j�|�}Wntk
r,Yq>YqX|V|d7}qdS)zR
        Return an iterator over all of the sub-messages of this message.
        rr>N)rlr�r�)r\rcr�r@r@rD�	_getParts�s
z$_MultipartMessageStructure._getPartscs8�fdd�|��D�}|�|j��r4|�|���|S)zW
        Encode each sub-message and added the additional I{multipart} fields.
        csg|]}t|�����qSr@�r�r�rU�r�r@rDrJ�sz5_MultipartMessageStructure.encode.<locals>.<listcomp>)r�rrr�rwr�r�r@r�rDr��s
z!_MultipartMessageStructure.encodecCsbg}|j�dddd�}|�|���|�|�|�d���|�|�dd��|�|�dd��|S)af
        The extension data of a multipart body part are in the following order:

          1. body parameter parenthesized list
               A parenthesized list of attribute/value pairs [e.g., ("foo"
               "bar" "baz" "rag") where "bar" is the value of "foo", and
               "rag" is the value of "baz"] as defined in [MIME-IMB].

          2. body disposition
               A parenthesized list, consisting of a disposition type
               string, followed by a parenthesized list of disposition
               attribute/value pairs as defined in [DISPOSITION].

          3. body language
               A string or parenthesized list giving the body language
               value as defined in [LANGUAGE-TAGS].

          4. body location
               A string list giving the body content URI as defined in
               [LOCATION].
        Fr�r�r�N)rlr5rrr�r�r6r�r@r@rDr��s�z$_MultipartMessageStructure._extendedN)r�r�r�r�r_r�r�r�r@r@r@rDr��s
r�FcCst|��|�S)ar
    RFC 3501, 7.4.2, BODYSTRUCTURE::

      A parenthesized list that describes the [MIME-IMB] body structure of a
      message.  This is computed by the server by parsing the [MIME-IMB] header
      fields, defaulting various fields as necessary.

        For example, a simple text message of 48 lines and 2279 octets can have
        a body structure of: ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL
        "7BIT" 2279 48)

    This is represented as::

        ["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 2279, 48]

    These basic fields are documented in the RFC as:

      1. body type

         A string giving the content media type name as defined in
         [MIME-IMB].

      2. body subtype

         A string giving the content subtype name as defined in
         [MIME-IMB].

      3. body parameter parenthesized list

         A parenthesized list of attribute/value pairs [e.g., ("foo"
         "bar" "baz" "rag") where "bar" is the value of "foo" and
         "rag" is the value of "baz"] as defined in [MIME-IMB].

      4. body id

         A string giving the content id as defined in [MIME-IMB].

      5. body description

         A string giving the content description as defined in
         [MIME-IMB].

      6. body encoding

         A string giving the content transfer encoding as defined in
         [MIME-IMB].

      7. body size

         A number giving the size of the body in octets.  Note that this size is
         the size in its transfer encoding and not the resulting size after any
         decoding.

    Put another way, the body structure is a list of seven elements.  The
    semantics of the elements of this list are:

       1. Byte string giving the major MIME type
       2. Byte string giving the minor MIME type
       3. A list giving the Content-Type parameters of the message
       4. A byte string giving the content identifier for the message part, or
          None if it has no content identifier.
       5. A byte string giving the content description for the message part, or
          None if it has no content description.
       6. A byte string giving the Content-Encoding of the message body
       7. An integer giving the number of octets in the message body

    The RFC goes on::

        Multiple parts are indicated by parenthesis nesting.  Instead of a body
        type as the first element of the parenthesized list, there is a sequence
        of one or more nested body structures.  The second element of the
        parenthesized list is the multipart subtype (mixed, digest, parallel,
        alternative, etc.).

        For example, a two part message consisting of a text and a
        BASE64-encoded text attachment can have a body structure of: (("TEXT"
        "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23)("TEXT" "PLAIN"
        ("CHARSET" "US-ASCII" "NAME" "cc.diff")
        "<960723163407.20117h@cac.washington.edu>" "Compiler diff" "BASE64" 4554
        73) "MIXED")

    This is represented as::

        [["TEXT", "PLAIN", ["CHARSET", "US-ASCII"], None, None, "7BIT", 1152,
          23],
         ["TEXT", "PLAIN", ["CHARSET", "US-ASCII", "NAME", "cc.diff"],
          "<960723163407.20117h@cac.washington.edu>", "Compiler diff",
          "BASE64", 4554, 73],
         "MIXED"]

    In other words, a list of N + 1 elements, where N is the number of parts in
    the message.  The first N elements are structures as defined by the previous
    section.  The last element is the minor MIME subtype of the multipart
    message.

    Additionally, the RFC describes extension data::

        Extension data follows the multipart subtype.  Extension data is never
        returned with the BODY fetch, but can be returned with a BODYSTRUCTURE
        fetch.  Extension data, if present, MUST be in the defined order.

    The C{extended} flag controls whether extension data might be returned with
    the normal data.
    r�)rqr�r@r@rDr��sir�cCs(dd�|��D�}d�|�d}t|�S)Nc	Ss,g|]$\}}d�|��d�|���f��qS)z: �
)r��titler�r�r@r@rDrJOsz"_formatHeaders.<locals>.<listcomp>r�)r�r�r)r�r�r@r@rDr�Ms
�r�ccs8d}z|�|�V|d7}qWntk
r2YnXdSr�)r�r�)rQrcr@r@rD�subpartsTsr�cs2ddlm�t�������fdd���d��S)a�
    Consume an interator at most a single iteration per reactor iteration.

    If the iterator produces a Deferred, the next iteration will not occur
    until the Deferred fires, otherwise the next iteration will be taken
    in the next reactor iteration.

    @rtype: C{Deferred}
    @return: A deferred which fires (with None) when the iterator is
    exhausted or whose errback is called if there is an exception.
    rrcshzt��}Wn0tk
r*��|�Yn:���Yn(Xt|tj�rV|���n��d�|�dSr�)	rr�r�r�rWrr<r0r#)rkr��r��gorcrr@rDrmsziterateInReactor.<locals>.goN)r"rrr<)rcr@rrDr�_s
r�c@s4eZdZdZeej�Zd	dd�Zdd�Z	dd�Z
dS)
r��NcCs<||_|dkrt��}||_|dkr(t}||_|jj|_dS)a
        Produce this message.

        @param msg: The message I am to produce.
        @type msg: L{IMessage}

        @param buffer: A buffer to hold the message in.  If None, I will
            use a L{tempfile.TemporaryFile}.
        @type buffer: file-like
        N)rqr�r�r�r�r�r�)r\rqr�r�r@r@rDr_�szMessageProducer.__init__cCs||_|�|���Srg)�consumerr��_produce)r\rr@r@rDr��szMessageProducer.beginProducingc#s��j�d�}d}�j��r�|�d�}dd�|�d�dd�D�}tdd�|D��}|�d�}|dkr�d	���jf}|dd
|f7<n |�d�r�|�	d�r�|dd�}t
|�}��t|����d
��j���r&t
�j�D].}��d|d
�t|�j�j��d�Vq��d|d�n8�j��}|��j�}|�r^�j�|�dVn�q^�q0�j�r��j�dd�t�j���j���fdd��VdS)NTr�cSsg|]}|�dd��qSr�r�r�r@r@rDrJ�sz,MessageProducer._produce.<locals>.<listcomp>r�r>cSs g|]\}}|����|f�qSr@)r�rJr�r@r@rDrJ�s�boundaryz----=%sz; boundary="%s"r�ryr�s
--s--
rcs�Srgr@r|rhr@rDrQ�rRz*MessageProducer._produce.<locals>.<lambda>)rqr5r�r6r r��_uuid4�hexrer�rr�r�r�r�r�r�r�rAr��
CHUNK_SIZErr�r�r0)r\r�rr<r�r�rr_r@rhrDr�sF



�

�
�zMessageProducer._produce)NN)r�r�r�r�staticmethod�uuidZuuid4rr_r�rr@r@r@rDr�~s


r�c
@szeZdZGdd�d�ZGdd�d�ZGdd�d�ZGdd�d�ZGd	d
�d
�ZGdd�d�ZGd
d�d�Z	Gdd�d�Z
Gdd�d�ZGdd�d�ZGdd�d�Z
Gdd�d�ZGdd�d�ZdZdefdefdefdefd efd!efd"e	fd#e
fd$efg	Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Ze�d7�Zd8d9�Zd:d;�Zd<d=�Z d>d?�Z!d@dA�Z"dS)Br]c@seZdZdZdd�ZdS)z_FetchParser.Enveloper_cCsdS)Nr_r@rhr@r@rDrQ�rRz_FetchParser.Envelope.<lambda>N�r�r�r�r�r�r@r@r@rD�Envelope�src@seZdZdZdd�ZdS)z_FetchParser.FlagsrbcCsdS)Nrbr@rhr@r@rDrQ�rRz_FetchParser.Flags.<lambda>Nrr@r@r@rD�Flags�sr
c@seZdZdZdd�ZdS)z_FetchParser.InternalDater]cCsdS)Nr]r@rhr@r@rDrQ�rRz"_FetchParser.InternalDate.<lambda>Nrr@r@r@rD�InternalDate�src@seZdZdZdd�ZdS)z_FetchParser.RFC822HeaderrfcCsdS)Nr�r@rhr@r@rDrQ�rRz"_FetchParser.RFC822Header.<lambda>Nrr@r@r@rD�RFC822Header�src@seZdZdZdd�ZdS)z_FetchParser.RFC822TextrhcCsdS)Nr�r@rhr@r@rDrQ�rRz _FetchParser.RFC822Text.<lambda>Nrr@r@r@rD�
RFC822Text�src@seZdZdZdd�ZdS)z_FetchParser.RFC822SizerjcCsdS)Nr�r@rhr@r@rDrQ�rRz _FetchParser.RFC822Size.<lambda>Nrr@r@r@rD�
RFC822Size�src@seZdZdZdd�ZdS)z_FetchParser.RFC822rdcCsdS)Nrdr@rhr@r@rDrQ�rRz_FetchParser.RFC822.<lambda>Nrr@r@r@rD�RFC822�src@seZdZdZdd�ZdS)z_FetchParser.UIDr+cCsdS)Nr+r@rhr@r@rDrQ�rRz_FetchParser.UID.<lambda>Nrr@r@r@rDr��sr�c@s@eZdZdZdZdZdZdZdZdZ	dZ
dZdd�Zdd�Z
dS)	z_FetchParser.BodyrCFNr@cCst|���Srg�rr�rhr@r@rDr�sz_FetchParser.Body.__str__cCs�d}d}d}|jr,d�dd�|jD��}d}|jrX|d||t|j��d�d7}nN|jrt|d||d	7}n2|jr�|d||d
7}n|jr�|d|d7}|jdk	r�|dt	|j�dt	|j
�d7}|S)
NrsrR�.cSsg|]}t|d��d��qS)r>r�)rr�r�r@r@rDrJs�z/_FetchParser.Body.__bytes__.<locals>.<listcomp>r�r�r�sTEXT]sMIME]rurv)r�r�r�r�r�rr�r��partialBeginr�
partialLength)r\�baser�Z	separatorr@r@rDr�	s.
���
$z_FetchParser.Body.__bytes__)r�r�r�r�r}r�r�rr�r�rrr�r�r@r@r@rD�Body�src@seZdZdZdd�ZdS)z_FetchParser.BodyStructureracCsdS)Nrar@rhr@r@rDrQ#rRz#_FetchParser.BodyStructure.<lambda>Nrr@r@r@rD�
BodyStructure!src@s(eZdZdZdZdZdd�Zdd�ZdS)z_FetchParser.HeaderFNcCst|���Srgrrhr@r@rDr�,sz_FetchParser.Header.__str__cCs�d}|jrh|d7}|jr |d7}g}|jD]&}|��}t|�rFt|�}|�|�q*|dd�|�d7}|jr�d�dd	�|jD��d|}|S)
NsHEADERs.FIELDSs.NOTr�r�rTrcSsg|]}|d���qSr�)r�r�r@r@rDrJ@sz1_FetchParser.Header.__bytes__.<locals>.<listcomp>)r�r�r�r�r�rrr�r�)r\rr�rr@r@rDr�0s
z_FetchParser.Header.__bytes__)r�r�r�r�r�r�r�r�r@r@r@rD�Header's
rc@seZdZdS)z_FetchParser.TextN�r�r�r�r@r@r@rD�TextDsrc@seZdZdS)z_FetchParser.MIMENrr@r@r@rD�MIMEHsrNsenvelopesflagssinternaldates
rfc822.headersrfc822.textsrfc822.sizesrfc822suids
bodystructurecCsdg|_g|_d|_dS)N�initialrR)rr5�	remainingrhr@r@rDr_Ysz_FetchParser.__init__cCs~|j|}zf|s|jrn|js$td��|j��}zt|d|�|�}Wn|j�|��YqX||d�}qW5||_XdS)NzInvalid ArgumentZstate_)rrr/rrrr)r\r�r�usedr@r@rDr^_s


z_FetchParser.parseStringcCs�|dkrdS|��}|�d�rF|j�|��|��|��|��f�dS|�d�r~|j�|��|��|��|��|��f�dS|�d�r�|j�|��|��|��f�dS|�d�r�|j	�d	�d
S|j	�
d�dS)NrRrsallrsfullrsfastrS)Zclose_paren�maybe_fetch_att�	fetch_attr>r")r�rer5rwr
rrrrrrr)r\r�rdr@r@rD�
state_initialss@
�
�
�
z_FetchParser.state_initialcCs|�d�rdStd��dS)NrTr>z	Missing )�rerr�r@r@rD�state_close_paren�s
z_FetchParser.state_close_parencCsN|r|dd���std��d}tt|��D]}|||d���s,qJq,|S)Nrr>zWhitespace expected, none found)�isspacerrr�)r\r�rcr@r@rD�state_whitespace�sz_FetchParser.state_whitespacecCs|�d�s|j�d�dS)NrT)r!r"r�r�rerrwr�r@r@rD�state_maybe_fetch_att�s
z"_FetchParser.state_maybe_fetch_attcCs�|��}|jD],\}}|�|�r|j�|��t|�Sq|��}|�d�rZd|_d}n|�d�rjd}ntd|f��||_	|j
�d�|S)Ns	body.peekTr�sbodyrz#Nothing recognized in fetch_att: %s)Zgot_bodyZ
maybe_partialZ
maybe_section)r��_simple_fetch_attrer5rrr�rr}r�pending_bodyrrw)r\r�rdr��clsr_r r@r@rD�state_fetch_att�s


z_FetchParser.state_fetch_attcCs|j�|j�|`dSr�)r5rrr+r�r@r@rD�state_got_body�sz_FetchParser.state_got_bodycCs|�d�sdS|j�d�dS)Nr�r)ZsectionZpart_numberr>r(r�r@r@rD�state_maybe_section�s
z _FetchParser.state_maybe_sections(\d+(?:\.\d+)*)\.?cCsH|j�|�}|dk	r:dd�|��d�d�D�|_|��Sg|_dSdS)NcSsg|]}t|�d�qSr�)rKrUr@r@rDrJ�sz2_FetchParser.state_part_number.<locals>.<listcomp>rr)�	_partExprrO�groupsr r�r^)r\r�rQr@r@rD�state_part_number�sz_FetchParser.state_part_numbercCs|��}d}|�d�r(d|j_|d7}n�|�d�rX|��}|j_d|_d|_|d7}n�|�d�rx|��|j_	|d	7}nx|�d
�r�|�
�|j_|d	7}nX|��}|�d�r�d|_|d7}n"|�d
�r�|d7}ntd|f��||j_|j
�d�t|j�|j_d|_|S)Nrr�Tr>sheader]r@ristext]rsmime]sheader.fields.not�s
header.fieldsr?zUnhandled section contents: %r)Zfinish_sectionZheader_listr�)r�rer+r�rr�r�r�rrrr�rrrwr:r�r�)r\r�rdr rer@r@rD�
state_section�s8











z_FetchParser.state_sectioncCs|�d�std��dS)Nr�zsection must end with ]r>r$r�r@r@rD�state_finish_section	s
z!_FetchParser.state_finish_sectioncCsX|�d�std��|�d�}|dkr,td��|d|���}dd�|D�|jj_|dS)	NrSzHeader list must begin with (rTryzHeader list must end with )r>cSsg|]}|���qSr@r�)rFrer@r@rDrJsz2_FetchParser.state_header_list.<locals>.<listcomp>)rerrVr r+r�r�)r\r�r^r�r@r@rD�state_header_lists

z_FetchParser.state_header_listcCsz|�d�sdS|�d�}|dkr(td��|d|�}|�dd�}t|�dkrTtd	��tt|�\}}||j_||j_	|dS)
NrurrvryzFound < but not >r>rr�z>Partial specification did not include two .-delimited integers)
rerVrr r�r�rKr+rr)r\r�r^rpr�Zbeginrr@r@rD�state_maybe_partials

z _FetchParser.state_maybe_partial)#r�r�r�rr
rrrrrr�rrrrrr�r*r_r^r#r%r'r)r-r.r/r�r�r0r2r4r5r6r7r@r@r@rDr]�sN&�#

&r]c@sDeZdZdZdZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dS)r�rTcCs
||_dSrgr�)r\rr@r@rDr_4szFileProducer.__init__cCs.||_|j|_t��}|_|j�|d�|Sr�)rr��producerr<�_onDoneZregisterProducer)r\rr�r@r@rDr�8s
zFileProducer.beginProducingcCs|d}|jr$dt|���d}d|_|js.dS||j�|j�}|sn|j��|j�	|�d|_|_|_n
|�
|�dS)NrRrGr�F)�
firstWriter�_sizerr�rrZunregisterProducerr9r�r8)r\r_r@r@rD�resumeProducing@s
zFileProducer.resumeProducingcCsdS)z9
        Pause the producer.  This does nothing.
        Nr@rhr@r@rD�pauseProducingPszFileProducer.pauseProducingcCsdS)z8
        Stop the producer.  This does nothing.
        Nr@rhr@r@rD�
stopProducingVszFileProducer.stopProducingcCs8|j��}|j�dd�|j��}|j�|d�||S)Nrr�)rrMr�)r\r_rr@r@rDr;\s


zFileProducer._sizeN)r�r�r�rr:r_r�r<r=r>r;r@r@r@rDr�/sr�cCs�ddddddddd	d
ddd
dddddddddddg}dddd�}t�d||�}|sbtd|f��|��}zBd|�|d���d |d<t|d!�|d!<t|d"�|d"<Wn"tk
r�td|f��Yn*Xt�|d!|d|d"d#d#d#d$d$d$f	�SdS)%NZjanZfebZmarZaprZmayZjunZjulZaug�sep�octZnovZdecZjanuaryZfebruaryZmarchZaprilZjuneZjulyZaugustZ	septemberZoctoberZnovemberZdecemberz+(?P<day>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])z(?P<mon>\w+)z(?P<year>\d\d\d\d))�day�mon�yearz%(day)s-%(mon)s-%(year)szCannot parse time string %rr>rB�rCrArry)	r�rOr`�	groupdict�indexr�rKr��struct_time)r�Zmonths�exprrQr�r@r@rDr8esT�� �r8�castcGs|dSr�r@rOr@r@rDrQ�rRrQcCs|�d�}|dd��dd�S)N�utf-7r>ryr�r�)r�r��r�Zs_utf7r@r@rD�modified_base64�s
rLcCsd|�dd�d}|�d�S)Nrzr�r�r�rJ)r�r+rKr@r@rD�modified_unbase64�srMcCs�t�}g}ttttdd���dh}|D]�}||krl|r\|dtd�|��d7}|dd�=|�t|��q(|dkr�|r�|dtd�|��d7}|dd�=|d7}q(|�|�q(|r�|�	dtd�|��d�t
|�t|�fS)	ap
    Encode the given C{unicode} string using the IMAP4 specific variation of
    UTF-7.

    @type s: C{unicode}
    @param s: The text to encode.

    @param errors: Policy for handling encoding errors.  Currently ignored.

    @return: L{tuple} of a L{str} giving the encoded bytes and an L{int}
        giving the number of code units consumed from the input.
    � ��&�&r3r�Ns&-)�	bytearrayr�r��chrrrLr�rr�ordrwr;r�)r��errorsr�Z_inZvalid_charsrr@r@rD�encoder�s$



rVc	Cs�g}g}tt|�d�}|D]�}|dkr6|s6|�d�q|dkr||r|t|�dkrZ|�d�n|�td�|dd����g}q|r�|�|�q|�|���q|r�|�td�|dd����d�|�t|�fS)	aw
    Decode the given L{str} using the IMAP4 specific variation of UTF-7.

    @type s: L{str}
    @param s: The bytes to decode.

    @param errors: Policy for handling decoding errors.  Currently ignored.

    @return: a L{tuple} of a C{unicode} string giving the text which was
        decoded and an L{int} giving the number of bytes consumed from the
        input.
    rrQr�r>rPrRNr3)�memory_cast�
memoryviewrrr�rMr�r+)r�rUr�r+rr@r@rD�decoder�s"
rYc@seZdZddd�ZdS)�StreamReader�strictcCst|�Srg)rY�r\r�rUr@r@rDr+�szStreamReader.decodeN)r[)r�r�r�r+r@r@r@rDrZ�srZc@seZdZddd�ZdS)�StreamWriterr[cCst|�Srg)rVr\r@r@rDr��szStreamWriter.encodeN)r[)r�r�r�r�r@r@r@rDr]�sr]cCs|dkrtSdSr�)�
_codecInfor�r@r@rD�imap4_utf_7�sr_�IMailboxListenerrr��IMailboxrr�IMailboxInfo�IMessager�r�r
�IMessagePartr.r/r0r2r6r7r8r=r9r:r;r<r1r3r4r5r)r,r*r-r+)N)r)N)r>)F)N)N)�r�r��codecsr�ror�r�r�r�r
Zemail.utilsr9�	itertoolsr�iorZzope.interfacerZtwisted.protocolsrrr"rrZtwisted.internet.deferr	Ztwisted.pythonr
rZtwisted.python.compatrr
rSrr�rr�rrrrrrrrrrZtwisted.credrZtwisted.cred.errorrrZtwisted.mail.interfacesrrrr�r rdr!rcr"r�r#r
r$r�r%rbr&rar'rr(r`Ztwisted.mail._credr)r*r+r,r-Ztwisted.mail._exceptr.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r�rrr r�rErK�objectrLr�r�r�r�Z_SPr�Z_CTLr�r+Z_nativeNonAtomCharsr�r�rXr�ZLineReceiverZTimeoutMixinr��TimeoutErrorr�r�r[r�r�rnr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r3r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r]r�r8rrXrWrLrMrVrYrZr]�	CodecInfor^r_�register�__all__r@r@r@rD�<module>sv
<8
H	�<$4$e
;


A#
;
4}�
4gR
lJi6
$
#
�