Spamworldpro Mini Shell
Spamworldpro


Server : Apache/2.4.52 (Ubuntu)
System : Linux webserver 6.8.0-49-generic #49~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Wed Nov 6 17:42:15 UTC 2 x86_64
User : www-data ( 33)
PHP Version : 8.1.2-1ubuntu2.21
Disable Function : NONE
Directory :  /lib/python3/dist-packages/twisted/mail/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //lib/python3/dist-packages/twisted/mail/__pycache__/imap4.cpython-310.pyc
o

�bW:�@s
dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlm
Z
mZddlmZddlmZddlmZmZmZddlmZddlmZdd	lmZmZdd
lmZm Z m!Z!ddl"m#Z#ddl$m%Z%m&Z&m'Z'm(Z(m)Z)dd
l*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:ddl;m<Z=m>Z>m?Z@mAZBmCZDmEZFmGZHmIZJmKZLmMZNmOZOmPZQddlRmSZSmTZTddlUmVZVmWZWddlXmYZYmZZZm[Z[m\Z\m]Z]e^e_e`dd�d�a���Zbdd�Zcdd�ZdGdd�d�ZeGdd�d�ZfGdd�d�ZgGdd �d �ZhGd!d"�d"�Zid#Zjekee`d$�e`d%d&���Zld'ejelZmem�nd(�Zoe�pd)eod*�Zqekd+d,�e`d&�D��ZreeF�Gd-d.�d.eSjseTjt��Zue �v�ZweeF�Gd/d0�d0eSjseTjt��Zxd�d1d2�Zyd3Zzd4Z{e|Z}d�d5d6�Z~d7d8�Zd9d:�Z�d�d;d<�Z�d=d>�Z�d?d@�Z�dAdB�Z�d�dCdD�Z�dEdF�Z�dGekdHekfdIdJ�Z�GdKdL�dL�Z�dMZ�dNdO�Z�dPdQ�Z�dRdS�Z�dTdU�Z�dVdW�Z�ee=�GdXdY�dY��Z�eeO�GdZd[�d[e���Z�d\d]d^d_d`da�Z�dbdc�Z�ddde�Z�dfdg�Z�dhdi�Z�djdk�Z�dldm�Z�dndo�Z�Gdpdq�dq�Z�Gdrds�dse��Z�Gdtdu�due��Z�Gdvdw�dwe��Z�Gdxdy�dye��Z�d�d{d|�Z�d}d~�Z�dd��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��gd��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)�decodebytes�encodebytes)�BytesIO)�chain)�Any�List�cast)�implementer)�credentials)�UnauthorizedLogin�UnhandledCredentials)�defer�error�
interfaces)�
maybeDeferred)�CramMD5ClientAuthenticator�LOGINAuthenticator�LOGINCredentials�PLAINAuthenticator�PLAINCredentials)�IllegalClientResponse�IllegalIdentifierError�IllegalMailboxEncoding�IllegalOperation�IllegalQueryError�IllegalServerResponse�IMAP4Exception�MailboxCollision�MailboxException�MismatchedNesting�MismatchedQuoting�NegativeResponse�
NoSuchMailbox�NoSupportedAuthentication�ReadOnlyMailbox�UnhandledResponse)�IAccountIMAP�IClientAuthentication�ICloseableMailboxIMAP�IMailboxIMAP�IMailboxIMAPInfo�IMailboxIMAPListener�IMessageIMAP�IMessageIMAPCopier�IMessageIMAPFile�IMessageIMAPPart�INamespacePresenter�ISearchableIMAPMailbox)�basic�policies)�log�text)�_get_async_param�_matchingString�	iterbytes�nativeString�
networkString��
z/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov DeccCs||ur|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�_swap`srBcs��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=)rB)�.0�first�second�r@r?r=rA�
<listcomp>}s�z!_swapAllPairs.<locals>.<listcomp>r=)�ofr?r@r=rFrA�
_swapAllPairsns�rIc@s�eZdZUdZgZeeed<ed�Z	eefdd�Z
edd��Zej
dd��Zefd	d
�Zdd�Zd
d�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdefdd�Zdefdd�Zd edefd!d"�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).
    �_empty�infcCsZ|j|_g|_dd�|_||jurdSt|t�r%|dd�|_|��dS|�||�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=rA�<lambda>��z%MessageSet.__init__.<locals>.<lambda>N)rK�_last�ranges�getnext�
isinstance�list�clean�add��self�start�endr=r=rA�__init__�s



zMessageSet.__init__cCs|jS)z{
        The largest number in use.
        This is undefined until it has been set by assigning to this property.
        )rR�rZr=r=rA�last�szMessageSet.lastcCsv|j|jur
td��||_t|j�D]"\}\}}|dur|}|dur$|}||kr-||}}||f|j|<q|��dS)z�
        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 ValueError: if a largest value has already been set.
        zlast already setN)rRrK�
ValueError�	enumeraterSrW)rZ�value�i�low�highr=r=rAr_�s	
cCst||jur|}|j|jur|dur|j}|dur|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�r?r@)�key)rKrRr_�sorted�	functools�partialrB�	_infinityrS�appendrWrYr=r=rArX�s


�zMessageSet.addcCslt|t�r|j|j}t|�St|j�}|j|jur|j|_z|j|�W|Sty5|�|�Y|Sw�N)rUrJrSr_rKrX�	TypeError)rZ�otherrS�resr=r=rA�__add__s

��zMessageSet.__add__cCsTt|t�r|j�|j�|��|Sz|j|�W|Sty)|�|�Y|Sw)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}
        )rUrJrS�extendrWrXrn�rZror=r=rArrs
���zMessageSet.extendcCs�tt|j|jdd��}td�td�fg}|D]$\}}|d\}}||dkr.|�||f�qt||�t||�f|d<qt|dd�d|jd�|_dS)z>
        Clean ranges list, combining adjacent ranges
        Nrfz-inf���r;)rhrIrSrk�floatrl�min�max)rZrS�mergedRangesrdre�previousLow�previousHighr=r=rArW0szMessageSet.cleancCs|jddduS)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.
        rtN)rSr^r=r=rA�
_noneInRangesDszMessageSet._noneInRangescCs@|��rtd��|jD]\}}||kr|krdSqqdS)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)r{rnrS)rZrbrdrer=r=rA�__contains__es�zMessageSet.__contains__ccsD�|jD]\}}|�|d�}||kr|V|�|�}||ksqdSrM)rSrT)rZ�l�hr=r=rA�	_iteratorvs�
���zMessageSet._iteratorcCs|��rtd��|��S)Nz!Can't iterate; last value not set)r{rnrr^r=r=rA�__iter__}szMessageSet.__iter__cCsJd}|jD]\}}|dur|d7}q|durtd��|||d7}q|S)Nrr;z%Can't size object; last value not set)rSrn)rZrpr}r~r=r=rA�__len__�s
zMessageSet.__len__�returncCsvg}|jD]0\}}||kr|dur|�d�q|�t|��q|dur,|�d|f�q|�d||f�qd�|�S)N�*z%d:*z%d:%d�,)rSrl�str�join)rZ�prdrer=r=rA�__str__�s
zMessageSet.__str__cCsdt|��d�S)Nz<MessageSet �>�r�r^r=r=rA�__repr__��zMessageSet.__repr__rocCs t|t�rtt|j|jk�StSrm)rUrJr�boolrS�NotImplementedrsr=r=rA�__eq__�s
zMessageSet.__eq__N)�__name__�
__module__�__qualname__�__doc__rKrr�__annotations__rurkr]�propertyr_�setterrXrqrrrWr{r|rr�r�r�r�r��objectr�r�r=r=r=rArJ�s*
9

!rJc@s$eZdZdd�Zdd�Zdd�ZdS)�
LiteralStringcCs||_g|_||_dSrm)�size�datar
�rZr��deferedr=r=rAr]��
zLiteralString.__init__cC�n|jt|�8_d}|jdkr|j�|�|S|jr+|d|j�||jd�}}nd}|r5|j�|�|S�Nr�)r��lenr�rl�rZr��passonr=r=rA�write�s
	� zLiteralString.writecCs|j�d�|j�|f�dS)�:
        Call deferred with data and rest of line
        r�N)r
�callbackr�r��rZ�liner=r=rAr��szLiteralString.callbackN)r�r�r�r]r�r�r=r=r=rAr��sr�c@�(eZdZdZdd�Zdd�Zdd�ZdS)	�LiteralFile��cCs0||_||_||jkrt��|_dSt�|_dSrm)r�r
�_memoryFileLimit�tempfile�
TemporaryFiler�rr�r=r=rAr]�s

zLiteralFile.__init__cCr�r�)r�r�r�r�r�r=r=rAr��s
� zLiteralFile.writecCs$|j�dd�|j�|j|f�dS)r�rN)r��seekr
r�r�r=r=rAr��szLiteralFile.callbackN)r�r�r�r�r]r�r�r=r=r=rAr��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)rZr�r�r=r=rAr]�s
zWriteBuffer.__init__cCs:|jt|�7_|j�|�|j|jkr|��dSdSrm)r�r�r�rlr��flush�rZ�sr=r=rAr��s
�zWriteBuffer.writecCs(|jr|j�|j�g|_d|_dSdSr�)r�r��
writeSequencer�r^r=r=rAr��s

�zWriteBuffer.flushN)r�)r�r�r�r�r]r�r�r=r=r=rAr��s

r�c@sJeZdZdZdZdZdZ			ddd�Zdefd	d
�Z	dd�Z
d
d�ZdS)�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�|g��Ri���Srmr=rN��contArgs�contKw�continuationr=rArP�z"Command.__init__.<locals>.<lambda>)�command�args�wantResponser��lines)rZr�r�r�r�r�r�r=r�rAr]s
	
zCommand.__init__r�cCsd�|j|j|j|j|j�S)Nz(<imap4.Command {!r} {!r} {!r} {!r} {!r}>)�formatr�r�r�r�r�r^r=r=rAr�s�zCommand.__repr__cCs.|jdur
d�||jf�Sd�||j|jf�S�N� )r�r�r��rZ�tagr=r=rAr�$s
zCommand.formatc	Cs�g}g}|jD]E}t|�}t|�}|dkr|d|jvsA|dkr'|d|jvsA|dkrG|ddkrGt|dt�rG|dd|jvrG|�|�q|�|�q|j	d}|_	|�
||f�|rc||�dSdS)Nr;r��OK)r��parseNestedParensr��_1_RESPONSES�_2_RESPONSESrUrV�
_OK_RESPONSESrlr
r�)	rZ�lastLine�unusedCallback�send�unuse�L�names�N�dr=r=rA�finish)s*
��zCommand.finish)Nr=N)r�r�r�r�r�r�r
r]r�r�r�r�r=r=r=rAr��s	
�r�r��!��s	]\\(){%*"�charmap�[�]ccs�|]	}|tvr|VqdSrm)�
_nonAtomChars)rC�chr=r=rA�	<genexpr>Rs�r�c@s�eZdZdZdZdZdZdZdZdZ	dZ
dZdZdZ
dZdZdZhd�Zd	Zd
Z�dMdd�Zd
d�Zdd�Zdd�Zdd�Zdd�ZdZdd�Zdd�Zdd�Zdd�Z�dNdd �Zd!d"�Z d#d$�Z!d%d&�Z"d'd(�Z#d)d*�Z$d+d,�Z%d-d.�Z&�dOd/d0�Z'e(�)d1e(�*e+�d2�Z,d3d4�Z-d5d6�Z.d7d8�Z/d9d:�Z0d;d<�Z1d=d>�Z2d?d@�Z3dAdB�Z4dCdD�Z5dEdF�Z6dGdH�Z7dIdJ�Z8�dPdLdM�Z9�dPdNdO�Z:�dPdPdQ�Z;�dNdRdS�Z<�dQdUdV�Z=dWdX�Z>dYdZ�Z?d[d\�Z@e@fZAeAZBeAZCeAZDd]d^�ZEeEfZFeFZGeFZHeFZId_d`�ZJeJfZKeKZLeKZMeKZNdadb�ZOeOe-fZPdcdd�ZQdedf�ZRdgdh�ZSdidj�ZTdkdl�ZUdmdn�ZVdodp�ZWeWfZXdqdr�ZYeYe'e&fZZdsdt�Z[dudv�Z\dwdx�Z]dydz�Z^e^fZ_e_Z`d{d|�Zad}d~�Zbdd��Zceae'd�d�fZdedZeeae'd�d�fZfefZgd�d��Zhd�d��ZiehfZjejZkd�d��Zlele&fZmemZnd�d��Zoeoe&fZpepZqd�d��Zrere'e&fZsesZtd�d��Zueue&fZvevZwd�d��Zxexe&fZyeyZzd�d��Z{d�d��Z|d�d��Z}e{e'e'd�d�fZ~e~Ze{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'e5e6e/fZ�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��dRd�dĄZ�e�e7e0fZ�d�dƄZ��dNd�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ƐdR�d�d�Z�e�e1e2fZȐd�d�Zɐd�d�ZʐdS�d�d�ZːdS�d�d�Z̐dS�d�d �Z͐dS�d!�d"�ZΐdS�d#�d$�ZϐdS�d%�d&�ZАdS�d'�d(�ZѐdS�d)�d*�ZҐdS�d+�d,�ZӐdS�d-�d.�ZԐd/�d0�ZՐd1�d2�Z֐dR�d3�d4�Z�e�e1e-e3fZؐd5�d6�Zِd7�d8�ZڐdR�d9�d:�Z�e�e1e&fZܐd;�d<�Zݐd=�d>�Zސd?�d@�ZߐdA�dB�Z�dC�dD�Z�dE�dF�Z�e�e-e4fZ�dG�dH�Z�dI�dJ�Z�dK�dL�Z�dS(T�IMAP4Serverz�
    Protocol implementation for an IMAP4rev1 server.

    The server can be in any of four states:
        - Non-authenticated
        - Authenticated
        - Selected
        - Logout
    sTwisted IMAP4rev1 Ready�<iFNi>�OR�NOT�UID�unauthr�cCs4|duri}||_||_|durt}||_g|_dSrm)�challengers�ctx�iterateInReactor�
_scheduler�_queuedAsync)rZ�chal�contextFactory�	schedulerr=r=rAr]�s
zIMAP4Server.__init__cCsZdt|j���i}|jr#|jr#|js#t�|jd�dur#d|d<d|d<d|d<d|d<|S)N�AUTH�
LOGINDISABLED�STARTTLSr�sIDLE)	rVr��keysr��canStartTLS�
startedTLSr�
ISSLTransportr�)rZ�capr=r=rA�capabilities�s�zIMAP4Server.capabilitiescCs2i|_t�|jd�du|_|�|j�|��dSrm)�tagsr�
ITLSTransportr�r�
setTimeout�timeOut�sendServerGreetingr^r=r=rA�connectionMade�szIMAP4Server.connectionMadecCs&|�d�|jr|��d|_dSdSrm)r�	_onLogout)rZ�reasonr=r=rA�connectionLost�s


�zIMAP4Server.connectionLostcCs\|�d�|j��|jr)|j�|�t|jd�}|dur&t|j��t	j
�d|_d|_dS)Ns** BYE Autologout; connection idle too long�timeout)�sendLiner��loseConnection�mbox�removeListener�ICloseableMailboxr�close�
addErrbackr4�err�state)rZ�cmbxr=r=rA�timeoutConnection�s


zIMAP4Server.timeoutConnectioncCs.|��|j�|�}|dur|�|�dSdSrm)�resetTimeout�_pendingLiteralr��setLineModer�r=r=rA�rawDataReceived�s
�zIMAP4Server.rawDataReceivedcCsV|j}d|_|r|jdur|�|�d��|r|jdus
|jdur)|j�|�dSdSr�)�blocked�lineReceived�poprr)rZ�commandsr=r=rA�_unblock�s�
�zIMAP4Server._unblockc
Cs�|jdur
|j�|�dS|��t|d|j�}z||�WdStyB}z|�dtt|���t	�
�WYd}~dSd}~ww)N�parse_sBAD Server error: )r#rlr�getattr�
parseState�	Exception�sendUntaggedResponser:r�r4r)rZr��f�er=r=rAr$�s
��zIMAP4Server.lineReceivedc
CsB|�dd�}d}t|�dkr|\}}}n%t|�dkr|\}}nt|�dkr1|d}|�|d�dS|�dd�dS|��}z|�|||�WStyd}z|�|dtt|���WYd}~dSd}~wty�}z|�	|dtt|���WYd}~dSd}~wt
y�}z|�	|d	tt|���WYd}~dSd}~ww)
Nr��r;rsMissing commandsNull command�Illegal syntax: �Illegal operation: �Illegal mailbox name: )�splitr��sendBadResponse�upper�dispatchCommandrr:r�r�sendNegativeResponser)rZr�r��restr��cmdr.r=r=rA�
parse_command�s:
&������zIMAP4Server.parse_commandcCs |j}d|_d|_|�|�dS)Nr�)r r*r�)rZr�r�r=r=rA�
parse_pending�szIMAP4Server.parse_pendingcCsN|�|�}|r|d}|dd�}|�||||g|||�dS|�|d�dS)Nrr;sUnsupported command)�
lookupCommand�_IMAP4Server__doCommandr4)rZr�r9r8�uidr-�fn�	parseargsr=r=rAr6s
zIMAP4Server.dispatchCommandcCs t|d�|jt|���f�d�S)N�_)r)r�rr9r5)rZr9r=r=rAr<	s zIMAP4Server.lookupCommandc		Cs�t|�D],\}}t|�r+||dd�}t|||��|j|||||��|j|�dS|�|�q|r;tdt	|���|durH||d|i�dS||�dS)Nr;z Too many arguments for command: r>)
ra�callabler�addCallback�_IMAP4Server__cbDispatchr�_IMAP4Server__ebDispatchrlr�repr)	rZr��handlerr�r@r�r>rc�argr=r=rA�__doCommands�zIMAP4Server.__doCommandc	Cs*|\}}|�|�|�||||||�dSrm)rlr=)	rZ�resultr�r?r�r@r>rHr8r=r=rA�__cbDispatch s
zIMAP4Server.__cbDispatchcCs�|�t�r|�|dtt|j���dS|�t�r(|�|dtt|j���dS|�t�r<|�|dtt|j���dS|�|dtt|j���t	�
|�dS)Nr0r1r2�Server error: )�checkrr4r:r�rbrr7rr4r�rZ�failurer�r=r=rA�__ebDispatch%s 
�
�
��zIMAP4Server.__ebDispatchcCsR||jkr
td|jf��t��}d|_t||�|_|�td|��|�	�|S)Nz,Literal too long! I accept at most %d octets�pendingzReady for %d octets of text)
�_literalStringLimitrr
�Deferredr*r�r �sendContinuationRequestr:�
setRawMode�rZr�r�r=r=rA�_stringLiteral8s
��
�zIMAP4Server._stringLiteralcCs8t��}d|_t||�|_|�td|��|��|S)NrQzReady for %d octets of data)r
rSr*r�r rTr:rUrVr=r=rA�_fileLiteralGs
�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=rA�arg_finalastringQszIMAP4Server.arg_finalastringc	Cs|��}|s
td��d}d\}}|dd�dkr5z|�dd�\}}}|dd�}Wn^ty4td��w|dd�d	krs|d
d�dkrItd��z
t|dd
��}Wntyftd
t|dd
����w|rm|smdS|�|�}n|�dd�}t|�dkr�|�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�{rt�}�Malformed literal�Bad literal size: )r�r�r�r�)	�striprr3r`�intrFrWr�rl)rZr�rYr�rHr8�spamr�r=r=rArZcs8��
zIMAP4Server.arg_astrings
(?P<atom>[s]+)( (?P<rest>.*$)|$)cCs8|std��|j�|�}|r|�d�|�d�fStd��)z-
        Parse an atom from the line
        r\�atomr8zMalformed ATOM)r�atomre�match�group)rZr��mr=r=rA�arg_atom�szIMAP4Server.arg_atomcCs`|std��|dd�dkrtd��|�d�}|dkrtd��t|d|�d	�||d
d�fS)zG
        Parse a (non-nested) parenthesised list from the line
        r\Nr;�(zMissing parenthesis�)rt�Mismatched parenthesisrr�)r�findr�)rZr�rcr=r=rA�	arg_plist�s
"zIMAP4Server.arg_plistcCs�|std��|dd�dkrtd��|dd�dkrtd��z
t|dd��}Wnty:td	|dd�����w|�|�S)
z/
        Parse a literal from the line
        r\Nr;r_zMissing literalrtr`rarb)rrdr`rX)rZr�r�r=r=rA�arg_literal�s�
zIMAP4Server.arg_literalcCst|�}|dfS)z
        searchkeys
        r�)r�)rZr��queryr=r=rA�arg_searchkeys�szIMAP4Server.arg_searchkeysc
Csdd}|�dd�}t|�dkr|d}|d}zt|�|fWSty1}ztdt|���d}~ww)z
        sequence-set
        r�r�r;r�rzBad message number N)r3r��parseIdListrrr�)rZr�r8rHr.r=r=rA�
arg_seqset�s��zIMAP4Server.arg_seqsetcCst�}|�|�|jdfS)z
        fetch-att
        r�)�_FetchParser�parseStringrJ)rZr�r�r=r=rA�arg_fetchatt�s

zIMAP4Server.arg_fetchattcCs�g}|dd�dkr|dd�dkrtd��|dd�}|r]|j�|�}|s*td��|dd�d	krC|��dkrC|�d	|�d
��n|��dkrR|�|�d
��ntd��|�d�}|s|dfS)
z-
        Flag part of store-att-flag
        rr;rlrtNrmrnzMalformed flag�\rfr8r�)rrg�searchr[rlri)rZr��flagsrjr=r=rA�arg_flaglist�s"
�zIMAP4Server.arg_flaglistcCs|dfS)z-
        Command line of UID command
        r�r=r�r=r=rA�arg_line�szIMAP4Server.arg_linecCs|�d�r
|�|�Sd|fS)z-
        Optional parenthesised list
        rlN)�
startswithrpr�r=r=rA�	opt_plists

zIMAP4Server.opt_plistcCsP|�d�r$z|�dd�\}}}Wntytd��w||dd�fSd|fS)z+
        Optional date-time string
        r^r�zMalformed date-timer;N)r~r3r`r)rZr�re�dater8r=r=rA�opt_datetimes
�zIMAP4Server.opt_datetimecCsd|dd���dkr.|�dd�}t|�dkrtd��t|�dkr%|�d�|\}}}||fSd|fS)	z4
        Optional charset of SEARCH command
        N�sCHARSETr�r�r;zMissing charset identifierr�)r5r3r�rrl)rZr�rHrer8r=r=rA�opt_charsets

zIMAP4Server.opt_charsetcCs,dd�|���d|j}|j|d�dS)Ns[CAPABILITY r��] )�message)r��listCapabilities�IDENT�sendPositiveResponse�rZ�msgr=r=rAr*szIMAP4Server.sendServerGreetingr�cC�|�d||�dS)N�BAD��_respond�rZr�r�r=r=rAr4.�zIMAP4Server.sendBadResponsecCr�)Nr�r�r�r=r=rAr�1r�z IMAP4Server.sendPositiveResponsecCr�)N�NOr�r�r=r=rAr74r�z IMAP4Server.sendNegativeResponsecKs@t|fi|��}|r|jdur|�|dd�dS|j�|�dSrm)r6r#r�r�rl)rZr��isAsync�kwargsr=r=rAr,7sz IMAP4Server.sendUntaggedResponse�!Ready for additional command textcCs$|r|�d|�dS|�d�dS)Ns+ �+�rr�r=r=rArT>sz#IMAP4Server.sendContinuationRequestcCsp|dvr|jr|j}g|_|D]	}|�|dd�q|sd}|r,|�d�|||f��dS|�d�||f��dS)N)r�r�r��*r�)r�r�rr�)rZrr�r�r�r�r=r=rAr�DszIMAP4Server._respondcsTdg}|����D]\�}|dur|���q	t|�r'|��fdd�|D��q	|S)Ns	IMAP4rev1csg|]}�d|�qS)�=r=)rCr��cr=rArGW�z0IMAP4Server.listCapabilities.<locals>.<listcomp>)r	�itemsrlr�rr)rZ�caps�vr=r�rAr�Qs�zIMAP4Server.listCapabilitiescCs(|�dd�|����|�|d�dS)NsCAPABILITY r�sCAPABILITY completed)r,r�r�r�r�r=r=rA�
do_CAPABILITYZszIMAP4Server.do_CAPABILITYcCs$|�d�|�|d�|j��dS)NsBYE Nice talking to yousLOGOUT successful)r,r�r�rr�r=r=rA�	do_LOGOUTcs
zIMAP4Server.do_LOGOUTcCs|�|d�dS)NsNOOP No operation performed�r�r�r=r=rA�do_NOOPmr�zIMAP4Server.do_NOOPcCs>|����}||jvr|�|d�dS|�|j|�|�dS)NsAUTHENTICATE method unsupported)r5rcr�r7�authenticate)rZr�r�r=r=rA�do_AUTHENTICATEus
zIMAP4Server.do_AUTHENTICATEcCs*|jdur
|�|d�dS|�||�dS)Ns Temporary authentication failure)�portalr7�_setupChallenge)rZr�r�r=r=rAr�~s
zIMAP4Server.authenticatec
Cs�z|��}Wnty%}z|�|dtt|���WYd}~dSd}~wwt|�dd�}d|_t��|_	|�
|�|j	�|j||�|j	�
|j|�dS)NrLrtrQ)�getChallenger+r4r:r�rr*r
rSr rTrC�_IMAP4Server__cbAuthChunkr�_IMAP4Server__ebAuthChunk)rZr�r��	challenger.�codedr=r=rAr��s&��

zIMAP4Server._setupChallengecCstzt|�}Wntjytd��w|�|�|��r$|�||�dS|j�|dt	��
|j|j|fd|fd�dS)NzMalformed Response - not base64)
r�binascii�Errorr�setResponse�moreChallengesr�r��login�IAccount�addCallbacks�_IMAP4Server__cbAuthResp�_IMAP4Server__ebAuthResp)rZrJr�r��uncodedr=r=rA�
__cbAuthChunk�s�
�zIMAP4Server.__cbAuthChunkcCsH|\}}}|tus
Jd��||_d|_||_|�|d�|�|j�dS)Nz(IAccount is the only supported interface�authsAuthentication successful)r��accountrrr�r�POSTAUTH_TIMEOUT�rZrJr��iface�avatar�logoutr=r=rA�__cbAuthResp�s
zIMAP4Server.__cbAuthRespcCsN|�t�r
|�|d�dS|�t�r|�|d�dS|�|d�t�|�dS)Ns#Authentication failed: unauthorizeds+Authentication failed: server misconfigureds'Server error: login failed unexpectedly)rMrr7rr4r4rrNr=r=rA�__ebAuthResp�s

�zIMAP4Server.__ebAuthRespcC�|�|dtt|j���dS)NsAuthentication failed: )r7r:r�rbrNr=r=rA�
__ebAuthChunk���zIMAP4Server.__ebAuthChunkcCs�|jr|�|d�dS|jr?|jr?|�|d�|j�|j�d|_|j��|_d|jvr1t	|jd<d|jvr=t
|jd<dSdS|�|d�dS)NsTLS already negotiatedsBegin TLS negotiation nowT�LOGINsPLAINsTLS not available)rr7r�rr�r��startTLSr��copyrrr�r=r=rA�do_STARTTLS�s


�zIMAP4Server.do_STARTTLScCsBd|��vr|�|d�dSt|j||��|j|��|j|�dS)Nrs!LOGIN is disabled before STARTTLS)r	r4r�authenticateLoginrC�_IMAP4Server__cbLoginr�_IMAP4Server__ebLogin)rZr��user�passwdr=r=rA�do_LOGIN�s�zIMAP4Server.do_LOGINcCs$|jr|j�t�||�dt�St��)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�r
�UsernamePasswordr�r)rZr�r�r=r=rAr��s
�zIMAP4Server.authenticateLogincCsb|\}}}|tur|�|d�t�d|�d��dS||_||_|�|d�d|_|�|j	�dS)Ns-Server error: login returned unexpected valuez__cbLogin called with z, IAccount expectedsLOGIN succeededr�)
r�r4r4rr�rr�rrr�r�r=r=rA�	__cbLogin�s
zIMAP4Server.__cbLogincCsB|�t�r
|�|d�dS|�|dtt|j���t�|�dS)NsLOGIN failedrL)	rMrr7r4r:r�rbr4rrNr=r=rA�	__ebLogin�s
�zIMAP4Server.__ebLogincCs`d}}}t|jd�}|dur|��}|��}|��}|�dt|||g��|�|d�dS)Ns
NAMESPACE sNAMESPACE command completed)r0r��getPersonalNamespaces�getSharedNamespacesr,�collapseNestedListsr�)rZr��personal�public�shared�npr=r=rA�do_NAMESPACE�s�zIMAP4Server.do_NAMESPACEcCs||jr"|j�|�t|jd�}|durt|j��tj�d|_d|_t	|�}t|j
jt	|�|��|j
||��|j||�dS)Nr�)rrrrrrr4rr�
_parseMboxr��selectrC�
_cbSelectWork�
_ebSelectWork)rZr��name�rw�cmdNamerr=r=rA�_selectWorks�zIMAP4Server._selectWorkcCs|�||d�t�|�dS)Ns failed: Server error�r4r4r)rZrOr�r�r=r=rAr�szIMAP4Server._ebSelectWorkcCs�|dur|�|d�dSddd�|��D�vr|�|d�dSdd�|��D�}|�d|��f�|�d|��f�|�d	d
�|�d�|�dd|��f�|��rYd
pZd}|�	|�|�|d|d|d�d|_
||_dS)NsNo such mailboxz	\noselectcS�g|]}|���qSr=)�lower�rCr�r=r=rArG$�z-IMAP4Server._cbSelectWork.<locals>.<listcomp>zMailbox cannot be selectedcS�g|]}t|��qSr=�r:�rC�flagr=r=rArG(r��	%d EXISTS�	%d RECENT�FLAGS (r�rms[UIDVALIDITY %d]r�r��[r�s successfulr�)r7�getFlagsr,�getMessageCount�getRecentCountr�r��getUIDValidity�isWriteable�addListenerrr)rZrr�r�r{r�r=r=rAr� s 

zIMAP4Server._cbSelectWorkr;�SELECTr�EXAMINEcCs"|�d�||_|j|_d|_dS)N�idle)rT�parseTagr*�	lastStater�r=r=rA�do_IDLE:s

zIMAP4Server.do_IDLEcGs"|j|_|`|�|jd�|`dS)NsIDLE terminated)r�r*r�r�)rZr�r=r=rA�
parse_idle@szIMAP4Server.parse_idlec
Cs�t|�}z|j�|�}Wn0ty)}z|�|tt|���WYd}~dSd}~wty<|�|d�t	�
�YdSw|rG|�|d�dS|�|d�dS)Ns/Server error encountered while creating mailboxsMailbox createdsMailbox not created)r�r��createrr7r:r��
BaseExceptionr4r4rr�)rZr�r�rJr�r=r=rA�	do_CREATEIs"���zIMAP4Server.do_CREATEc
Cs�t|�}|��dkr|�|d�dSz|j�|�Wn1ty8}z|�|t|��d��WYd}~dSd}~wtyK|�	|d�t
��YdSw|�|d�dS)N�inboxsYou cannot delete the inbox�imap4-utf-7s/Server error encountered while deleting mailboxsMailbox deleted)
r�r�r7r��deleterr��encoder�r4r4rr��rZr�r�rjr=r=rA�	do_DELETE]s $���zIMAP4Server.do_DELETEc
Cs�dd�||fD�\}}|��dks|��dkr|�|d�dSz	|j�||�Wn?ty8|�|d�YdStyT}z|�|tt|���WYd}~dSd}~wt	yg|�|d�t
��YdSw|�|d�dS)Ncs��|]}t|�VqdSrm)r�)rC�nr=r=rAr�r��z(IMAP4Server.do_RENAME.<locals>.<genexpr>r�s@You cannot rename the inbox, or rename another mailbox to inbox.sInvalid command syntaxs/Server error encountered while renaming mailboxsMailbox renamed)
r�r7r��renamernr4rr:r�r�r4rr�)rZr��oldname�newnamerjr=r=rA�	do_RENAMEqs(�"���zIMAP4Server.do_RENAMEc
C�t|�}z|j�|�Wn0ty)}z|�|tt|���WYd}~dSd}~wty<|�|d�t	�
�YdSw|�|d�dS)Ns5Server error encountered while subscribing to mailboxs
Subscribed)r�r��	subscriberr7r:r�r�r4r4rr�rr=r=rA�do_SUBSCRIBE��"���zIMAP4Server.do_SUBSCRIBEc
Cr
)Ns9Server error encountered while unsubscribing from mailboxsUnsubscribed)r�r��unsubscriberr7r:r�r�r4r4rr�rr=r=rA�do_UNSUBSCRIBE�r
zIMAP4Server.do_UNSUBSCRIBEcCs<t|�}t|�}t|jj||��|j|||��|j|�dSrm)r�rr��
listMailboxesrC�_cbListWorkr�_ebListWork)rZr��refr�subr�r=r=rA�	_listWork�s
�zIMAP4Server._listWorkc
Cs||D]1\}}|r|j�|�r3dd�|��D�}|���d�}t|�tt|�||�d�f}	|�t|	��q|�	||d�dS)NcSr�r=r�r�r=r=rArG�r�z+IMAP4Server._cbListWork.<locals>.<listcomp>r�s
 completed)
r��isSubscribedr��getHierarchicalDelimiterr�DontQuoteMe�mapr,r�r�)
rZ�	mailboxesr�rr�r��boxr{�delim�respr=r=rAr�s��zIMAP4Server._cbListWorkcC�|�|d�t�|�dS)Ns1Server error encountered while listing mailboxes.r�rNr=r=rAr��zIMAP4Server._ebListWorkr�r�cCsPg}|D]	}|�t|��qt|�}t|jj|d��|j|||��|j	|�dSr�)
rlr9r�rr�r�rC�_cbStatusGotMailboxr�_ebStatusGotMailbox)rZr��mailboxr��nativeNamesr�r=r=rA�	do_STATUS�s
�zIMAP4Server.do_STATUScCs@|rt|j|��|j|j||fd||fd�dS|�|d�dS)NsCould not open mailbox)r�
requestStatusr��_IMAP4Server__cbStatus�_IMAP4Server__ebStatusr7)rZrr�r"r�r=r=rAr �s�	zIMAP4Server._cbStatusGotMailboxcCr�Ns/Server error encountered while opening mailbox.r�rNr=r=rAr!�rzIMAP4Server._ebStatusGotMailboxcCsLtd�dd�|��D���}|�d|�d�d|d�|�|d�dS)	N� cSsg|]}d|�qS)z%s %sr=�rCrOr=r=rArG�r�z*IMAP4Server.__cbStatus.<locals>.<listcomp>�STATUS r�� (rmsSTATUS complete)r:r�r�r,rr�)rZ�statusr�rr�r=r=rA�
__cbStatus�s
�zIMAP4Server.__cbStatuscCs&|�|d|dtt|j���dS)Nr+s	 failed: �r4r:r�rb)rZrOr�rr=r=rA�
__ebStatus�s�zIMAP4Server.__ebStatuscCs4t|�}t|jj|��|j||||��|j|�dSrm)r�rr�r�rC�_cbAppendGotMailboxr�_ebAppendGotMailbox)rZr�r"r{r�r�r=r=rA�	do_APPEND��
�zIMAP4Server.do_APPENDcCsR|s
|�|d�dSdd�|D�}|�|||�}|�|j||�|�|j|�dS)NzRYCREATE] No such mailboxcSr�r=�r9r�r=r=rArGr�z3IMAP4Server._cbAppendGotMailbox.<locals>.<listcomp>)r7�
addMessagerC�_IMAP4Server__cbAppendr�_IMAP4Server__ebAppend)rZrr�r{r�r��decodedFlagsr�r=r=rAr1�szIMAP4Server._cbAppendGotMailboxcCrr(r�rNr=r=rAr2rzIMAP4Server._ebAppendGotMailboxcCs$|�d|��f�|�|d�dS)Nr�sAPPEND complete)r,r�r�)rZrJr�rr=r=rA�
__cbAppend
szIMAP4Server.__cbAppendcCr�)NsAPPEND failed: r/rNr=r=rA�
__ebAppendr�zIMAP4Server.__ebAppendcCs>|��}|dur|�d|�dS|j|j|j|f|fd�dS)N)�callbackArgs�errbackArgs)�
checkpoint�_IMAP4Server__cbCheckr��_IMAP4Server__ebCheck�rZr�r�r=r=rA�do_CHECKs
�zIMAP4Server.do_CHECKcCs|�|d�dS)NsCHECK completedr��rZrJr�r=r=rA�	__cbCheck!r�zIMAP4Server.__cbCheckcCr�)NsCHECK failed: r/rNr=r=rA�	__ebCheck$�zIMAP4Server.__ebCheckcC�dS)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=r^r=r=rAr>'s	zIMAP4Server.checkpointcs�d}|j��r
t|jj�}t|jd���dur*|dur%|��fdd��nt�j�}|dur>|�|j|j	|fd|fd�dS|�d|�dS)Nc����Srm)r)rJ�rr=rArP9rQz&IMAP4Server.do_CLOSE.<locals>.<lambda>)
rr�r�expungerrCrr��_IMAP4Server__cbClose�_IMAP4Server__ebCloserAr=rIrA�do_CLOSE2s

 zIMAP4Server.do_CLOSEcCs(|�|d�|j�|�d|_d|_dS)NsCLOSE completedr�)r�rrrrCr=r=rA�	__cbCloseCs
zIMAP4Server.__cbClosecCr�)NsCLOSE failed: r/rNr=r=rA�	__ebCloseIrFzIMAP4Server.__ebClosecCsB|j��rt|jj��|j|j|fd|fd�dS|�|d�dS)Ns$EXPUNGE ignored on read-only mailbox)rr�rrJr��_IMAP4Server__cbExpunge�_IMAP4Server__ebExpunger7r�r=r=rA�
do_EXPUNGELs

�zIMAP4Server.do_EXPUNGEcCs*|D]
}|�d|f�q|�|d�dS)Ns
%d EXPUNGEsEXPUNGE completed)r,r�)rZrJr�r.r=r=rA�__cbExpungeVszIMAP4Server.__cbExpungecC�(|�|dtt|j���t�|�dS)NsEXPUNGE failed: �r4r:r�rbr4rrNr=r=rA�__ebExpunge[��zIMAP4Server.__ebExpungecCs|t|jd�}|dur!t|j||d��|j||j|��|j|�dStd�}t|jj	||d��|j
||j||��|j|�dS)N�r>s1:*)�ISearchableMailboxrrrzrC�_IMAP4Server__cbSearchr�_IMAP4Server__ebSearchrt�fetch�_IMAP4Server__cbManualSearch)rZr��charsetrrr>�smr�r=r=rA�	do_SEARCHas��zIMAP4Server.do_SEARCHcCsF|rt|j|�}td�dd�|D���}|�d|�|�|d�dS)Nr)cSr�r=r��rCrcr=r=rArGtr�z*IMAP4Server.__cbSearch.<locals>.<listcomp>�SEARCH �SEARCH completed)r�getUIDr:r�r,r�)rZrJr�rr>�idsr=r=rA�
__cbSearchqs
zIMAP4Server.__cbSearchc

Cs�|durg}d}|o|dd}|o|dd��}	tttd�|��D] \}\}
}|�t�|�|
|||	�rC|�d|r>|��n|
f�q#|dkrcddlm	}|�
d|jt|dd��|||||�dS|ro|�d	d
�
|��|�|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.
        Nrrtr;�s%d���reactorrbr�rc)rdrV�zip�range�
_searchFilterr��deepcopyrl�twisted.internetrj�	callLaterr]r,r�r�)
rZrJr�rrrr>�
searchResultsrc�lastSequenceId�
lastMessageId�msgIdr�rjr=r=rA�__cbManualSearchxs4���zIMAP4Server.__cbManualSearchcCs"|r|�|||||�s
dS|sdS)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)rZrr�idr�rrrsr=r=rArm�s
��zIMAP4Server._searchFiltercCs�|�d�}t|t�r|�|||||�sdSdS|��}|dd���s,t||�}||vSt|dt|�d�}	|	durBt	dt|���||j
vrQ|	|||||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;�search_zInvalid search command %sT)r%rUrVrmr5�isalphartr)r9r�_requiresLastMessageInfo)rZrrrtr�rrrs�qr��
messageSetr-rJr=r=rArw�s(

�

�
zIMAP4Server._singleSearchStepcCrG)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=�rZrrrxr�r=r=rA�
search_ALLszIMAP4Server.search_ALLcC�d|��vS)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=rA�search_ANSWEREDszIMAP4Server.search_ANSWEREDcC�0|�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�rrt��
getHeaders�getr�ror%)rZrrrxr�r�r=r=rA�
search_BCCszIMAP4Server.search_BCCcCs&t|�d��}tj�t|����|kSr�)�	parseTimer%�email�utils�	parsedater9�getInternalDate�rZrrrxr�r�r=r=rA�
search_BEFORE,szIMAP4Server.search_BEFOREcC� |�d���}t�||��d�S�NrF�r%r�r5�strFile�getBodyFile�rZrrrxr��bodyr=r=rA�search_BODY0szIMAP4Server.search_BODYcCr�)NF�ccr�rrtr�)rZrrrxr�r�r=r=rA�	search_CC4�zIMAP4Server.search_CCcCr��Nz\Deletedr�r~r=r=rA�search_DELETED8�zIMAP4Server.search_DELETEDcCr��Nz\Draftr�r~r=r=rA�search_DRAFT;r�zIMAP4Server.search_DRAFTcCr��Nz\Flaggedr�r~r=r=rA�search_FLAGGED>r�zIMAP4Server.search_FLAGGEDcCr�)NF�fromr�rrtr�)rZrrrxr��fmr=r=rA�search_FROMAr�zIMAP4Server.search_FROMcCs>|�d���}|�d|��|d�}|���|�d����dkS)NrFr�rt)r%r�r�r�ro)rZrrrxr��hdrr=r=rA�
search_HEADEREszIMAP4Server.search_HEADERcC�|�d�dSr��r%r~r=r=rA�search_KEYWORDJ�
zIMAP4Server.search_KEYWORDcCst|�d��|��kSr��rdr%�getSizer~r=r=rA�
search_LARGERN�zIMAP4Server.search_LARGERcCsd|��vod|��vS)N�\Recent�\Seenr�r~r=r=rA�
search_NEWQszIMAP4Server.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.
        rv)rZrrrxr��lastIDsrrrsr=r=rA�
search_NOTTszIMAP4Server.search_NOTcC�d|��vS�Nr�r�r~r=r=rA�
search_OLDjr�zIMAP4Server.search_OLDcCs"t|�d��}tj�|���|kSr��r�r%r�r�r�r�r�r=r=rA�	search_ONm�zIMAP4Server.search_ONc	Cs4|\}}|�|||||�}|�|||||�}|p|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.
        rv)	rZrrrxr�r�rrrs�a�br=r=rA�	search_ORqszIMAP4Server.search_ORcCr�r�r�r~r=r=rA�
search_RECENT�r�zIMAP4Server.search_RECENTcCr��Nr�r�r~r=r=rA�search_SEEN�r�zIMAP4Server.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}
        Fr�r�r�r�r�r�r�r�r�r%r�r=r=rA�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}
        Fr�r�Nr/rr�r�r=r=rA�
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}
        Fr�r�rr�r�r=r=rA�search_SENTSINCE�szIMAP4Server.search_SENTSINCEcCs"t|�d��}tj�|���|kSr�r�r�r=r=rA�search_SINCE�r�zIMAP4Server.search_SINCEcCst|�d��|��kSr�r�r~r=r=rA�search_SMALLER�r�zIMAP4Server.search_SMALLERcCr�)NF�subjectr�rrtr�)rZrrrxr��subjr=r=rA�search_SUBJECT�r�zIMAP4Server.search_SUBJECTcCr�r�r�r�r=r=rA�search_TEXT�szIMAP4Server.search_TEXTcCr�)NF�tor�rrtr�)rZrrrxr�r�r=r=rA�	search_TO�r�zIMAP4Server.search_TOc	Cs(|\}}|�d�}t||�}|��|vS)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)r%rtrd)	rZrrrxr�r�rrrsr�rjr=r=rA�
search_UID�s

zIMAP4Server.search_UIDcCr�)Nr�r�r~r=r=rA�search_UNANSWERED�r�zIMAP4Server.search_UNANSWEREDcCr�r�r�r~r=r=rA�search_UNDELETED�r�zIMAP4Server.search_UNDELETEDcCr�r�r�r~r=r=rA�search_UNDRAFT�r�zIMAP4Server.search_UNDRAFTcCr�r�r�r~r=r=rA�search_UNFLAGGED�r�zIMAP4Server.search_UNFLAGGEDcCr�r�r�r~r=r=rA�search_UNKEYWORD�r�zIMAP4Server.search_UNKEYWORDcCr�r�r�r~r=r=rA�
search_UNSEEN�r�zIMAP4Server.search_UNSEENcCrT)NsSEARCH failed: rUrNr=r=rA�
__ebSearchrWzIMAP4Server.__ebSearchcCsT|r"|�d�|_t|jj||d��t��|j|||��|j	|�dS|�
|d�dS)NrXsFETCH complete)r�_oldTimeoutrrr\rC�iter�_IMAP4Server__cbFetchr�_IMAP4Server__ebFetchr�)rZr��messagesrrr>r=r=rA�do_FETCHs��zIMAP4Server.do_FETCHcs��jdurg�_zt��\}}Wnty,���j��`���d����YdSw��||���������fdd���	�j
�dS)NsFETCH completedcs�������Srm)r��rA�rr�resultsrZr�r>r=rArP4sz'IMAP4Server.__cbFetch.<locals>.<lambda>)r#�next�
StopIterationrr�r�r'�spewMessagerCr�_IMAP4Server__ebSpewMessage)rZr�r�rrr>rxr�r=r�rA�	__cbFetchs
��zIMAP4Server.__cbFetchcCst�|�|j��dSrm)r4rr�r�rZrOr=r=rA�__ebSpewMessage7s
zIMAP4Server.__ebSpewMessagecCs*|dur|jj}|dtt|�g��dS)Ns	ENVELOPE )r�r�r��getEnvelope�rZrxr��_w�_fr=r=rA�
spew_envelope?szIMAP4Server.spew_envelopecCs<|dur|jj}dd�|��D�}|dd�|�d�dS)NcSr�r=r�r�r=r=rArGGr�z*IMAP4Server.spew_flags.<locals>.<listcomp>r�r�rm)r��writenr�r�)rZrxr�r�r��encodedFlagsr=r=rA�
spew_flagsDszIMAP4Server.spew_flagsc
Cs�|dur|jj}|��}tj�t|��}|dur&t�d|||f�t	d��t
�d|dd��}t|t
|df�}|ddurF|d}n&|ddkrOd}	nd	}	||	d
t|d�ddt|d�dd
f}|dt|��dS)Nz$%d:%r: unpareseable internaldate: %rz(Internal failure generating INTERNALDATEz%d-%%s-%Y %H:%M:%S �	r;s+0000rr��-s%04di�dr�s
INTERNALDATE )r�r�r�r�r��parsedate_tzr9r4r�r�time�strftimer:�_MONTH_NAMES�abs�_quote)
rZrxr�r�r��idate�ttup�strdate�odate�signr=r=rA�spew_internaldateJs.
�(���zIMAP4Server.spew_internaldatecCs2|dur|jj}t|�d��}|dt|��dS)NTsRFC822.HEADER )r�r��_formatHeadersr��_literal)rZrxr�r�r��hdrsr=r=rA�spew_rfc822headereszIMAP4Server.spew_rfc822headercCs2|dur|jj}|d�|�t|����|j�S)NsRFC822.TEXT )r�r��FileProducerr��beginProducingr�r=r=rA�spew_rfc822textks
zIMAP4Server.spew_rfc822textcC�&|dur|jj}|d|��f�dS)NsRFC822.SIZE %d)r�r�r�r�r=r=rA�spew_rfc822sizer�zIMAP4Server.spew_rfc822sizecCsZ|dur|jj}|d�|�t|d�}|dur"t|����|j�St|d|j��|j�S)NsRFC822 )r�r��IMessageFiler�openr�MessageProducerr�)rZrxr�r�r��mfr=r=rA�spew_rfc822ws
�zIMAP4Server.spew_rfc822cCr)NsUID %d)r�r�rdr�r=r=rA�spew_uid�rzIMAP4Server.spew_uidcCs|dtt|d�g��dS)NsBODYSTRUCTURE T)r��getBodyStructurer�r=r=rA�spew_bodystructure�szIMAP4Server.spew_bodystructurec	Csp|dur|jj}|jD]}|��r|�|�}q|dkrtd��q|jrB|j|jjg|jj	�R�}t
|�}||��dt|��dS|j
rZ||��d�|�t|����|j�S|jrrt
|�d��}||��dt|��dS|jr�||��d�|�|jr�t|����|j�St|d�}|dur�t|����|j�St|d|j��|j�S|dtt|�g��dS)Nrz*Requested subpart of non-multipart messager�TsBODY )r�r��part�isMultipart�
getSubPartrn�headerr��negate�fieldsr��	__bytes__r�r5rr�r�mime�emptyrrr	r�r�r
)	rZrrxr�r�r�r�r�r
r=r=rA�	spew_body�s>
�
�zIMAP4Server.spew_bodyc
sft�j�}|j�	|j���	fdd���	fdd���	fdd������������	f
dd�}��|��S)	Ncs�d�f�dS)Ns* %d FETCH (r=r=)rxr�r=rAr[�r�z&IMAP4Server.spewMessage.<locals>.startc��d�dS)Ns)
r=r=�r�r=rAr��r�z'IMAP4Server.spewMessage.<locals>.finishcrr�r=r=rr=rA�space�r�z&IMAP4Server.spewMessage.<locals>.spacec3s��d}���D]2}|jdkrd}|jdkr!��|���	��Vnt�d|j�}|���	��V|�dur:��q�rK|sK�������	��V����dS)NFr>Tr��spew_rt)�typerr)r)�seenUIDrr-�
r�r�rxr�rrrZrr[r>r�r=rA�spew�s$�

�
z%IMAP4Server.spewMessage.<locals>.spew)r�r�r�r�r�)rZrxr�rrr>�wbufr r=rrAr��s
zIMAP4Server.spewMessagecCs8|�|j�|`t�|�|�|dtt|j���dS)NsFETCH failed: )rr�r4rr4r:r�rbrNr=r=rA�	__ebFetch�s
zIMAP4Server.__ebFetchcCs~|��}|�d�}|�d�rd}n
|�d�rd}nd}dd�|D�}t|jj||||d	��|j|j||j||fd|fd�dS)
NsSILENTr�r;r�rtrcSr�r=r5r�r=r=rArG�r�z(IMAP4Server.do_STORE.<locals>.<listcomp>rX)	r5�endswithr~rr�storer��_IMAP4Server__cbStore�_IMAP4Server__ebStore)rZr�r��moder{r>�silentr=r=rA�do_STORE�s 


�zIMAP4Server.do_STOREc
Csl|r.|s.|��D]%\}}|rd|�|�f}nd}dd�|D�}	|�d|d�|	�|f�q|�|d�dS)Ns UID %dr�cSr�r=r�r�r=r=rArG�r�z)IMAP4Server.__cbStore.<locals>.<listcomp>s%d FETCH (FLAGS (%b)%b)r�sSTORE completed)r�rdr,r�r�)
rZrJr�rr>r(�kr��uidstrr{r=r=rA�	__cbStore�s�zIMAP4Server.__cbStorecCr��NrLr/rNr=r=rA�	__ebStore�rFzIMAP4Server.__ebStorecCs4t|�}t|jj|��|j||||��|j|�dSrm)r�rr�r�rC�_cbCopySelectedMailboxr�_ebCopySelectedMailbox)rZr�r�r"r>r=r=rA�do_COPY	r4zIMAP4Server.do_COPYcCsN|s|�|d|�dSt|jj||��|j||��|j||��|j|�dS)NzNo such mailbox: )	r7rrr\rC�_IMAP4Server__cbCopy�_IMAP4Server__cbCopiedr�_IMAP4Server__ebCopy)rZrr�r�r"r>r=r=rAr/		s�z"IMAP4Server._cbCopySelectedMailboxcCr�r-r/rNr=r=rAr0	rFz"IMAP4Server._ebCopySelectedMailboxcs�g}t�d�}|D]U\}}|durt|j|�}|�|�q	|��}	|��}
t|d�}|dur;|��}t�j||	|
�}ndd��t	�
�}
t||
|j��
d��|
|	|
f��fdd�	�}|�|�q	t�|�S)NcSs|�d�|Sr�)r��r-r=r=rA�rewind+	r�z$IMAP4Server.__cbCopy.<locals>.rewindcs���|�||�Srm)r6)rAr�r-r��rr6r=rArP4	s
�z&IMAP4Server.__cbCopy.<locals>.<lambda>)�IMessageCopierrr�rlr�r�rrr6r�r�r	r�rrCr
�DeferredList)rZr�r�r�addedDeferreds�fastCopyMboxrxr�r�r{r�r��bodyFile�bufferr=r7rA�__cbCopy	s.


��	
zIMAP4Server.__cbCopycCsVg}g}|D]\}}|r|�|�q|�|j�q|r#|�|d�dS|�|d�dS)Nz%[ALERT] Some messages were not copiedsCOPY completed)rlrbr7r�)rZ�deferredIdsr�rre�failuresr-rJr=r=rA�
__cbCopied<	szIMAP4Server.__cbCopiedcCrT)NsCOPY failed:rUrNr=r=rA�__ebCopyI	szIMAP4Server.__ebCopycCs.|��}|dvrt|��|j|||dd�dS)N)�COPYr��STOREr�r;rX)r5rr6)rZr�r�r�r=r=rA�do_UIDM	szIMAP4Server.do_UIDcCs(|r|jddd�dS|jddd�dS)Ns[READ-WRITE]T)r�r�s[READ-ONLY]�r,�rZ�	writeabler=r=rA�modeChangedZ	szIMAP4Server.modeChangedcCsD|��D]\}}dd�|D�}d|d�|�f}|j|dd�qdS)NcSr�r=r�r�r=r=rArGb	r�z,IMAP4Server.flagsChanged.<locals>.<listcomp>s%d FETCH (FLAGS (%b))r�T�r�)r�r�r,)rZ�newFlags�mIdr{r�r�r=r=rA�flagsChanged`	s
�zIMAP4Server.flagsChangedcCs@|dur|jd|fdd�|dur|jd|fdd�dSdS)Nr�TrJr�rF�rZ�exists�recentr=r=rA�newMessagesf	s
�zIMAP4Server.newMessages�NNNrm�F�Nr�)r��rr])�r�r�r�r�r�r
r�rrr
r�r�rrr rRr�r{rr*r]r	rrrr"r#r'r$r:r;r6r<r=rDrErWrXr[rZ�re�compile�escape�
_atomCharsrgrkrprqrsrurxr|r}rr�r�rr4r�r7r,rTr�r�r��unauth_CAPABILITY�auth_CAPABILITY�select_CAPABILITY�logout_CAPABILITYr��
unauth_LOGOUT�auth_LOGOUT�
select_LOGOUT�
logout_LOGOUTr��unauth_NOOP�	auth_NOOP�select_NOOP�logout_NOOPr��unauth_AUTHENTICATEr�r�r�r�r�r�r��unauth_STARTTLSr��unauth_LOGINr�r�r�r��auth_NAMESPACE�select_NAMESPACEr�r�r��auth_SELECT�
select_SELECT�auth_EXAMINE�select_EXAMINEr�r��select_IDLE�	auth_IDLEr��auth_CREATE�
select_CREATEr�auth_DELETE�
select_DELETEr	�auth_RENAME�
select_RENAMEr�auth_SUBSCRIBE�select_SUBSCRIBEr�auth_UNSUBSCRIBE�select_UNSUBSCRIBErrr�	auth_LIST�select_LIST�	auth_LSUB�select_LSUBr$r r!�auth_STATUS�
select_STATUSr&r'r3r1r2�auth_APPEND�
select_APPENDr7r8rB�select_CHECKr?r@r>rM�select_CLOSErKrLrR�select_EXPUNGErPrQr`�
select_SEARCHrZr]rmrwrr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r[r��select_FETCHr�r�r�r�r�rrrrrrrr�r�r)�select_STOREr%r&r1�select_COPYr/r0r2r3r4rE�
select_UIDrIrMrQr=r=r=rAr�Us�


	
/�		

	
	
		


	
<0

"&#
(

r�c@sJeZdZdZdZdZdZdZdZdZ	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��ZMdd��d�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�)�OK�NO�BAD�PREAUTH�BYE)�MESSAGES�RECENT�UNSEENcCs.i|_g|_i|_||_d|_d|_d|_dSrm)r
�queued�authenticators�context�_tag�_parts�_lastCmd)rZr�r=r=rAr]�	s
zIMAP4Client.__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��getNamer5)rZr�r=r=rA�registerAuthenticator�	sz!IMAP4Client.registerAuthenticatorcCs�|jdkr	|��|jt|�8_|jdkr|j�|�dSd}|jdkr5|d|j�||jd�}}|j�|�|j}d|_d|_|�dd�|j�|�	��|�
|�d��dS)Nrr��
)rr�_pendingSizer��_pendingBufferr�r�r�rl�readr!�lstrip)rZr�r�r8r=r=rAr"�	s


zIMAP4Client.rawDataReceivedcCsD|�|�|_||_|jdur|dg|_n|j�|dg�|��dS)Nr�)�messageFiler�r�r�rrrU)rZr8�octetsr=r=rA�_setupForLiteral�	s
zIMAP4Client._setupForLiteralcCs|jdkr
|�|j�dSdSr�)rrr^r=r=rAr�	s
�zIMAP4Client.connectionMadecCs�|jdkr
|�d�|jdur |j}d|_|D]}|j�|�q|jdurA|j}d|_|��D]}|dur@|jdur@|j�|�q/dSdS)z,
        We are no longer connected
        rN)rrr�r
�errbackr
�values)rZrr�r9r
r=r=rAr�	s 



��zIMAP4Client.connectionLostcCs�|jdkr	|��|�d�}|dkrN||dd�}|�d�rNz
t|dd��}Wnty4t|��w|jdurD|�dd�\|_	}n|}|�
||�dS|jdurZ|�|�dS|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.
        rr_rtr;Nr`r�)rr�rfindr#rdr`rr�r3r�r��_regularDispatchrlr�r6)rZr��lastPartr��partsr�r8r=r=rAr$�	s,


�

zIMAP4Client.lineReceivedcCsp|jr|jjdur|jjd}|j_|�t�|jr1|jD]}|jdur0|j|}|_|�t�q|j��dSrm)r�r
r��
TIMEOUT_ERRORr�r�r)rZr�r9r=r=rAr
s



�zIMAP4Client.timeoutConnectioncCs:|�dd�}t|�dkr|�d�|\}}|�||�dS)Nr;r�r�)r3r�rlr6)rZr�r�r�r8r=r=rAr�
s

zIMAP4Client._regularDispatchcCs||jkr	t��St�S)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
        )r�r�r�r)rZr�r=r=rAr�!
s
zIMAP4Client.messageFilecCs"d|j�d�}|jd7_|S)Nz%0.4X�asciir;)�tagIDrr�r=r=rA�makeTag1
szIMAP4Client.makeTagcCs�|jdur	|j}nt|d|j��d�}|r2z|||�WdSty1t��|j��YdSwt�d|j�d|�d|���|j��dS)N�	response_zCannot dispatch: z, )	r�response_UNAUTHr)r5r�r4rr�r)rZr�r8r-r=r=rAr66
s
�zIMAP4Client.dispatchCommandcCs�|jdur]|�dd�\}}|��dkrd|_n|��dkr!d|_n
|j��t|d|��|�d�|�d�}}|d	krV|d	krV|�|�t	||d|��gdf��dS|�d�dS|�
||�dS)
Nr;r�r�sPREAUTHr�r�r��]rt)rr3r5r�rrro�serverGreeting�_IMAP4Client__cbCapabilitiesr��_defaultHandler)rZr�r8r-r�r.r=r=rAr�E
s

�zIMAP4Client.response_UNAUTHcCs|�||�dSrm)r�)rZr�r8r=r=rA�
response_AUTH\
r�zIMAP4Client.response_AUTHcCs�|dks|dkr.|js|�t|�g�dS|j|j}|dkr&|�|�dS|j�|�dSz|j|}WntyI|j�	�t
|d|��w|�dd�\}}|dkr^|�||j�n|j
�t|��|j|=d|_|��dS)Nr�r�r�r;r�)�waiting�
_extraInfor�r
r�r�rl�KeyErrorr�rrr3r�r
r�r�_flushQueue)rZr�r8r9r-r�r=r=rAr�_
s(
�zIMAP4Client._defaultHandlercCsB|jr|j�d�}|��}||j|<|�|�|��||_dSdSr�)r�r%r�r
rr�r��rZr9�tr=r=rAr�{
s

�zIMAP4Client._flushQueuec
Cs6i}d}}|D]y}t|�}|dkr|ddgkr|�d�q|dkr0|ddgkr0|�d�q|dkrA|ddkrAt|d�}q|dkrR|dd	krRt|d�}q|d
kry|ddkryt|d�}|�|d�\}}	|�|g��|�dd
��qt�d|���q|r�|�	|�|dus�|dur�|�
||�dSdS)Nr;rr�Fr�Tr�r�r�r/r��FLAGSr=z Unhandled unsolicited response: )r�rIrd�_parseFetchPairs�
setdefaultrrr�r4r�rMrQ)
rZr�r{rPrO�response�elementsrLr�rAr=r=rAr��
s,
�zIMAP4Client._extraInfocCsVt��|_|jr|j�|�|jS|��}||j|<|�|�|��||_||_	|jSrm)
r
rSr�r�rlr�r
rr�r�r�r=r=rA�sendCommand�
s

zIMAP4Client.sendCommandcCsD|r
|jdur
t�|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
�succeedr�r�rCr�)rZ�useCacher9rr�r=r=rA�getCapabilities�
szIMAP4Client.getCapabilitiesc
Cs�|\}}i}|D],}|dd�D]#}|�dd�}t|�dkr&|dd}}	n|\}}	|�|g��|	�qq|D]
}||dgkrDd||<q7||_|S)Nr;r�r)r3r�r�rlr�)
rZrJr��tagliner�r8rr��categoryrbr=r=rA�__cbCapabilities�
s ��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�)r�r�rC�_IMAP4Client__cbLogout�rZr�r=r=rAr��
s
zIMAP4Client.logoutcCs|\}}|j��dSrm)r�r�rZrJr�r�r=r=rA�
__cbLogout�
s
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)r�r�rC�_IMAP4Client__cbNoopr�r=r=rA�noop�
s
zIMAP4Client.noopcCs|\}}|Srmr=r�r=r=rA�__cbNoop�
szIMAP4Client.__cbNoopcs��jrJd��|dur���}|durt�td��Sd�jvr&t�td��St��jd�}|dur8t�td��S��	t
d��}|��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 handshakerz:Server does not support secure communication via TLS / SSLzAIMAP4Client transport does not implement interfaces.ITLSTransportcrHrm�r�r�r^r=rArP1rQz&IMAP4Client.startTLS.<locals>.<lambda>)
r�_getContextFactoryr
�failrr�rrr�r�r�rC�_startedTLS)rZr��tlsr�r=r^rAr�s:����
����zIMAP4Client.startTLScCs2|jdur
|��}nt�|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)r�r�r
r�rC�_IMAP4Client__cbAuthenticate)rZ�secretr�r=r=rAr�4s



zIMAP4Client.authenticatecs�|�dd���D]}|���jvr"td|d�j||�}��|�Sq�jr1t�t	��j�
���S��fdd�}���}|�|�|�
�fdd��|�
�j|�|S)Nrr=�AUTHENTICATEcs |�t�t�t��j����Srm)�traprr
r�r#r�r)r��authsrZr=rA�
ebStartTLSTs
�z0IMAP4Client.__cbAuthenticate.<locals>.ebStartTLScrHrmr�r�r^r=rArP]rQz.IMAP4Client.__cbAuthenticate.<locals>.<lambda>)r�r5r�r��_IMAP4Client__cbContinueAuthr�rr
r�r#rr�rrC�_IMAP4Client__cbAuthTLS)rZr�r��schemer9r�r�r=r�rA�__cbAuthenticateEs$���
zIMAP4Client.__cbAuthenticatecCs`zt|d�}Wntjy|�d�t|��w|j|}|�||�}|�t|����dS)N�
r�)	rr�r�rrr��challengeResponserrc)rZr8r�r�r�r�r=r=rA�__cbContinueAuthas
�
zIMAP4Client.__cbContinueAuthcCsV|�dd�}|D]}|��|jvr"td|d|j||�}|�|�Sqt||j����)Nrr=r�)r�r5r�r�r�r�r#r)rZr�r�r�r�r9r=r=rA�__cbAuthTLSls��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.
        )rr�rC�_IMAP4Client__cbLoginCaps)rZ�username�passwordr�r=r=rAr�vs
zIMAP4Client.logincCrG)z�
        Called when the server has sent us a greeting.

        @type caps: C{dict}
        @param caps: Capabilities the server advertised in its greeting.
        Nr=)rZr�r=r=rAr���zIMAP4Client.serverGreetingcCsL|jdur|jSzddlm}Wn
tyYdSw|��}|jj|_|S)Nr)�ssl)r�ror��ImportError�ClientContextFactory�SSL�TLSv1_METHOD�method)rZr�r�r=r=rAr��s
�
zIMAP4Client._getContextFactoryc	Cs�d|v}t�|jd�du}t�|jd�du}|js1|r1|r1|r1|��}|j|j|j||fd�|S|r8t	�
d�d�t|�t|�f�}|�
td|��S)Nr)r<z5Server has no TLS support. logging in over cleartext!r�r�)rrr�rrr�r��_IMAP4Client__cbLoginTLS�_IMAP4Client__ebLoginTLSr4r�r�r�r�r�)	rZr	r�r��tryTLS�tlsableTransport�nontlsTransportr�r�r=r=rA�
__cbLoginCaps�s�
zIMAP4Client.__cbLoginCapscCs|j�|�d|_d|_|S)NT)r�r�r�r)rZrJr�r=r=rAr��szIMAP4Client._startedTLScCs&d�t|�t|�f�}|�td|��S)Nr�r�)r�r�r�r�)rZrJr�r�r�r=r=rA�__cbLoginTLS�szIMAP4Client.__cbLoginTLScCst�|�|Srm)r4rr�r=r=rA�__ebLoginTLS�r�zIMAP4Client.__ebLoginTLScC�*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�)r�r�rC�_IMAP4Client__cbNamespace�rZr9rr�r=r=rA�	namespace��
zIMAP4Client.namespacecsd|\}}dd��|D]}t|�dkr'|ddkr'�fdd�|dd�D�Sq
t�d	�ggggS)
NcSsdd�|D�S)NcS�g|]}|�d��qS)r�)�decode)rC�elementr=r=rArG�r�zSIMAP4Client.__cbNamespace.<locals>._prepareNamespaceOrDelimiter.<locals>.<listcomp>r=)�
namespaceListr=r=rA�_prepareNamespaceOrDelimiter��z?IMAP4Client.__cbNamespace.<locals>._prepareNamespaceOrDelimiterrhrr�cs*g|]}|dur
gn�fdd�|D��qS)Nc�g|]}�|��qSr=r=)rCrb�r�r=rArG�r�z8IMAP4Client.__cbNamespace.<locals>.<listcomp>.<listcomp>r=)rC�
pairOrNonerr=rArG�s���z-IMAP4Client.__cbNamespace.<locals>.<listcomp>r;z*No NAMESPACE response to NAMESPACE command)r�r4r)rZrJr�r_r�r=rrA�
__cbNamespace�s


��

zIMAP4Client.__cbNamespacecC�6d}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�UIDVALIDITYr�r;��_prepareMailboxNamer�r�rC�_IMAP4Client__cbSelect�rZr"r9r�rr�r=r=rAr��s zIMAP4Client.selectcCr)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�r�rr	rr=r=rA�examine#s zIMAP4Client.examinecCs"zt|�WStyt|��w)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.
        )rdr`r)rZrb�phraser=r=rA�_intOrRaiseQs

�zIMAP4Client._intOrRaisec	Cs�|\}}d|i}|�t|��|D]�}t|�dkr�|d��dkr�|d}t|t�r/|d}n|}|��}|dkr>d|d<q|dkrGd|d<q|d	krV|�|d|�|d
<q|dkre|�|d|�|d<q|d
krt|�|d|�|d<q|dkr�tdd�|dD��|d<qt�	d|���qt|�dkr�|d��dkr�tdd�|dD��|d<qt|dt
�r�|d��dkr�|�|d|�|d<q|d��dkr�|�|d|�|d<qt�	d|���qt�	d|���qt�	d|���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�rr�r�r��UIDNEXTr�csrrmr5r�r=r=rAr�|s�
�z)IMAP4Client.__cbSelect.<locals>.<genexpr>rzUnhandled SELECT response (2): r�r�csrrmr5r�r=r=rAr��rr�r�rr�r�zUnhandled SELECT response (0): zUnhandled SELECT response (1): zUnhandled SELECT response (4): )rlr�r�r5rUrVr�tupler4r�bytes)	rZrJr�r�r��datumr3�contentrgr=r=rA�
__cbSelect\sJ



�zIMAP4Client.__cbSelectcC�|�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�r�r�r
�rZr�r=r=rAr���
zIMAP4Client.createcCr)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.
        sDELETErrr=r=rAr��rzIMAP4Client.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�)r
r�r�r�)rZrrr=r=rAr�szIMAP4Client.renamecCr)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	SUBSCRIBErrr=r=rAr�rzIMAP4Client.subscribecCr)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.
        sUNSUBSCRIBErrr=r=rAr�rzIMAP4Client.unsubscribecCsFd}d|�d|�d��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" "r�)r�r�)rr�r�rC�_IMAP4Client__cbList)rZ�	reference�wildcardr9r�rr�r=r=rArV�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�r�r^s" ")r�r�)rr�r�r�rCr)	rZrrr9�encodedReference�encodedWildcardr�rr�r=r=rA�lsub
s


��	zIMAP4Client.lsubcCs�|\}}g}|D]8}t|�dkr@|d|kr@tdd�|dD��|d<|d�d�|d<|d�d�|d<|�t|dd���q|S)	Nrhrcsrrmr5r�r=r=rAr�+
rz'IMAP4Client.__cbList.<locals>.<genexpr>r;r�r�r/)r�rr�rl)rZrJr�r�r_r�r�r=r=rA�__cbList$
s
�zIMAP4Client.__cbListcCsi|]}||�d��qS)r��r�rCr�r=r=rA�
<dictcomp>?
s
��zIMAP4Client.<dictcomp>�r�r�rrr�cs�d}t|�}zd��fdd�|D��}Wnty)tdt|�t�j�����wd�|d|dg�}d	}��t|||d
��}|��j	�|S)a7
        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|VqdSrm)�_statusNamesr#r^r=rAr�c
s�z%IMAP4Client.status.<locals>.<genexpr>zUnknown names: r�r,rm)r�r�)
r
r�r�r`�setr&r�r�rC�_IMAP4Client__cbStatus)rZr"r�r9�preparedMailboxr�rr�r=r^rAr-J
s�zIMAP4Client.statusc
s�|\}}i}|D]7}|ddkr?|d��fdd�tdt��d�D���D]\}}z||t|�<Wq%ty>tt����wq|��D]3}|j�|�}|rwz
|||�||<WqDt	yv}	ztd|d||dt
|	���d}	~	wwqD|S)	Nrr�r�csg|]
}�||d��qS)r�r=ra�r�r=rArGs
�z*IMAP4Client.__cbStatus.<locals>.<listcomp>�(r)z): )rlr�r9�UnicodeDecodeErrorrrFr�STATUS_TRANSFORMATIONSr�r+r�)
rZrJr�r_r-r�r*r�r�r.r=r*rAr.m
s4������zIMAP4Client.__cbStatusr=c	Cs~|�dd�|��}|�dd�|rtdt|��}nd}dd�|D�}dt|�d�|�||f}|�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"r�cSr�r=r�r�r=r=rArG�
r�z&IMAP4Client.append.<locals>.<listcomp>s%b (%b)%b {%d}r�sAPPENDr=)	r��tellr:r9r
r�r�r��_IMAP4Client__cbContinueAppend)	rZr"r�r{r�r�r�r9r�r=r=rArl�
s"��zIMAP4Client.appendcCs t��}|�||jd��|j�Srm)r2�
FileSender�beginFileTransferr�rC�_IMAP4Client__cbFinishAppend)rZr�r�r�r=r=rA�__cbContinueAppend�
s�zIMAP4Client.__cbContinueAppendcCs|�d�dSrTr�)rZ�foor=r=rA�__cbFinishAppend�
rzIMAP4Client.__cbFinishAppendcC�|�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�r�r�r^r=r=rArM�
s
zIMAP4Client.checkcCr7)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.
        sCLOSEr8r^r=r=rAr�
szIMAP4Client.closecCr�)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�)r�r�rC�_IMAP4Client__cbExpunger�r=r=rArJ�
r�zIMAP4Client.expungecCsH|\}}g}|D]}t|�dkr!|ddkr!|�|�|d|��q|S)Nr�r;r�r)r�rlr)rZrJr�r_rer�r=r=rArS�
s�zIMAP4Client.__cbExpungerXcGsJdd�|D�}|rdnd}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.
        @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.
        cSr�)r�r")rCrrr=r=rArG
r�z&IMAP4Client.search.<locals>.<listcomp>s
UID SEARCHr�r�r�)r�r�r�rC�_IMAP4Client__cbSearch)rZr>�queriesr9r�r�r=r=rArz�
s
zIMAP4Client.searchcsT|\}}g}|D]�t��dkr'�ddkr'|���fdd��dd�D��q|S)Nrr�csg|]}��|���qSr=)r�rCr��r�rZr=rArGr�z*IMAP4Client.__cbSearch.<locals>.<listcomp>r;)r�rr)rZrJr�r\rer=r=rArfs"�zIMAP4Client.__cbSearchcC�|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�rZr�r>r=r=rA�fetchUID�zIMAP4Client.fetchUIDcCr>)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;)r?r{r@rBr=r=rA�
fetchFlags.rDzIMAP4Client.fetchFlagscCr>)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;)r?�internaldater@rBr=r=rA�fetchInternalDateBszIMAP4Client.fetchInternalDatecCr>)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;)r?�enveloper@rBr=r=rA�
fetchEnvelopeW�zIMAP4Client.fetchEnvelopecCr>)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;)r?�
bodystructurer@rBr=r=rA�fetchBodyStructuretrJzIMAP4Client.fetchBodyStructurecCr>)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;)r?r�r@rBr=r=rA�fetchSimplifiedBody�szIMAP4Client.fetchSimplifiedBodycCr>)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;)r?�rfc822r@rBr=r=rA�fetchMessage�szIMAP4Client.fetchMessagecCr>)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;)r?�rfc822headerr@rBr=r=rA�fetchHeaders�rDzIMAP4Client.fetchHeaderscCr>)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;)r?�
rfc822textr@rBr=r=rA�	fetchBody�rDzIMAP4Client.fetchBodycCr>)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;)r?�
rfc822sizer@rBr=r=rA�	fetchSize�rDzIMAP4Client.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;)r?r{rFrTrHr�r@rBr=r=rA�	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;)r?r{rFrTrHr@rBr=r=rA�fetchAlls�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;)r?r{rFrTr@rBr=r=rA�	fetchFast4szIMAP4Client.fetchFastc
s��fdd��i}g}t|�}	zt|�}Wnty!Y||fSwzt|�}Wnty4td|��w|dvr<d}nt|t�sDd}nt|�dkrMd}n|rYt|dt�rYd}nd}t|�}|�|�|r�t|�dkrd	d
�|D�}|�|�|t	|�f}nt|d�}dd
�|dD�}	|�||	g�||t	|	�ff}zt|�}Wnty�td|��w|�
d
�r�|�d�r�z
t|dd��Wn	t
y�Yn"wt|�}|�|�||f}zt|�}Wnty�td|��w�|�}|�|�|||<q)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�r�fdd�|D�SdS)Nr�crr=r=)rC�subthing��nativeStringResponser=rArGur�zNIMAP4Client._parseFetchPairs.<locals>.nativeStringResponse.<locals>.<listcomp>)rUrr�rV)�thingrZr=rAr[qs



�z:IMAP4Client._parseFetchPairs.<locals>.nativeStringResponseTsNot enough arguments)�BODYs	BODY.PEEKFr�rcSr�r=r5�rCr�r=r=rArG�r�z0IMAP4Client._parseFetchPairs.<locals>.<listcomp>cSr�r=r5r^r=r=rArG�r�r;�<�>rt)r�r�r�rrUrVr�r9rlrr~r#rdr`)
rZ�fetchResponseListr��unstructured�
responsePartsrgrb�
hasSection�	valueHead�	valueTailr=rZrAr�Ks~&`�
�


���

��
�zIMAP4Client._parseFetchPairscCs�|\}}i}|D]-}t|�dkr5|ddkr5|�|d|�}||vr*|dg||<q||d�|d�qi}	i}
|��D]"\}}|�|d�\}
}|
�|gg�d�|�|	�|i��|
�q>|
}i}t|	���D]I}|	|}t|���D]<}||vr�|dkr�|d||<t	t||d��D]}||d|dkr�||d||d�=nq�|d=|s�|	|=qwqk|r�|�
|�|r�|	S|S)Nr/r;r�rr�r�)r�rrrr�r�r��updaterVrrlrM)rZrJ�requestedParts�
structuredr�r_�infor�rxr��decodedInfo�	messageIdr��
structuredMap�unstructuredList�flagChangesrrcr=r=rA�_cbFetch�sJ����
zIMAP4Client._cbFetchc	Cs�d}	|dur	d}
nt|t�rt|�}
nd�tt|��}
|dur"d}n	|
r)d|}n|}|r@|dvr@|dur=dd�|�}nd}nd}|durId}
nd	||f}
|rSd
pTd}|	||r[dp\d|
|||
f}|�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]%sNr��.)z
HEADER.FIELDSzHEADER.FIELDS.NOTz (%s)r)z ()z<%d.%d>�	UID FETCHr�z.PEEKr��r�r�r=F)
rUrdr�r�rrr�r�rCrp)rZr�r>�
headerType�headerNumber�
headerArgs�peek�offset�length�fmt�numberr�payload�extrar\r9r�r=r=rA�
fetchSpecifics27



zIMAP4Client.fetchSpecificcKs�t|��d�}|rdpd}d|vr|d=d|d<d|vr#|d=d|d<d	|vr.|d	=d|d
<dd�|D�}|d
d�dd�|D��d}|�t||dd��}|�|jdd�|��D�d�|S)Nr�rrr�rRT�rfc822.textrT�rfc822.sizerP�
rfc822.headercSr�r=r�r�r=r=rArGvr�z&IMAP4Client._fetch.<locals>.<listcomp>r,r�cSr�r=�r5r�r=r=rArGwr�rmrsr�cSr�r=r�)rCr�r=r=rArGzr�)r�rr�r�r�rCrpr)rZr�r?�termsr\�encodedTermsr9r�r=r=rArAes  zIMAP4Client._fetchcC�|�|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�rZr�r{r(r>r=r=rA�setFlags}�zIMAP4Client.setFlagscCr�)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=rA�addFlags�r�zIMAP4Client.addFlagscCr�)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=rA�removeFlags�r�zIMAP4Client.removeFlagscCs�t|��d�}dd�|D�}|r|d}|rdpd}d�||dd�|�d	f�}|�t||d
d��}	d}
|s9d
}
|	�|j|
d�|	S)Nr�cSr�r=r�r�r=r=rArG�r�z&IMAP4Client._store.<locals>.<listcomp>s.SILENTs	UID STORErDr�rlrmrsr�r=)r�T)r�rr�r�r�rCrp)rZr�r9r(r{r>r�r$r�r��expectedr=r=rAr��szIMAP4Client._storecCs>t|��d�}|rd}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 COPYrCr�)r�rr�r
r�r�)rZr�r"r>r9r�r=r=rAr��szIMAP4Client.copycCrG�zOverride meNr=rGr=r=rArI�r�zIMAP4Client.modeChangedcCrGr�r=)rZrKr=r=rArM�r�zIMAP4Client.flagsChangedcCrGr�r=rNr=r=rArQr�zIMAP4Client.newMessagesrm�r;)r=NrU)rNNNNNN)r;r)ir�r�r�r�r
r�r�r�rrrr�r�r��STATUS_CODESrdr.r�r]r�r"r�rrr$rr�r�r�r6r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r
rrr�r�rrrrVr rr&r-r(rlr0r3rMrrJr9rzr:rCrErGrIrLrMrOrQrSrUrVrWrXr�rpr~rAr�r�r�r�r�rIrMrQr=r=r=rAr�p	s�

	*


3
).9#�#
0











 
-
�
Z


 r�c	Cs6t�}|�d�}|D]�}d|vrl|�dd�\}}zH|dkr d}nt|�}|dkr+d}nt|�}||ur<dur=t|��|durE|dksM|durQ|dkrQt|��|pT|}|pX|}|�||�Wq
tykt|��wz|dkrtd}nt|�}|dur�|dkr�t|��Wnty�t|��w|�|p�|�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)rJr3rdrrXr`rr)r�rsrpr�r�rdrer=r=rArtsF
� ���rt)�ALL�ANSWERED�DELETED�DRAFT�FLAGGED�NEW�OLDr��SEEN�
UNANSWERED�	UNDELETED�UNDRAFT�	UNFLAGGEDr�)�LARGER�SMALLER�UIDcKs:g}|��}|rt|�}|D]z}||}|��}|tvr$|r$|�|�q|dkr9|�|t|d�t|d�g�q|dksA|dkrOt�d|�}|�||g�q|t	vrpt
|t�r[d}n
t
|t�rcd}nd}|�|||fg�qt
|t�r�|�|d	|fg�q|�||�g�qt
|�dkr�d
d�|�dSd�|�S)
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
    �HEADERrr;�KEYWORD�	UNKEYWORDr�z"%s"z"%d"z%dr,r)�))r�_sortedr5�_SIMPLE_BOOLrlrrr��
_nonAtomREr�
_NO_QUOTESrUrJrdr�r�)rh�kwargr9rr*r�rzr=r=rA�QueryUs6n"



r�cGsJt|�dkr
t|��t|�dkrd|Sd|d�dt|dd���d�S)	z0
    The disjunction of two or more queries
    r�z
(OR %s %s)z(OR rr)r;Nr�)r�r�Or)r�r=r=rAr��s
"r�cCsd|�d�S)zThe negation of a queryz(NOT r�r=)rrr=r=rA�Not�sr�cCsF|�dd�}|dur|�dd�}n|�ddt�|��}t�|tj�S)Nr�z(?:.*?)�%z(?:(?:[^%s])*?))�replacerVrXrW�I)rrr=r=rA�wildcardToRegexp�s
r�cCst|��}g}g}d}}td|�}td|�}td|�}td|�}tt|��D]t\}	}
|
|krV|	rD||	d|	�|krD|��|�|�q&|sId}q&d}|�|�|��g}q&|sl|sl|
|tj�	d�vrld}|�|
�q&|r�|s�|
tj�	d�vr�|�|�}||kr�|�d	�n|�|�g}d}q&|s�|r�|�|
�q&|r�t
|��|r�|�|�}||kr�|�d	�|S|�|�|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
    Fr�\r��NILr;Tr�N)rcr7rar8r%rlr��string�
whitespacerr )r�rJ�word�inQuote�inWord�qu�escr�nilrcr��wr=r=rA�splitQuotedsX



��


�


�r�cCszg}||d�}|dg}|dd�D]}||�}||kr,|�|||��|g}|}q|�|�q|�|||��|S�Nrr;)rrrl)�sequence�	predicate�transformersrJr'�tmpr.r�r=r=rA�splitOnAs
r�cCs�g}d}dd�}dd�dd�d�}t|�D]*\}}t|t�r9|dur1|�t|||�||��d}|�t|��q|dur?|}q|durQ|�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�Srm)rUr�r.r=r=rArPas
z!collapseStrings.<locals>.<lambda>cSstd�|��SrT)r�r�r�r=r=rArPcscSsd�dd�|D��gS)Nr�cSsg|]}|d�qSrUr=rar=r=rArGdr�z5collapseStrings.<locals>.<lambda>.<locals>.<listcomp>)r�r�r=r=rArPdr�)rr;)rarUrVrrr�rl�collapseStrings)r�r��begun�pred�tranrcr�r=r=rAr�Qs$
�
�r�c	Cs�|��}d}gg}z�d}t|�}||kr�|||d�}|rG|dkr4|d�|||d��|d7}q|dkr;|}|d�|�|d7}n}|dkrZ|d�|�|}|d7}nj|r�|dkr�|�d|�}|dkrntd	��t||d|��}|d�||d
|d
|�f�|d
|}n3|dks�|dkr�|�g�|d7}n!|d
ks�|dkr�|d�|���|d7}n|d�|�|d7}||ksWnty�t|��wt|�dkr�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;ryrtr�r^r_r`rar/rlr�rmr����)
rcr�rlror`rdr%�
IndexErrorrr�)	r��
handleLiteralr��contentStackrcr�r�r\�literalSizer=r=rAr�ssX


$


�� �r�cCs8td|�}td|�}||�|||��|||�|S)Nrr�)r7r�)r�r�r�r=r=rAr��s

$r�r�r�cCsdt|�|fS)Ns{%d}
%b)r��r�r=r=rAr��r�r�c@s"eZdZdd�Zdefdd�ZdS)rcC�
||_dSrm)rb)rZrbr=r=rAr]��
zDontQuoteMe.__init__r�cCs
t|j�Srm)r�rbr^r=r=rAr��r�zDontQuoteMe.__str__N)r�r�r�r]r�r�r=r=r=rAr�srs(){ %*"cCsB|dkrdSt|�D]}|dks|dkrdS|tvrdSq
dS)Nr�r;r��r)r8�_ATOM_SPECIALS)r�r�r=r=rA�_needsQuote�s�r�cCs:t|t�r|Sz|�d�WStyt��t|��w)Nr�)rUr�r�r�r4rr�r�r=r=rAr��s
�r�cCs2t|t�s
|�d�}|�d�}t|�rt|�S|S)Nr�r�)rUr�r�rr�r�r�r=r=rAr
�s


r
cCs0td|�}td|�}||vp||vpt|�dkS)N�
�
i�)r7r�)r��cr�lfr=r=rA�
_needsLiteral�s

r�cCsg}|D]�}t|t�r|�d�}|dur|�ddg�qt|t�r-|�dtt|��g�qt|t�r;|�d|jg�qt|t�r^t	|�rT|�ddt
|�ftj|g�q|�dt
|�g�qt|d�rw|��}|�ddt
|�ftj|g�q|�ddt|�dg�qd	�|d
d��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�sNILs{%d}r�rlrmr�r;)rUr�rrrrdr:rrbrr�r�r��	delimiterr��hasattrr�r�r�)r��piecesrcr�r=r=rAr��s&




 
 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|_dSrm)r�r�
subscriptionsrr=r=rAr]r�z'MemoryAccountWithoutNamespaces.__init__cCs|j}|jd7_|SrM)�top_id)rZrxr=r=rA�
allocateID#sz)MemoryAccountWithoutNamespaces.allocateIDcCsDt|���}||jvrt|��|dur|�||���}||j|<dSrM)r�r5rr�
_emptyMailboxr�)rZr�rr=r=rA�
addMailbox+s

z)MemoryAccountWithoutNamespaces.addMailboxc	Cs�dd�|�d�D�}tdt|��D]}z|�d�|d|���Wqty*Yqwz|�d�|��WdStyH|�d�sEYdSYdSw)NcSsg|]}|r|�qSr=r=)rC�pathr=r=rArG5r�z9MemoryAccountWithoutNamespaces.create.<locals>.<listcomp>�/r;FT)r3rlr�r�r�rr#)rZ�pathspec�paths�accumr=r=rAr�4s ��
��z%MemoryAccountWithoutNamespaces.createcCst�rm)�NotImplementedError)rZr�rxr=r=rAr�B�z,MemoryAccountWithoutNamespaces._emptyMailboxr;cCs|j�t|����Srm)rr�r�r5)rZr��	readwriter=r=rAr�Esz%MemoryAccountWithoutNamespaces.selectcCs�t|���}|j�|�}|std��d|��vr-|j��D]}||kr,|�|�r,td��q|��t	|�
|��dkrBtd|�d���|j|=dS)NzNo such mailboxz	\Noselectz<Hierarchically inferior mailboxes exist and \Noselect is setr;zName "z!" has inferior hierarchical names)r�r5rr�rr�rr~�destroyr��_inferiorNames)rZr�r�othersr=r=rAr�Hs��z%MemoryAccountWithoutNamespaces.deletecs�t�����t������|jvrt���|���}��fdd�|D�}|D]
\}}||jvr3t|��q&|D]\}}|j||j|<|j|=q6dS)Ncsg|]}||���d�f�qSr�)r�)rC�o�rrr=rArGf�z9MemoryAccountWithoutNamespaces.rename.<locals>.<listcomp>)r�r5rr"r�r)rZrr�	inferiors�old�newr=r�rAr_s


�
�z%MemoryAccountWithoutNamespaces.renamecCs,g}|j��D]}|�|�r|�|�q|Srm)rrr~rl)rZr�r��infnamer=r=rAr�ps

�z-MemoryAccountWithoutNamespaces._inferiorNamescCst|���|jvSrm)r�r5r�rr=r=rArwr�z+MemoryAccountWithoutNamespaces.isSubscribedcCs*t|���}||jvr|j�|�dSdSrm)r�r5r�rlrr=r=rArzs
�z(MemoryAccountWithoutNamespaces.subscribecCs4t|���}||jvrtd|����|j�|�dS)NzNot currently subscribed to )r�r5r�r�removerr=r=rArs
z*MemoryAccountWithoutNamespaces.unsubscribecs0��t|����}t�d����fdd�|D�S)Nr�cs$g|]}��|�r|�j|f�qSr=)rhrra�rZrr=rArG�s$z@MemoryAccountWithoutNamespaces.listMailboxes.<locals>.<listcomp>)r�r�r5r�)rZrrr=r�rAr�s
z,MemoryAccountWithoutNamespaces.listMailboxesrmr�)r�r�r�rr�r�r]r�r�r�r�r�r�rr�rrrrr=r=r=rAr�s"
	
r�c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�
MemoryAccountcCs
ddggS)Nr��/r=r^r=r=rAr��r�z#MemoryAccount.getPersonalNamespacescC�dSrmr=r^r=r=rAr��r�z!MemoryAccount.getSharedNamespacescCr�rmr=r^r=r=rA�getOtherNamespaces�r�z MemoryAccount.getOtherNamespacescCr�rmr=r^r=r=rA�getUserNamespaces�szMemoryAccount.getUserNamespacesN)r�r�r�r�r�r�r�r=r=r=rAr��s
r�r�r��
getUIDNextr��getUnseenCountr%cCs*i}|D]}t|t|����||<q|Srm)r)�_statusRequestDictr5)rr��rrr=r=rA�statusRequestHelper�srcCs*|durdgStj�|g�}dd�|D�S)NrRcSs&g|]\}}|p	ddg|�d��qS)N�@�r3)rCr?�addressr=r=rArG�s&zparseAddr.<locals>.<listcomp>)r�r��getaddresses)�addrr=r=rA�	parseAddr�s
�rc
Cs�|�d�}|�d�}|�d�}|�d�}|�d|�}|�d|�}|�d�}|�d�}|�d	�}	|�d
�}
|�d�}||t|�t|�|oFt|�|oKt|�|oPt|�|	oUt|	�|
|f
S)NTr�r�r��senderzreply-tor�r�r�zin-reply-toz
message-id)r�r�r)r��headersr�r��from_r�reply_tor�r�r��in_reply_to�midr=r=rAr��s,












�r�cCsd}|��D]}|d7}q|Sr�)r�)r�r�rAr=r=rA�getLineCount�s
r
cCs2|d|dkrdkrn|S|dd�S|S)Nrrtrr;r=r�r=r=rA�unquote�s�rcCs�d}|�dd��dd�}d�|���}|rA|�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-typer��;rr�r;css$�|]
}|�����dd�VqdS)�=r;N)rcr�r3r*r=r=rAr��s�"z"_getContentType.<locals>.<genexpr>)r�r�r��
splitlinesr3r��dict)r��attrs�mm�mimetyper�major�minorr=r=rA�_getContentType�s

rcCs�t|�\}}}|dur|��}|dur|��}|dkr!t|||�S||fdkr.t||||�S|dkr9t||||�St||||�S)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.
    N�	multipart)r�rNr5)rr��_MultipartMessageStructure�_RFC822MessageStructure�_TextMessageStructure�_SinglepartMessageStructure)r��main�subtyperr=r=rA�_getMessageStructure�sr!c@r�)	�_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)r�r)rZr�rr=r=rAr]s
z_MessageStructure.__init__cCsh|r2|�d�}t|�dkr|d��df}|St|�dkr0dd�|dd�D�}|d��|g}|SdS)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]}|�q
qS�rr;r)rC�paramrOr=r=rArG0s"z2_MessageStructure._disposition.<locals>.<listcomp>)r3r�r�)rZ�disp�paramsr=r=rA�_disposition"s
�z_MessageStructure._dispositioncCs0|jrdd�|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�rCr*r�r=r=rArG=r+z4_MessageStructure._unquotedAttrs.<locals>.<listcomp>cSsg|]	}|D]}|�qqSr=r=)rCrO�yr=r=rArG>�N)rr�rh)rZ�unquotedr=r=rA�_unquotedAttrs6sz _MessageStructure._unquotedAttrsN)r�r�r�r�r]r'r,r=r=r=rAr"s
r"c@s8eZdZdZgd�Zdd�Zdd�Zdd�Zd	d
�ZdS)rzn
    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]rr r)rZr�rr rr=r=rAr]Js
z$_SinglepartMessageStructure.__init__cCsZ|jjdg|j�R�}|j��}|j|j}}|��}||||�d�|�d�|�d�|gS)zN
        Return a list of the basic fields for a single-part message.
        Fr-r.r/)r�r��_HEADERSr�rr r,r�)rZrr�rr�
unquotedAttrsr=r=rA�_basicFields]s
�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.
        )r2rr�	_extended�rZ�extendedrJr=r=rArusz"_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)r�r�rlr�r'�rZrJrr=r=rAr3�s�z%_SinglepartMessageStructure._extendedN)	r�r�r�r�r0r]r2rr3r=r=r=rArBsrc@�eZdZdZdd�ZdS)rz_
    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.
        )rr2rlr
r�rrr3r4r=r=rAr�s

z_TextMessageStructure.encodeN�r�r�r�r�rr=r=r=rAr��rc@r:)rzi
    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)rrr�rrlr�r
r
)rZr5rJ�	containedr=r=rAr�sz_RFC822MessageStructure.encodeNr;r=r=r=rAr�r<rc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)rzi
    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 )rZr�r rr=r=rAr]�s
z#_MultipartMessageStructure.__init__ccs>�d}	z|j�|�}Wn
tyYdSw|V|d7}q)zR
        Return an iterator over all of the sub-messages of this message.
        rTr;N)r�rr�)rZrcrr=r=rA�	_getParts�s���z$_MultipartMessageStructure._getPartscs8�fdd�|��D�}|�|j��r|�|���|S)zW
        Encode each sub-message and added the additional I{multipart} fields.
        csg|]	}t|�����qSr=�r!rr<�r5r=rArG�r*z5_MultipartMessageStructure.encode.<locals>.<listcomp>)r>rlr rrr3r4r=r@rAr�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].
        Fr7r8r6N)r�r�rlr,r'r�r9r=r=rAr3�s�z$_MultipartMessageStructure._extendedN)r�r�r�r�r]r>rr3r=r=r=rAr�s
rFcCst|��|�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?)r�r5r=r=rAr
"sir
cCs(dd�|��D�}d�|�d}t|�S)Nc	Ss,g|]\}}d�|��d�|���f��qS)z: �
)r��titlerr(r=r=rArG�s��z"_formatHeaders.<locals>.<listcomp>rA)r�r�r:)rr�r=r=rAr��s
�r�ccs4�d}z	|�|�V|d7}qtyYdSw)NrTr;)rr�)rjrcr=r=rA�subparts�s���rCcs2ddlm�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.
    rricsrzt��}Wnty��|�YdSty"���YdSwt|tj�r0|���dS��	d�|�dSr�)
r�r�r�r�r�rUr
rSrCrp)r_r��r��gorcrjr=rArE�s�ziterateInReactor.<locals>.goN)rorjr
rS)rcr=rDrAr��s

r�c@s4eZdZdZeej�Zd	dd�Zdd�Z	dd�Z
dS)
r	�NcCs<||_|durt��}||_|durt}||_|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)r�r�r�r=r�rr�)rZr�r=rr=r=rAr]�szMessageProducer.__init__cCs||_|�|���Srm)�consumerr�_produce)rZrGr=r=rAr�szMessageProducer.beginProducingc#s���j�d�}d}�j��rZ|�d�}dd�|�d�dd�D�}dd�|D�}|�d	�}|durFd
���j��}|dd|�d�7<n|�d�rV|�d�rV|dd
�}t	|�}��
t|����
d��j��r�t�j�D]}��
d|d�t
|�j�j��d�Vqp��
d|d�n�j��}	|��j�}|r��j�
|�dVnnq��jrɈj�dd�t�j���j���fdd��VdSdS)NTrcSsg|]}|�dd��qSr#rr*r=r=rArG�r�z,MessageProducer._produce.<locals>.<listcomp>rr;cSsi|]\}}|����|�qSr=)r�rcr(r=r=rAr$�r�z,MessageProducer._produce.<locals>.<dictcomp>�boundaryz----=z; boundary="rrtr�s
--s--
rcs�Srmr=r�r^r=rArPr�z*MessageProducer._produce.<locals>.<lambda>)r�r�rr�r3�_uuid4�hexr~r#r:r�r�rCr	r=rrr�r��
CHUNK_SIZErGr�rrC)rZrrIrr�r�r-r�r=r^rArH�sJ�




�
�

��zMessageProducer._producer])r�r�r�rL�staticmethod�uuid�uuid4rJr]rrHr=r=r=rAr	�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)Brvc@r:)z_FetchParser.EnveloperHcCrG)NrHr=r^r=r=rArPr�z_FetchParser.Envelope.<lambda>N�r�r�r�rr�r=r=r=rA�Envelope
srQc@r:)z_FetchParser.Flagsr{cCrG)Nr{r=r^r=r=rArPr�z_FetchParser.Flags.<lambda>NrPr=r=r=rA�Flags�rRc@r:)z_FetchParser.InternalDaterFcCrG)NrFr=r^r=r=rArPr�z"_FetchParser.InternalDate.<lambda>NrPr=r=r=rA�InternalDaterSrTc@r:)z_FetchParser.RFC822HeaderrPcCrG)Nr�r=r^r=r=rArP"r�z"_FetchParser.RFC822Header.<lambda>NrPr=r=r=rA�RFC822Header rSrUc@r:)z_FetchParser.RFC822TextrRcCrG)Nrr=r^r=r=rArP&r�z _FetchParser.RFC822Text.<lambda>NrPr=r=r=rA�
RFC822Text$rSrVc@r:)z_FetchParser.RFC822SizerTcCrG)Nr�r=r^r=r=rArP*r�z _FetchParser.RFC822Size.<lambda>NrPr=r=r=rA�
RFC822Size(rSrWc@r:)z_FetchParser.RFC822rNcCrG)NrNr=r^r=r=rArP.r�z_FetchParser.RFC822.<lambda>NrPr=r=r=rA�RFC822,rSrXc@r:)z_FetchParser.UIDr>cCrG)Nr>r=r^r=r=rArP2r�z_FetchParser.UID.<lambda>NrPr=r=r=rAr�0rSr�c@sLeZdZdZdZdZdZdZdZdZ	dZ
dZdefdd�Z
defdd	�ZdS)
z_FetchParser.Bodyr�FNr=r�cC�|���d�S�Nr��rr�r^r=r=rAr�?rz_FetchParser.Body.__str__cCs�d}d}d}|jrd�dd�|jD��}d}|jr,|d||t|j��d�d7}n'|jr:|d||d	7}n|jrH|d||d
7}n|jrS|d|d7}|jdurb|d|j|j	f7}|S)Nr]r��.cSsg|]}t|d��d��qS)r;r�)r�rr*r=r=rArGGr�z/_FetchParser.Body.__bytes__.<locals>.<listcomp>r�r�r�sTEXT]sMIME]s<%d.%d>)
rr�rr�rr5rr�partialBegin�
partialLength)rZ�baser�	separatorr=r=rArBs&�
z_FetchParser.Body.__bytes__)r�r�r�rrwrrr5rrr]r^r�r�rrr=r=r=rA�Body4srac@r:)z_FetchParser.BodyStructurerKcCrG)NrKr=r^r=r=rArP[r�z#_FetchParser.BodyStructure.<lambda>NrPr=r=r=rA�
BodyStructureYrSrbc@s4eZdZdZdZdZdefdd�Zdefdd�Z	dS)z_FetchParser.HeaderFNr�cCrYrZr[r^r=r=rAr�crz_FetchParser.Header.__str__cCs�d}|jr4|d7}|jr|d7}g}|jD]}|��}t|�r#t|�}|�|�q|dd�|�d7}|jrFd�dd	�|jD��d|}|S)
NsHEADERs.FIELDSs.NOTr,r�rmr\cSsg|]}|d���qSr�)rr*r=r=rArGvr�z1_FetchParser.Header.__bytes__.<locals>.<listcomp>)rrrBr�r�rlr�r)rZr_rr-r=r=rArfs
z_FetchParser.Header.__bytes__)
r�r�r�rrrr�r�rrr=r=r=rA�Header^srcc@�eZdZdS)z_FetchParser.TextN�r�r�r�r=r=r=rA�Texty�rfc@rd)z_FetchParser.MIMENrer=r=r=rA�MIME|rgrhNsenvelopesflagssinternaldates
rfc822.headersrfc822.textsrfc822.sizesrfc822suids
bodystructurecCsdg|_g|_d|_dS)N�initialr�)rrJ�	remainingr^r=r=rAr]�s
z_FetchParser.__init__cCs�|j|}zB|s|jrB|jstd��|j��}zt|d|�|�}Wnty0|j�|��w||d�}|s|jsW||_dSW||_dS||_w)NzInvalid Argument�state_)rjrrr%r)r�rl)rZr�r�usedr=r=rArw�s"


��
�z_FetchParser.parseStringcCs�|dkrdS|��}|�d�r#|j�|��|��|��|��f�dS|�d�r?|j�|��|��|��|��|��f�dS|�d�rU|j�|��|��|��f�dS|�d�rb|j	�d	�d
S|j	�
d�dS)Nr�rsallr/sfullrhsfastrl)�close_paren�maybe_fetch_att�	fetch_attr;ro)r�r~rJrrrRrTrWrQrarrl)rZr�r}r=r=rA�
state_initial�s>
�
��	
��
z_FetchParser.state_initialcCs|�d�rdStd��)Nrmr;z	Missing )�r~r+r�r=r=rA�state_close_paren�s
z_FetchParser.state_close_parencCsP|r
|dd���std��d}tt|��D]}|||d���s%|Sq|S)Nrr;zWhitespace expected, none found)�isspacer+rlr�)rZr�rcr=r=rA�state_whitespace�s�z_FetchParser.state_whitespacecCs|�d�s|j�d�dS)Nrm)rnror�r�r~rrrr�r=r=rA�state_maybe_fetch_att�s
z"_FetchParser.state_maybe_fetch_attcCs�|��}|jD]\}}|�|�r|j�|��t|�Sq|��}|�d�r-d|_d}n|�d�r5d}ntd|����||_	|j
�d�|S)Ns	body.peekTr�sbodyrhz!Nothing recognized in fetch_att: )�got_body�
maybe_partial�
maybe_section)r��_simple_fetch_attr~rJrlr�rarwr+�pending_bodyrrr)rZr�r}r��clsr�rlr=r=rA�state_fetch_att�s 
�

z_FetchParser.state_fetch_attcCs|j�|j�|`dSr�)rJrlr{r�r=r=rA�state_got_body�sz_FetchParser.state_got_bodycCs|�d�sdS|j�d�dS)Nr�r)�section�part_numberr;rur�r=r=rA�state_maybe_sections
z _FetchParser.state_maybe_sections(\d+(?:\.\d+)*)\.?cCsD|j�|�}|durdd�|��d�d�D�|_|��Sg|_dS)NcSsg|]}t|�d�qSr�)rdr<r=r=rArGr�z2_FetchParser.state_part_number.<locals>.<listcomp>rr\)�	_partExprrh�groupsr3r�r\)rZr�rjr=r=rA�state_part_numbersz_FetchParser.state_part_numbercCs|��}d}|�d�rd|j_|d7}nd|�d�r,|��}|j_d|_d|_|d7}nL|�d�r<|��|j_	|d	7}n<|�d
�rL|�
�|j_|d	7}n,|��}|�d�r]d|_|d7}n|�d
�rg|d7}ntd|����||j_|j
�d�t|j�|j_d|_|S)Nrr�Tr;sheader]r=r�stext]rgsmime]sheader.fields.not�s
header.fieldsr<zUnhandled section contents: )�finish_section�header_listr�)r�r~r{rrcrrrrfr5rhrr+rrrrr�r)rZr�r}rlr~r=r=rA�
state_sections8











z_FetchParser.state_sectioncCs|�d�s	td��dS)Nr�zsection must end with ]r;rqr�r=r=rA�state_finish_section9s
z!_FetchParser.state_finish_sectioncCsX|�d�s	td��|�d�}|dkrtd��|d|���}dd�|D�|jj_|dS)	NrlzHeader list must begin with (rmrtzHeader list must end with )r;cSr�r=r�)rCr~r=r=rArGFr�z2_FetchParser.state_header_list.<locals>.<listcomp>)r~r+ror3r{rr)rZr�r\rr=r=rA�state_header_list>s

z_FetchParser.state_header_listcCsz|�d�sdS|�d�}|dkrtd��|d|�}|�dd�}t|�dkr*td	��tt|�\}}||j_||j_	|dS)
Nr_rr`rtzFound < but not >r;r\r�z>Partial specification did not include two .-delimited integers)
r~ror+r3r�rrdr{r]r^)rZr�r\rjr��beginryr=r=rA�state_maybe_partialIs

�z _FetchParser.state_maybe_partial)#r�r�r�rQrRrTrUrVrWrXr�rarbrcrfrhr�rzr]rwrprrrtrvr}r~r�rVrWr�r�r�r�r�r�r=r=r=rArv	sP%�)

	%rvc@sDeZdZdZdZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dS)rrFTcCr�rmr5)rZr-r=r=rAr]cr�zFileProducer.__init__cCs.||_|j|_t��}|_|j�|d�|S)NF)rGr��producer
rS�_onDone�registerProducer)rZrGr�r=r=rArfs
zFileProducer.beginProducingcCsxd}|jrd|��f}d|_|jsdS||j�|j�}|s5|j��|j�|�d|_|_|_dS|�	|�dS)Nr�s{%d}
F)
�
firstWrite�_sizer-r�rLrG�unregisterProducerr�r�r�)rZr�r=r=rA�resumeProducingms
zFileProducer.resumeProducingcCrG)z9
        Pause the producer.  This does nothing.
        Nr=r^r=r=rA�pauseProducing|r�zFileProducer.pauseProducingcCrG)z8
        Stop the producer.  This does nothing.
        Nr=r^r=r=rA�
stopProducing�r�zFileProducer.stopProducingcCs8|j��}|j�dd�|j��}|j�|d�||S)Nrr�)r-r/r�)rZr�r.r=r=rAr��s


zFileProducer._sizeN)r�r�r�rLr�r]rr�r�r�r�r=r=r=rAr^srcCs�gd�}dddd�}t�d||�}|std|����|��}z!d|�|d	���d
|d	<t|d�|d<t|d�|d<WntyNtd|����wt�|d|d	|dd
d
d
dddf	�S)N)�jan�feb�mar�apr�may�jun�jul�aug�sep�oct�nov�dec�january�february�march�aprilr��june�july�august�	september�october�november�decemberz+(?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 r;r��r�r�rrt)	rVrhr`�	groupdict�indexr�rdr��struct_time)r��months�exprrjr�r=r=rAr��s"��(r�rcGs|dSr�r=rNr=r=rArP�rQrPcCs|�d�}|dd��dd�S)N�utf-7r;rtr�r�)rr��r��s_utf7r=r=rA�modified_base64�s
r�cCsd|�dd�d}|�d�S)Nr�r�r�r�r�)r�r�r�r=r=rA�modified_unbase64�s
r�cCs�t�}g}ttttdd���dh}|D]D}||vr6|r.|dtd�|��d7}|dd�=|�t|��q|dkrS|rN|dtd�|��d7}|dd�=|d7}q|�|�q|ri|�	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.
    � ��&�&r�r�Ns&-)�	bytearrayr'r�chrrlr�r�rl�ordrrrr�)r��errorsr��_in�valid_charsr�r=r=rA�encoder�s$



r�c	Cs�g}g}tt|�d�}|D]@}|dkr|s|�d�q
|dkr>|r>t|�dkr-|�d�n|�td�|dd����g}q
|rF|�|�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.
    r�r�r�r;r�r�Nr�)�memory_cast�
memoryviewrlr�r�r�r�)r�r�r�r�r�r=r=rA�decoder�s"
r�c@�eZdZddd�ZdS)�StreamReader�strictcC�t|�Srm)r��rZr�r�r=r=rAr��zStreamReader.decodeN�r�)r�r�r�r�r=r=r=rAr��r�c@r�)�StreamWriterr�cCr�rm)r�r�r=r=rArr�zStreamWriter.encodeNr�)r�r�r�rr=r=r=rAr�r�r�cCs|�dd�dkr
tSdS)N�-rA�imap4_utf_7)r��
_codecInfor�r=r=rAr�s�r�)(r�r��IMailboxListenerr'r��IMailboxr0r�IMailboxInfo�IMessager8rrY�IMessagePartrrrrr%r!r#rrrrr rrr"r$rrrrrr�r�r�r�rrmrUr�rS)�r�r��codecsr��email.utilsr�rirVr�r�r�rN�base64rr�ior�	itertoolsr�typingrrr�zope.interfacer	�twisted.credr
�twisted.cred.errorrrror
rr�twisted.internet.deferr�twisted.mail._credrrrrr�twisted.mail._exceptrrrrrrrrrrr r!r"r#r$r%�twisted.mail.interfacesr&r�r'r(rr)r�r*r�r+r�r,r�r-r8r.rr/r�r0r1rY�twisted.protocolsr2r3�twisted.pythonr4r5�twisted.python.compatr6r7r8r9r:rrkrlr3r�rBrIrJr�r�r�r��_SPr�_CTLr�r��_nativeNonAtomCharsrWr�rY�LineReceiver�TimeoutMixinr��TimeoutErrorr�r�rtr�r�rhr�r�r�r�r�r�r�r�r�r�r�rr�r�r�r
r�r�r�r�r�rrr�r
rrr!r"rrrrr
r�rCr�r	rvrr�r)r�r�r�r�r�r�r�r��	CodecInfor�r��register�__all__r=r=r=rA�<module>s
H8	�&!K
%
$9

	A
":
	1r�			2h
Ol

!FW02

""


Spamworldpro Mini