Your IP : 18.218.1.38


Current Path : /opt/alt/python35/lib64/python3.5/__pycache__/
Upload File :
Current File : //opt/alt/python35/lib64/python3.5/__pycache__/imaplib.cpython-35.opt-1.pyc



��Yf���Y@sbdZdZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZmZm
Z
ddlmZyddlZdZWnek
r�dZYnXdd	d
ddd
gZdZdZdZdZddfZdZdddfddfdddddfddfddfddfdddfdddfdddfd dfd!ddfd"dfd#dfd$ddfd%ddfd&ddfd'ddfd(ddfd)ddfd*dfdddddfd+ddfd,ddfd-ddddfd.dfd/dfd0ddfd1dfd2ddfd3ddfd4ddfd5ddfd6dfd7dfd8ddfd9dfd:ddfd;dfd<dfd=ddfi(Zejd>�Zejd?�Zejd@�ZejdAej�Z ejdB�Z!ejdC�Z"ejdD�Z#ejdEej�Z$dAZ%dEZ&GdFd�d�Z'er�GdGdH�dHe'�Z(ej)dH�GdId	�d	e'�Z*GdJdK�dK�Z+dLj,dM�Z-dNdO�e.e-dPd��D�Z/dQd
�Z0dRd�Z1dSd�Z2dTd
�Z3e4dUkr^ddl5Z5ddl6Z6y)e5j5ej7dPd�dV�\Z8Z9Wn:e5j:k
r�Z;zfff\Z8Z9WYddZ;[;XnXdZ<xQe8D]I\Z=Z;e=dWkr�e>e;�Zn"e=dXkre;Z<e9re<fZ9q�We9r*dYfZ9e9dZ?e6j@�ZAe6j6dZeAe?pUd[f�ZBd\d]eAd^d_iZCd`eAeBffdadbffdcdbddffddeffdfdeddeCffdgdhdiffdjdeffdkddldmffdndodpffdqdodrdsffdtffduffdvffdwfffZDdjffdxdyffdzd1d{ffdxd|ffdfdddeCffdvffd}fffZEd~d�ZFy�e<r�e*e<�ZGne'e?�ZGeGjHdkr�eDdPd�ZDeGjId�eGjJ�eGjId�eGjKf�x!eDD]\ZLZ9eFeLe9�qWxheFdgd�d�f�D]QZMejNd�eM�ZOeOryeOjPdP�ZQneMj,�dPZQeFd�eQf�qIWx~eED]v\ZLZ9eFeLe9�ZReLe9fdzd1d{ffkr�q�eRdPj,�ZSeSr�q�eFdzd#d�eSdPd�f�q�WeTd��Wn1eTd��erVeTd�ej7d��YnXdS)�z�IMAP4 client.

Based on RFC 2060.

Public class:           IMAP4
Public variable:        Debug
Public functions:       Internaldate2tuple
                        Int2AP
                        ParseFlags
                        Time2Internaldate
z2.58�N)�datetime�timezone�	timedelta)�DEFAULT_BUFFER_SIZETF�IMAP4�IMAP4_stream�Internaldate2tuple�Int2AP�
ParseFlags�Time2Internaldates
�i�Z	IMAP4REV1i@B�APPEND�AUTH�SELECTED�AUTHENTICATE�NONAUTH�
CAPABILITY�LOGOUT�CHECK�CLOSE�COPY�CREATE�DELETE�	DELETEACL�ENABLE�EXAMINE�EXPUNGE�FETCH�GETACL�
GETANNOTATION�GETQUOTA�GETQUOTAROOT�MYRIGHTS�LIST�LOGIN�LSUB�	NAMESPACE�NOOP�PARTIAL�	PROXYAUTH�RENAME�SEARCH�SELECT�SETACL�
SETANNOTATION�SETQUOTA�SORT�STARTTLS�STATUS�STORE�	SUBSCRIBE�THREAD�UID�UNSUBSCRIBEs\+( (?P<data>.*))?s.*FLAGS \((?P<flags>[^\)]*)\)s�.*INTERNALDATE "(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9]) (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9]) (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])"s.*{(?P<size>\d+)}$s
\r\n|\r|\ns)\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]s$\* (?P<type>[A-Z-]+)( (?P<data>.*))?s3\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?c@s�eZdZdZGdd�de�ZGdd�de�ZGdd�de�Zded	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdedd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Zd7d8�Z d9d:�Z!d;d<�Z"d=d>�Z#d?d@�Z$dAdB�Z%dCdD�Z&dEdF�Z'dGdH�Z(dIdJdKdL�Z)dMdN�Z*dOdP�Z+dQdR�Z,dSdT�Z-dIdJdUdV�Z.dWdX�Z/dYdZ�Z0d[d\�Z1d]d^�Z2d_d`�Z3dadb�Z4dcdd�Z5dedfdgdh�Z6didj�Z7dkdl�Z8dmdn�Z9dodp�Z:dqdrds�Z;dtdu�Z<dvdw�Z=dxdy�Z>dzd{�Z?d|d}�Z@d~d�ZAd�d��ZBd�d��ZCd�d��ZDd�d��ZEd�d��ZFd�d��ZGd�d��ZHd�d��ZId�d��ZJd�d��ZKd�d��ZLd�d��ZMd�d��ZNd�d��ZOdqS)�ra�IMAP4 client class.

    Instantiate with: IMAP4([host[, port]])

            host - host's name (default: localhost);
            port - port number (default: standard IMAP4 port).

    All IMAP4rev1 commands are supported by methods of the same
    name (in lower-case).

    All arguments to commands are converted to strings, except for
    AUTHENTICATE, and the last argument to APPEND which is passed as
    an IMAP4 literal.  If necessary (the string contains any
    non-printing characters or white-space and isn't enclosed with
    either parentheses or double quotes) each string is quoted.
    However, the 'password' argument to the LOGIN command is always
    quoted.  If you want to avoid having an argument string quoted
    (eg: the 'flags' argument to STORE) then enclose the string in
    parentheses (eg: "(\Deleted)").

    Each command returns a tuple: (type, [data, ...]) where 'type'
    is usually 'OK' or 'NO', and 'data' is either the text from the
    tagged response, or untagged results from command. Each 'data'
    is either a string, or a tuple. If a tuple, then the first part
    is the header of the response, and the second part contains
    the data (ie: 'literal' value).

    Errors raise the exception class <instance>.error("<reason>").
    IMAP4 server errors raise <instance>.abort("<reason>"),
    which is a sub-class of 'error'. Mailbox status changes
    from READ-WRITE to READ-ONLY raise the exception class
    <instance>.readonly("<reason>"), which is a sub-class of 'abort'.

    "error" exceptions imply a program error.
    "abort" exceptions imply the connection should be reset, and
            the command re-tried.
    "readonly" exceptions imply the command should be re-tried.

    Note: to use this module, you must read the RFCs pertaining to the
    IMAP4 protocol, as the semantics of the arguments to each IMAP4
    command are left to the invoker, not to mention the results. Also,
    most IMAP servers implement a sub-set of the commands available here.
    c@seZdZdS)zIMAP4.errorN)�__name__�
__module__�__qualname__�r;r;�,/opt/alt/python35/lib64/python3.5/imaplib.py�error�sr=c@seZdZdS)zIMAP4.abortN)r8r9r:r;r;r;r<�abort�sr>c@seZdZdS)zIMAP4.readonlyN)r8r9r:r;r;r;r<�readonly�sr?�cCs�t|_d|_d|_i|_i|_d|_d|_d|_d|_	|j
�|j||�y|j�Wn8t
k
r�y|j�Wntk
r�YnX�YnXdS)Nrr@Fr)�Debug�debug�state�literal�tagged_commands�untagged_responses�continuation_response�is_readonly�tagnum�_tls_established�_mode_ascii�open�_connect�	Exception�shutdown�OSError)�self�host�portr;r;r<�__init__�s&									


zIMAP4.__init__cCsFd|_d|_tjttj�|_tjttj�|_dS)NF�ascii)	�utf8_enabled�	_encoding�re�compile�_Literal�ASCII�Literal�_Untagged_status�Untagged_status)rQr;r;r<rK�s		zIMAP4._mode_asciicCs:d|_d|_tjt�|_tjt�|_dS)NTzutf-8)rVrWrXrYrZr\r]r^)rQr;r;r<�
_mode_utf8�s		zIMAP4._mode_utf8cCs�ttjdd��|_tjd|jdtj�|_|j�|_	d|j
krhd|_n-d|j
kr�d|_n|j|j	��|j
�x*tD]"}||jkr�q�||_dSW|jd	��dS)
Nii��s(?P<tag>s"\d+) (?P<type>[A-Z]+) (?P<data>.*)ZPREAUTHr�OKrzserver not IMAP4 compliant)r	�randomZrandint�tagprerXrYr[�tagre�
_get_responseZwelcomerFrCr=�_get_capabilities�AllowedVersions�capabilities�PROTOCOL_VERSION)rQ�versionr;r;r<rM�s 


	zIMAP4._connectcCs3|tkrt||j��Std|��dS)NzUnknown IMAP4 command: '%s')�Commands�getattr�lower�AttributeError)rQ�attrr;r;r<�__getattr__szIMAP4.__getattr__cCs|S)Nr;)rQr;r;r<�	__enter__szIMAP4.__enter__cGs'y|j�Wntk
r"YnXdS)N)�logoutrP)rQ�argsr;r;r<�__exit__	s
zIMAP4.__exit__cCstj|j|jf�S)N)�socketZcreate_connectionrRrS)rQr;r;r<�_create_socketszIMAP4._create_socketcCs:||_||_|j�|_|jjd�|_dS)z�Setup connection to remote server on "host:port"
            (default: localhost:standard IMAP4 port).
        This connection will be used by the routines:
            read, readline, send, shutdown.
        �rbN)rRrSru�sock�makefile�file)rQrRrSr;r;r<rLs		z
IMAP4.opencCs|jj|�S)zRead 'size' bytes from remote.)ry�read)rQ�sizer;r;r<rz"sz
IMAP4.readcCs?|jjtd�}t|�tkr;|jdt��|S)zRead line from remote.�zgot more than %d bytes)ry�readline�_MAXLINE�lenr=)rQ�liner;r;r<r}'szIMAP4.readlinecCs|jj|�dS)zSend data to remote.N)rwZsendall)rQ�datar;r;r<�send/sz
IMAP4.sendcCs�|jj�zpy|jjtj�WnRtk
r{}z2|jtjkrit	|dd�dkri�WYdd}~XnXWd|jj�XdS)z Close I/O established in "open".Zwinerrorri&'N)
ry�closerwrOrtZ	SHUT_RDWRrP�errnoZENOTCONNrk)rQ�excr;r;r<rO4s
zIMAP4.shutdowncCs|jS)zfReturn socket instance used to connect to IMAP4 server.

        socket = <instance>.socket()
        )rw)rQr;r;r<rtDszIMAP4.socketcCs]d}|jddg|�\}}|dr8||fS|j�\}}|j|||�S)aReturn most recent 'RECENT' responses if any exist,
        else prompt server for an update using the 'NOOP' command.

        (typ, [data]) = <instance>.recent()

        'data' is None if no new messages,
        else list of RECENT responses, most recent last.
        ZRECENTr`Nr|���)�_untagged_response�noop)rQ�name�typ�datr;r;r<�recentPs	

zIMAP4.recentcCs|j|dg|j��S)z�Return data for response 'code' if received, or None.

        Old value for response 'code' is cleared.

        (code, [data]) = <instance>.response(code)
        N)r��upper)rQ�coder;r;r<�responseaszIMAP4.responsecCs�d}|sd}|r?|d|dfdkrEd|}nd}|rZt|�}nd}tjt|�}|jr�d	|d
}||_|j||||�S)
z�Append message to named mailbox.

        (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)

                All args except `message' can be None.
        r
�INBOXrr|�(�)z(%s)NsUTF8 (�)r�)r�r�)r�MapCRLF�sub�CRLFrVrD�_simple_command)rQ�mailbox�flags�	date_time�messager�rDr;r;r<�appendos
		zIMAP4.appendcCst|j�}t|�j|_|jd|�\}}|dkra|j|djdd���d|_||fS)asAuthenticate command - requires response processing.

        'mechanism' specifies which authentication mechanism is to
        be used - it must appear in <instance>.capabilities in the
        form AUTH=<mechanism>.

        'authobject' must be a callable object:

                data = authobject(response)

        It will be called to process server continuation responses; the
        response argument it is passed will be a bytes.  It should return bytes
        data that will be base64 encoded and sent to the server.  It should
        return None if the client abort response '*' should be sent instead.
        rr`r|zutf-8�replacerr�)r��_Authenticator�processrDr�r=�decoderC)rQZ	mechanismZ
authobject�mechr�r�r;r;r<�authenticate�s	zIMAP4.authenticatecCs.d}|j|�\}}|j|||�S)zT(typ, [data]) = <instance>.capability()
        Fetch capabilities list from server.r)r�r�)rQr�r�r�r;r;r<�
capability�szIMAP4.capabilitycCs
|jd�S)zRCheckpoint mailbox on server.

        (typ, [data]) = <instance>.check()
        r)r�)rQr;r;r<�check�szIMAP4.checkcCs0z|jd�\}}Wdd|_X||fS)z�Close currently selected mailbox.

        Deleted messages are removed from writable mailbox.
        This is the recommended command before 'LOGOUT'.

        (typ, [data]) = <instance>.close()
        rNr)r�rC)rQr�r�r;r;r<r��s
zIMAP4.closecCs|jd||�S)z�Copy 'message_set' messages onto end of 'new_mailbox'.

        (typ, [data]) = <instance>.copy(message_set, new_mailbox)
        r)r�)rQ�message_setZnew_mailboxr;r;r<�copy�sz
IMAP4.copycCs|jd|�S)zPCreate new mailbox.

        (typ, [data]) = <instance>.create(mailbox)
        r)r�)rQr�r;r;r<�create�szIMAP4.createcCs|jd|�S)zPDelete old mailbox.

        (typ, [data]) = <instance>.delete(mailbox)
        r)r�)rQr�r;r;r<�delete�szIMAP4.deletecCs|jd||�S)z�Delete the ACLs (remove any rights) set for who on mailbox.

        (typ, [data]) = <instance>.deleteacl(mailbox, who)
        r)r�)rQr��whor;r;r<�	deleteacl�szIMAP4.deleteaclcCshd|jkrtjd��|jd|�\}}|dkr^d|j�kr^|j�||fS)zkSend an RFC5161 enable string to the server.

        (typ, [data]) = <intance>.enable(capability)
        rzServer does not support ENABLEr`zUTF8=ACCEPT)rgrr=r�r�r_)rQr�r�r�r;r;r<�enable�s
zIMAP4.enablecCs.d}|j|�\}}|j|||�S)z�Permanently remove deleted items from selected mailbox.

        Generates 'EXPUNGE' response for each deleted message.

        (typ, [data]) = <instance>.expunge()

        'data' is list of 'EXPUNGE'd message numbers in order received.
        r)r�r�)rQr�r�r�r;r;r<�expunge�s	z
IMAP4.expungecCs4d}|j|||�\}}|j|||�S)a#Fetch (parts of) messages.

        (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)

        'message_parts' should be a string of selected parts
        enclosed in parentheses, eg: "(UID BODY[TEXT])".

        'data' are tuples of message part envelope and data.
        r)r�r�)rQr�Z
message_partsr�r�r�r;r;r<�fetch�s
zIMAP4.fetchcCs+|jd|�\}}|j||d�S)zXGet the ACLs for a mailbox.

        (typ, [data]) = <instance>.getacl(mailbox)
        rZACL)r�r�)rQr�r�r�r;r;r<�getacl
szIMAP4.getaclcCs1|jd|||�\}}|j||d�S)za(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute)
        Retrieve ANNOTATIONs.r�
ANNOTATION)r�r�)rQr��entryZ	attributer�r�r;r;r<�
getannotationszIMAP4.getannotationcCs+|jd|�\}}|j||d�S)z�Get the quota root's resource usage and limits.

        Part of the IMAP4 QUOTA extension defined in rfc2087.

        (typ, [data]) = <instance>.getquota(root)
        r �QUOTA)r�r�)rQ�rootr�r�r;r;r<�getquotaszIMAP4.getquotacCs^|jd|�\}}|j||d�\}}|j||d�\}}|||gfS)z�Get the list of quota roots for the named mailbox.

        (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
        r!r�Z	QUOTAROOT)r�r�)rQr�r�r�ZquotaZ	quotarootr;r;r<�getquotaroot)szIMAP4.getquotarootz""�*cCs4d}|j|||�\}}|j|||�S)z�List mailbox names in directory matching pattern.

        (typ, [data]) = <instance>.list(directory='""', pattern='*')

        'data' is list of LIST responses.
        r#)r�r�)rQ�	directory�patternr�r�r�r;r;r<�list4sz
IMAP4.listcCsV|jd||j|��\}}|dkrC|j|d��d|_||fS)z�Identify client using plaintext password.

        (typ, [data]) = <instance>.login(user, password)

        NB: 'password' will be quoted.
        r$r`r|rr�)r��_quoter=rC)rQ�user�passwordr�r�r;r;r<�login@s
$	zIMAP4.logincCs&|||_|_|jd|j�S)zr Force use of CRAM-MD5 authentication.

        (typ, [data]) = <instance>.login_cram_md5(user, password)
        zCRAM-MD5)r�r�r��_CRAM_MD5_AUTH)rQr�r�r;r;r<�login_cram_md5NszIMAP4.login_cram_md5cCs]ddl}t|jt�r0|jjd�n|j}|jd|j||d�j�S)z1 Authobject to use with CRAM-MD5 authentication. rNzutf-8� Zmd5)�hmac�
isinstancer��str�encoder�ZHMACZ	hexdigest)rQZ	challenger��pwdr;r;r<r�Ws$	zIMAP4._CRAM_MD5_AUTHcCs�d|_y|jd�\}}Wn,ddtj�dd�g}}YnX|j�d|jkr{d|jdfS||fS)z|Shutdown connection to server.

        (typ, [data]) = <instance>.logout()

        Returns server 'BYE' response.
        r�NOz%s: %sN��BYE)rCr��sys�exc_inforOrF)rQr�r�r;r;r<rq_s	)
zIMAP4.logoutcCs4d}|j|||�\}}|j|||�S)z�List 'subscribed' mailbox names in directory matching pattern.

        (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')

        'data' are tuples of message part envelope and data.
        r%)r�r�)rQr�r�r�r�r�r;r;r<�lsubosz
IMAP4.lsubcCs+|jd|�\}}|j||d�S)z�Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).

        (typ, [data]) = <instance>.myrights(mailbox)
        r")r�r�)rQr�r�r�r;r;r<�myrightszszIMAP4.myrightscCs.d}|j|�\}}|j|||�S)zb Returns IMAP namespaces ala rfc2342

        (typ, [data, ...]) = <instance>.namespace()
        r&)r�r�)rQr�r�r�r;r;r<�	namespace�szIMAP4.namespacecCs
|jd�S)zFSend NOOP command.

        (typ, [data]) = <instance>.noop()
        r')r�)rQr;r;r<r��sz
IMAP4.noopcCs:d}|j|||||�\}}|j||d�S)z�Fetch truncated part of a message.

        (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)

        'data' is tuple of message part envelope and data.
        r(r)r�r�)rQZmessage_numZmessage_part�startZlengthr�r�r�r;r;r<�partial�s!z
IMAP4.partialcCsd}|jd|�S)z�Assume authentication as "user".

        Allows an authorised administrator to proxy into any user's
        mailbox.

        (typ, [data]) = <instance>.proxyauth(user)
        r))r�)rQr�r�r;r;r<�	proxyauth�s	zIMAP4.proxyauthcCs|jd||�S)zkRename old mailbox name to new.

        (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
        r*)r�)rQZ
oldmailboxZ
newmailboxr;r;r<�rename�szIMAP4.renamecGspd}|rE|jr$tjd��|j|d||�\}}n|j||�\}}|j|||�S)z�Search mailbox for matching messages.

        (typ, [data]) = <instance>.search(charset, criterion, ...)

        'data' is space separated list of matching message numbers.
        If UTF8 is enabled, charset MUST be None.
        r+z'Non-None charset not valid in UTF8 mode�CHARSET)rVrr=r�r�)rQ�charsetZcriteriar�r�r�r;r;r<�search�s	!zIMAP4.searchr�FcCs�i|_||_|r!d}nd}|j||�\}}|dkr^d|_||fSd|_d|jkr�|r�|jd|��||jjdd	g�fS)
atSelect a mailbox.

        Flush all untagged responses.

        (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=False)

        'data' is count of messages in mailbox ('EXISTS' response).

        Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
        other responses should be obtained via <instance>.response('FLAGS') etc.
        rr,r`rrz	READ-ONLYz%s is not writable�EXISTSN)rFrHr�rCr?�get)rQr�r?r�r�r�r;r;r<�select�s				
	zIMAP4.selectcCs|jd|||�S)zZSet a mailbox acl.

        (typ, [data]) = <instance>.setacl(mailbox, who, what)
        r-)r�)rQr�r�Zwhatr;r;r<�setacl�szIMAP4.setaclcGs+|jd|�\}}|j||d�S)z_(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+)
        Set ANNOTATIONs.r.r�)r�r�)rQrrr�r�r;r;r<�
setannotation�szIMAP4.setannotationcCs.|jd||�\}}|j||d�S)ziSet the quota root's resource limits.

        (typ, [data]) = <instance>.setquota(root, limits)
        r/r�)r�r�)rQr�Zlimitsr�r�r;r;r<�setquota�szIMAP4.setquotacGs[d}|d|dfdkr*d|}|j||||�\}}|j|||�S)	z�IMAP4rev1 extension SORT command.

        (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
        r0rr|r�r�z(%s)r�)r�r�)r�r�)rQZ
sort_criteriar��search_criteriar�r�r�r;r;r<�sorts

z
IMAP4.sortNcCs�d}ts|jd��|jr3|jd��||jkrQ|jd��|dkritj�}|j|�\}}|dkr�|j|j	d|j
�|_	|j	jd�|_d|_|j
�n|jd	��|j|||�S)
Nr1zSSL support missingzTLS session already establishedzTLS not supported by serverr`�server_hostnamervTzCouldn't establish TLS session)�HAVE_SSLr=rJr>rg�ssl�_create_stdlib_contextr��wrap_socketrwrRrxryrer�)rQ�ssl_contextr�r�r�r;r;r<�starttlss$		
zIMAP4.starttlscCs4d}|j|||�\}}|j|||�S)zpRequest named status conditions for mailbox.

        (typ, [data]) = <instance>.status(mailbox, names)
        r2)r�r�)rQr��namesr�r�r�r;r;r<�status(szIMAP4.statuscCsU|d|dfd	kr$d|}|jd|||�\}}|j||d�S)
z�Alters flag dispositions for messages in mailbox.

        (typ, [data]) = <instance>.store(message_set, command, flags)
        rr|r�r�z(%s)r3rr�)r�r�)r�r�)rQr��commandr�r�r�r;r;r<�store4s
zIMAP4.storecCs|jd|�S)zYSubscribe to new mailbox.

        (typ, [data]) = <instance>.subscribe(mailbox)
        r4)r�)rQr�r;r;r<�	subscribe?szIMAP4.subscribecGs7d}|j||||�\}}|j|||�S)z�IMAPrev1 extension THREAD command.

        (type, [data]) = <instance>.thread(threading_algorithm, charset, search_criteria, ...)
        r5)r�r�)rQZthreading_algorithmr�r�r�r�r�r;r;r<�threadGszIMAP4.threadcGs�|j�}|tkr+|jd|��|jt|krj|jd||jdjt|�f��d}|j|||�\}}|d	kr�|}nd}|j|||�S)
z�Execute "command arg ..." with messages identified by UID,
                rather than message number.

        (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)

        Returns response appropriate to 'command'.
        zUnknown IMAP4 UID command: %sz9command %s illegal in state %s, only allowed in states %sz, r6r+r0r5r)r+r0r5)r�rjr=rC�joinr�r�)rQr�rrr�r�r�r;r;r<�uidQs			z	IMAP4.uidcCs|jd|�S)z_Unsubscribe from old mailbox.

        (typ, [data]) = <instance>.unsubscribe(mailbox)
        r7)r�)rQr�r;r;r<�unsubscribejszIMAP4.unsubscribecGs8|j�}|tkr(|jft|<|j||�S)aAllow simple extension commands
                notified by server in CAPABILITY response.

        Assumes command is legal in current state.

        (typ, [data]) = <instance>.xatom(name, arg, ...)

        Returns response appropriate to extension command `name'.
        )r�rjrCr�)rQr�rrr;r;r<�xatomrs
zIMAP4.xatomcCsL|dkrd}|j}||kr;||j|�n
|g||<dS)N�)rFr�)rQr�r�Zurr;r;r<�_append_untagged�s	zIMAP4._append_untaggedcCs>|jjd�}|r:|j|dj|jd���dS)Nr�r|r�r�)rFr�r>r�rW)rQZbyer;r;r<�
_check_bye�szIMAP4._check_byec
Gs�|jt|krHd|_|jd||jdjt|�f��x'dD]}||jkrO|j|=qOWd|jkr�|jr�|jd��|j�}t	||j
�}|d|}xL|D]D}|dkr�q�t|t�rt	||j
�}|d|}q�W|j}|dk	r}d|_t
|�t
|j�krW|}n&d}|t	d	t|�|j
�}y|j|t�Wn8tk
r�}	z|jd
|	��WYdd}	~	XnX|dkr�|Sx�x!|j�r|j|r�|Sq�W|r||j�}y|j|�|jt�Wn8tk
rq}	z|jd
|	��WYdd}	~	XnX|s�Pq�W|S)Nz9command %s illegal in state %s, only allowed in states %sz, r`r��BADz	READ-ONLYz#mailbox status changed to READ-ONLY� z {%s}zsocket error: %s)r`r�r�)rCrjrDr=r�rFrHr?�_new_tag�bytesrWr�r��type�_commandrr�r�rPr>rdrErG)
rQr�rrr��tagr��argrDZ	literator�valr;r;r<r��s^			


			 &

&zIMAP4._commandcCs�|dkr|j�y|j|�\}}Wn�|jk
rr}z|jd||f��WYdd}~XnA|jk
r�}z|jd||f��WYdd}~XnX|dkr�|j�|dkr�|jd|||f��||fS)Nrzcommand: %s => %sr�z%s command error: %s %s)r��_get_tagged_responser>r=)rQr�r�r�r�r�r;r;r<�_command_complete�s
+,
zIMAP4._command_completecCsk|j�\}}|dgkr0|jd��t|d|j�}|j�}t|j��|_dS)Nz"no CAPABILITY response from serverr|r�)r�r=r�rWr��tuple�splitrg)rQr�r�r;r;r<re�szIMAP4._get_capabilitiescCsc|j�}|j|j|�r�|jjd�}||jkrU|jd|��|jjd�}t||j�}|jjd�}||gf|j|<n]d}|jt	|�s�|j|j
|�r�|jjd�}|jdkr0|jt|�r|jjd�|_dS|jd|��|jjd�}t||j�}|jjd�}|dkrxd}|r�|d|}xb|j|j
|�r�t|jjd	��}|j|�}|j|||f�|j�}q�W|j||�|d
kr_|jt|�r_|jjd�}t||j�}|j||jjd��|S)Nr�zunexpected tagged response: %rr�r�Zdata2zunexpected response: %rr�r�r{r`r�r�)r`r�r�)�	_get_line�_matchrc�mo�grouprEr>r�rW�Untagged_responser^�ContinuationrGr\�intrzr��
Response_code)rQ�respr�r�r�Zdat2r{r�r;r;r<rdsHzIMAP4._get_responsecCsxxq|j|}|dk	r*|j|=|S|j�y|j�Wq|jk
ro}z�WYdd}~XqXqWdS)N)rEr�rdr>)rQr��resultr�r;r;r<r�Ss


zIMAP4._get_tagged_responsecCsW|j�}|s!|jd��|jd�sC|jd|��|dd�}|S)Nzsocket error: EOFs
z#socket error: unterminated line: %rr����)r}r>�endswith)rQr�r;r;r<r�nszIMAP4._get_linecCs|j|�|_|jdk	S)N)�matchr)rQZcre�sr;r;r<r��szIMAP4._matchcCsC|jtt|j�|j�}|jd|_d|j|<|S)Nr|)rbr�r�rIrWrE)rQr�r;r;r<r��s"
zIMAP4._new_tagcCs0|jdd�}|jdd�}d|dS)N�\z\\�"z\")r�)rQr�r;r;r<r��szIMAP4._quotecGs|j||j||��S)N)r�r�)rQr�rrr;r;r<r��szIMAP4._simple_commandcCsN|dkr||fS||jkr2|dgfS|jj|�}||fS)Nr�)rF�pop)rQr�r�r�r�r;r;r<r��s

zIMAP4._untagged_response)Pr8r9r:�__doc__rNr=r>r?�
IMAP4_PORTrTrKr_rMrorprsrurLrzr}r�rOrtr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rqr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rerdr�r�r�r�r�r�r�r;r;r;r<r}s�,*
			

 	
M	Pc@sOeZdZdZdeddddd�Zdd�Zdedd	�ZdS)
�	IMAP4_SSLa3IMAP4 client class over SSL connection

        Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile[, ssl_context]]]]])

                host - host's name (default: localhost);
                port - port number (default: standard IMAP4 SSL port);
                keyfile - PEM formatted file that contains your private key (default: None);
                certfile - PEM formatted certificate chain file (default: None);
                ssl_context - a SSLContext object that contains your certificate chain
                              and private key (default: None)
                Note: if ssl_context is provided, then parameters keyfile or
                certfile should not be set otherwise ValueError is raised.

        for more documentation see the docstring of the parent class IMAP4.
        r@NcCs�|dk	r$|dk	r$td��|dk	rH|dk	rHtd��||_||_|dkr~tjd|d|�}||_tj|||�dS)Nz8ssl_context and keyfile arguments are mutually exclusivez9ssl_context and certfile arguments are mutually exclusive�certfile�keyfile)�
ValueErrorrrr�r�r�rrT)rQrRrSrrr�r;r;r<rT�s				zIMAP4_SSL.__init__cCs(tj|�}|jj|d|j�S)Nr�)rrur�r�rR)rQrwr;r;r<ru�szIMAP4_SSL._create_socketcCstj|||�dS)z�Setup connection to remote server on "host:port".
                (default: localhost:standard IMAP4 SSL port).
            This connection will be used by the routines:
                read, readline, send, shutdown.
            N)rrL)rQrRrSr;r;r<rL�szIMAP4_SSL.open)r8r9r:r�IMAP4_SSL_PORTrTrurLr;r;r;r<r�s
	rc@sdeZdZdZdd�Zdddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)rz�IMAP4 client class over a stream

    Instantiate with: IMAP4_stream(command)

            "command" - a string that can be passed to subprocess.Popen()

    for more documentation see the docstring of the parent class IMAP4.
    cCs||_tj|�dS)N)r�rrT)rQr�r;r;r<rTs	zIMAP4_stream.__init__NcCsd|_d|_d|_d|_tj|jdtdtjdtjdddd�|_	|j	j
|_|j	j|_
dS)z�Setup a stream connection.
        This connection will be used by the routines:
            read, readline, send, shutdown.
        N�bufsize�stdin�stdout�shellTZ	close_fds)rRrSrwry�
subprocess�Popenr�r�PIPEr�r�	writefiler�readfile)rQrRrSr;r;r<rLs				zIMAP4_stream.opencCs|jj|�S)zRead 'size' bytes from remote.)rrz)rQr{r;r;r<rz+szIMAP4_stream.readcCs
|jj�S)zRead line from remote.)rr})rQr;r;r<r}0szIMAP4_stream.readlinecCs!|jj|�|jj�dS)zSend data to remote.N)r�write�flush)rQr�r;r;r<r�5szIMAP4_stream.sendcCs+|jj�|jj�|jj�dS)z Close I/O established in "open".N)rr�rr��wait)rQr;r;r<rO;s

zIMAP4_stream.shutdown)
r8r9r:rrTrLrzr}r�rOr;r;r;r<r
s	c@sFeZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)r�zcPrivate class to provide en/decoding
            for base64-based authentication conversation.
    cCs
||_dS)N)r�)rQZmechinstr;r;r<rTIsz_Authenticator.__init__cCs5|j|j|��}|dkr(dS|j|�S)N�*)r�r�r�)rQr�Zretr;r;r<r�Lsz_Authenticator.processcCs�d}t|t�r$|jd�}xt|r�t|�dkrb|dd�}|dd�}n|}d}tj|�}|r'||dd�}q'W|S)Nr�zutf-8�0r|r�)r�r�r�r�binasciiZ
b2a_base64)rQ�inpZoup�t�er;r;r<r�Rs		z_Authenticator.encodecCs|s
dStj|�S)Nr�)r$Z
a2b_base64)rQr%r;r;r<r�jsz_Authenticator.decodeN)r8r9r:rrTr�r�r�r;r;r;r<r�Cs
r�z0 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Decr�cCs)i|]\}}|d|j��qS)r|)r�)�.0�nrr;r;r<�
<dictcomp>ps	r*r|c	Cs4tj|�}|sdSt|jd�}|jd�}t|jd��}t|jd��}t|jd��}t|jd��}t|jd��}t|jd	��}	t|jd
��}
|	d|
d}|dkr�|}||||||dddf	}tj|�|}
tj|
�S)z�Parse an IMAP4 INTERNALDATE string.

    Return corresponding local time.  The return value is a
    time.struct_time tuple or None if the string has wrong format.
    N�mon�zonen�day�year�hour�min�sec�zoneh�zonem�<�-r|r�r�r�)	�InternalDater
�Mon2numrr�calendarZtimegm�time�	localtime)rrr+r,r-r.r/r0r1r2r3ZzoneZtt�utcr;r;r<rrs$!cCs\d}d}tt|��}x7|rWt|d�\}}|||d�|}q!W|S)z-Convert integer to A-P string representation.r�sABCDEFGHIJKLMNOP�r|)r�abs�divmod)Znumr�ZAP�modr;r;r<r	�s	cCs2tj|�}|sfSt|jd�j��S)z-Convert IMAP4 flags response to python tuple.r�)�Flagsr
r�rr�)rrr;r;r<r
�sc
Cs�t|ttf�r3tj|tj�j�}n0t|t�r�y
|j	}Wnqt
k
r�tjr�|d}|dkr�tj
tj|��d}tjtjf|}n
tj}YnXtd|�}t|dd�dt|��}nlt|t�r*|jdkr!td��|}n9t|t�rW|d|d
fdkrW|Std
��djt|j�}|j|�S)a�Convert date_time to IMAP4 INTERNALDATE representation.

    Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'.  The
    date_time argument can be a number (int or float) representing
    seconds since epoch (as returned by time.time()), a 9-tuple
    representing local time, an instance of time.struct_time (as
    returned by time.localtime()), an aware datetime instance or a
    double-quoted string.  In the last case, it is assumed to already
    be in the correct format.
    �r|ZsecondsN��tzinfozdate_time must be awarerr
zdate_time not of a known typez"%d-{}-%Y %H:%M:%S %z"r�r�)r
r
)r�r�floatrZ
fromtimestamprr;Z
astimezoner�Z	tm_gmtoffrmr9Zdaylightr:ZmktimeZaltzonerrCrr��format�MonthsZmonthZstrftime)r�ZdtZgmtoffZdstZdeltaZfmtr;r;r<r�s0	

	
%	)�__main__zd:s:z-dz-sr@zIMAP password for %s on %s: Z	localhostzJFrom: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)sr�Zlf�
r�r�z
/tmp/xxx 1r�z/tmp/yyyz
/tmp/yyz 2r�r�z/tmpzyy*r�r�ZSUBJECTZtestr��1z(FLAGS INTERNALDATE RFC822)r��FLAGSz
(\Deleted)r�r�r�r�r�ZUIDVALIDITYr�ZALLr�rqcCsftjd||f�tt|�|�\}}tjd|||f�|dkrb|d�|S)Nz%s %sz%s => %s %sr�r)�M�_mesgrk)�cmdrrr�r�r;r;r<�runs
rNzPROTOCOL_VERSION = %szCAPABILITIES = %rz/tmp/zyy%z.*"([^"]+)"$r�z%sz:(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)z
All tests OK.z
Tests failed.z8
If you would like to see debugging output,
try: %s -d5
)Ur�__version__r$r�rarXrtrr�r9r8rrr�iorr�r��ImportError�__all__r�rArrrfr~rjrYrr@r6r[r\r�rrr^rZr]rrr�rr�r�rF�	enumerater7rr	r
rr8ZgetoptZgetpass�argvZoptlistrrr=r�Zstream_commandZoptrrRZgetuserZUSERZPASSWDZ	test_mesgZ	test_seq1Z	test_seq2rNrKrCrLrhrgrMZmlr
rr�pathr�r��printr;r;r;r<�<module>s<l

																		����[1
9,##
))%
	
					


?>