Your IP : 18.219.247.59


Current Path : /opt/alt/python34/lib64/python3.4/__pycache__/
Upload File :
Current File : //opt/alt/python34/lib64/python3.4/__pycache__/imaplib.cpython-34.pyc

�
i f[��%@s�dZdZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZmZm
Z
ddlmZyddlZdZWnek
r�dZYnXdd	d
ddd
gZdZdZdZdZddfZdZi'ddfd6dfd6ddddfd6dfd6dfd6dfd6ddfd6ddfd6ddfd6ddfd 6dfd!6dfd"6ddfd#6ddfd$6ddfd%6ddfd&6ddfd'6ddfd(6dfd)6ddddfd6ddfd*6ddfd+6ddddfd,6dfd-6dfd.6ddfd/6dfd06ddfd16ddfd26ddfd36ddfd46dfd56dfd66ddfd76dfd86ddfd96dfd:6dfd;6ddfd<6Zejd=�Zejd>�Zejd?�Zejd@ej�Z ejdA�Z!ejdB�Z"ejdC�Z#ejdDej�Z$GdEd�d�Z%er�GdFdG�dGe%�Z&ej'dG�nGdHd	�d	e%�Z(GdIdJ�dJ�Z)dKj*dL�Z+dMdN�e,e+dOd��D�Z-dPd
�Z.dQd�Z/dRd�Z0dSd
�Z1e2dTkr�ddl3Z3ddl4Z4y)e3j3ej5dOd�dU�\Z6Z7Wn:e3j8k
r�Z9zfff\Z6Z7WYddZ9[9XnXdZ:xWe6D]O\Z;Z9e;dVkr	e<e9�Zn(e;dWkr1e9Z:e7r.e:fZ7nnq�We7rHdXfZ7ne7dZ=e4j>�Z?e4j4dYe?e=psdZf�Z@d[ie?d\6d]d^6ZAd_e?e@ffd`daffdbdadcffdddffdeddddeAffdfdgdhffdiddffdjddkdlffdmdndoffdpdndqdrffdsffdtffduffdvfffZBdiffdwdxffdyd0dzffdwd{ffdedddeAffduffd|fffZCd}d~�ZDy�e:r�e(e:�ZEne%e=�ZEeEjFdkreBdOd�ZBneEjGdeEjH�eEjGd�eEjIf�x!eBD]\ZJZ7eDeJe7�q9WxheDdfd�d�f�D]QZKejLd�eK�ZMeMr�eMjNdO�ZOneKj*�dOZOeDd�eOf�qlWx�eCD]|\ZJZ7eDeJe7�ZPeJe7fdyd0dzffkrq�nePdOj*�ZQeQr%q�neDdyd"d�eQdOd�f�q�WeRd��Wn4eRd��er�eRd�ej5d�n�YnXndS)�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�AUTH�SELECTED�APPEND�NONAUTH�AUTHENTICATE�LOGOUT�
CAPABILITY�CHECK�CLOSE�COPY�CREATE�DELETE�	DELETEACL�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dedd�Z
dd�Zdd�Zdd�Zdd�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@dAdB�Z$dCdD�Z%dEdF�Z&dGdH�Z'dIdJ�Z(d?d@dKdL�Z)dMdN�Z*dOdP�Z+dQdR�Z,dSdT�Z-dUdV�Z.dWdX�Z/dYdZ�Z0d[d\d]d^�Z1d_d`�Z2dadb�Z3dcdd�Z4dedf�Z5dgdhdi�Z6djdk�Z7dldm�Z8dndo�Z9dpdq�Z:drds�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��ZJdgd�d��ZKd�d��ZLd�d��ZMd�d��ZNdgS)�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/python34/lib64/python3.4/imaplib.py�error�sr<c@seZdZdS)zIMAP4.abortN)r7r8r9r:r:r:r;�abort�sr=c@seZdZdS)zIMAP4.readonlyN)r7r8r9r:r:r:r;�readonly�sr>�cCs�t|_d|_d|_i|_i|_d|_d|_d|_d|_	|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�open�_connect�	Exception�shutdown�OSError)�self�host�portr:r:r;�__init__�s$									

zIMAP4.__init__cCs]ttjdd��|_tjd|jdtj�|_d|_d|_	i|_
|jdkr�|jdt
�|jd	|j�n|j�|_d
|jkr�d|_n-d|jkr�d
|_n|j|j��|j�|jdkr|jd|jf�nx-tD]%}||jkr<q!n||_dSW|jd��dS)Nii��s(?P<tag>s"\d+) (?P<type>[A-Z]+) (?P<data>.*)�
r�zimaplib version %sznew IMAP4 connection, tag=%sZPREAUTHr
�OKr�zCAPABILITIES: %rzserver not IMAP4 compliant)r	�randomZrandint�tagpre�re�compile�ASCII�tagre�_cmd_log_len�_cmd_log_idx�_cmd_logrA�_mesg�__version__�
_get_responseZwelcomerErBr<�_get_capabilities�capabilities�AllowedVersions�PROTOCOL_VERSION)rO�versionr:r:r;rK�s0			

	zIMAP4._connectcCs3|tkrt||j��Std|��dS)NzUnknown IMAP4 command: '%s')�Commands�getattr�lower�AttributeError)rO�attrr:r:r;�__getattr__�szIMAP4.__getattr__cCstj|j|jf�S)N)�socketZcreate_connectionrPrQ)rOr:r:r;�_create_socket�szIMAP4._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)rPrQro�sock�makefile�file)rOrPrQr:r:r;rJ�s		z
IMAP4.opencCs|jj|�S)zRead 'size' bytes from remote.)rs�read)rO�sizer:r:r;rtsz
IMAP4.readcCsB|jjtd�}t|�tkr>|jdt��n|S)zRead line from remote.rTzgot more than %d bytes)rs�readline�_MAXLINE�lenr<)rO�liner:r:r;rvszIMAP4.readlinecCs|jj|�dS)zSend data to remote.N)rqZsendall)rO�datar:r:r;�sendsz
IMAP4.sendcCs}|jj�z[y|jjtj�Wn=tk
rf}z|jtjkrT�nWYdd}~XnXWd|jj�XdS)z Close I/O established in "open".N)	rs�closerqrMrnZ	SHUT_RDWRrN�errnoZENOTCONN)rO�er:r:r;rMs
zIMAP4.shutdowncCs|jS)zfReturn socket instance used to connect to IMAP4 server.

        socket = <instance>.socket()
        )rq)rOr:r:r;rn%sz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.
        ZRECENTrUNrT���)�_untagged_response�noop)rO�name�typ�datr:r:r;�recent1s	

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)rO�coder:r:r;�responseBszIMAP4.responsecCs�d}|sd}n|rE|d|d	fd
krKd|}qKnd}|r`t|�}nd}tjt|�|_|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�INBOXrrT�(�)z(%s)Nr)r�r�)r�MapCRLF�sub�CRLFrC�_simple_command)rO�mailbox�flags�	date_time�messager�r:r:r;�appendPs	zIMAP4.appendcCsk|j�}t|�j|_|jd|�\}}|dkrX|j|d��nd|_||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.
        rrUrTr
r)r��_Authenticator�processrCr�r<rB)rOZ	mechanismZ
authobject�mechr�r�r:r:r;�authenticategs	zIMAP4.authenticatecCs.d}|j|�\}}|j|||�S)zT(typ, [data]) = <instance>.capability()
        Fetch capabilities list from server.r)r�r�)rOr�r�r�r:r:r;�
capability�szIMAP4.capabilitycCs
|jd�S)zRCheckpoint mailbox on server.

        (typ, [data]) = <instance>.check()
        r)r�)rOr: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�rB)rOr�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�)rO�message_setZnew_mailboxr:r:r;�copy�sz
IMAP4.copycCs|jd|�S)zPCreate new mailbox.

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

        (typ, [data]) = <instance>.delete(mailbox)
        r)r�)rOr�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�)rOr��whor:r:r;�	deleteacl�szIMAP4.deleteaclcCs.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�)rOr�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�)rOr�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�)rOr�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�)rOr��entryZ	attributer�r�r:r:r;�
getannotation�szIMAP4.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�)rO�rootr�r�r:r:r;�getquota�szIMAP4.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�)rOr�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�)rO�	directory�patternr�r�r�r:r:r;�listsz
IMAP4.listcCsY|jd||j|��\}}|dkrF|j|d��nd|_||fS)z�Identify client using plaintext password.

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

        NB: 'password' will be quoted.
        r#rUrTr
r)r��_quoter<rB)rO�user�passwordr�r�r:r:r;�logins
$	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)rOr�r�r:r:r;�login_cram_md5 szIMAP4.login_cram_md5cCs]ddl}t|jt�r0|jjd�n|j}|jd|j||d�j�S)z1 Authobject to use with CRAM-MD5 authentication. rNr[� Zmd5)�hmac�
isinstancer��str�encoder�ZHMACZ	hexdigest)rOZ	challenger��pwdr:r:r;r�)s$	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)rBr��sys�exc_inforMrE)rOr�r�r:r:r;�logout1s	)
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�)rOr�r�r�r�r�r:r:r;�lsubAsz
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�)rOr�r�r�r:r:r;�myrightsLszIMAP4.myrightscCs.d}|j|�\}}|j|||�S)zb Returns IMAP namespaces ala rfc2342

        (typ, [data, ...]) = <instance>.namespace()
        r%)r�r�)rOr�r�r�r:r:r;�	namespaceTszIMAP4.namespacecCs/|jdkr"|j|j�n|jd�S)zFSend NOOP command.

        (typ, [data]) = <instance>.noop()
        rVr&)rA�_dump_urrEr�)rOr: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�)rOZmessage_numZmessage_part�startZlengthr�r�r�r:r:r;�partialis!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�)rOr�r�r:r:r;�	proxyauthus	zIMAP4.proxyauthcCs|jd||�S)zkRename old mailbox name to new.

        (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
        r))r�)rOZ
oldmailboxZ
newmailboxr:r:r;�rename�szIMAP4.renamecGsXd}|r-|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.
        r*�CHARSET)r�r�)rO�charsetZcriteriar�r�r�r:r:r;�search�s
!zIMAP4.searchr�FcCs�i|_||_|r!d}nd}|j||�\}}|dkr^d|_||fSd|_d|jkr�|r�|jdkr�|j|j�n|jd|��n||jjd	d
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+rUr
rz	READ-ONLYrTz%s is not writable�EXISTSN)rErGr�rBrAr�r>�get)rOr�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�)rOr�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�)rO�argsr�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�)rOr�Zlimitsr�r�r:r:r;�setquota�szIMAP4.setquotacGs^d}|d|dfdkr-d|}n|j||||�\}}|j|||�S)	z�IMAP4rev1 extension SORT command.

        (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
        r/rrTr�r�z(%s)r)r�r�)r�r�)rOZ
sort_criteriar��search_criteriar�r�r�r:r:r;�sort�s

z
IMAP4.sortNcCsd}ts|jd��n|jr9|jd��n||jkrZ|jd��n|dkrutj�}n|j|�\}}|dkr�|j|j	d|j
�|_	|j	jd�|_d|_|j
�n|jd	��|j|||�S)
Nr0zSSL support missingzTLS session already establishedzTLS not supported by serverrU�server_hostnamerpTzCouldn't establish TLS session)�HAVE_SSLr<rIr=rd�ssl�_create_stdlib_contextr��wrap_socketrqrPrrrsrcr�)rO�ssl_contextr�r�r�r:r:r;�starttls�s$		
zIMAP4.starttlscCs4d}|j|||�\}}|j|||�S)zpRequest named status conditions for mailbox.

        (typ, [data]) = <instance>.status(mailbox, names)
        r1)r�r�)rOr��namesr�r�r�r:r:r;�status�szIMAP4.statuscCsX|d|dfd	kr'd|}n|jd|||�\}}|j||d�S)
z�Alters flag dispositions for messages in mailbox.

        (typ, [data]) = <instance>.store(message_set, command, flags)
        rrTr�r�z(%s)r2rr)r�r�)r�r�)rOr��commandr�r�r�r:r:r;�stores
zIMAP4.storecCs|jd|�S)zYSubscribe to new mailbox.

        (typ, [data]) = <instance>.subscribe(mailbox)
        r3)r�)rOr�r:r:r;�	subscribeszIMAP4.subscribecGs7d}|j||||�\}}|j|||�S)z�IMAPrev1 extension THREAD command.

        (type, [data]) = <instance>.thread(threading_algorithm, charset, search_criteria, ...)
        r4)r�r�)rOZthreading_algorithmr�r�r�r�r�r:r:r;�threadszIMAP4.threadcGs�|j�}|tkr.|jd|��n|jt|krp|jd||jdjt|�f��nd}|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, r5r*r/r4r)zSEARCHzSORTzTHREAD)r�rhr<rB�joinr�r�)rOr�r�r�r�r�r:r:r;�uid s			z	IMAP4.uidcCs|jd|�S)z_Unsubscribe from old mailbox.

        (typ, [data]) = <instance>.unsubscribe(mailbox)
        r6)r�)rOr�r:r:r;�unsubscribe9szIMAP4.unsubscribecGs;|j�}|tkr+|jft|<n|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�rhrBr�)rOr�r�r:r:r;�xatomAs
zIMAP4.xatomcCs�|dkrd}n|j}|jdkr\|jd|t|j|d��|f�n||kr|||j|�n
|g||<dS)N��z#untagged_responses[%s] %s += ["%r"]r?)rErAr`rxr�r�)rOr�r�Zurr:r:r;�_append_untaggedWs			&zIMAP4._append_untaggedcCs>|jjd�}|r:|j|djdd���ndS)Nr�rT�ascii�replacer)rEr�r=�decode)rOZbyer:r:r;�
_check_byeeszIMAP4._check_byec
Gs�|jt|krKd|_|jd||jdjt|�f��nx*dD]"}||jkrR|j|=qRqRWd|jkr�|jr�|jd��n|j�}t	|d�}|d	|}xO|D]G}|dkr�q�nt
|t�rt	|d�}n|d	|}q�W|j}|dk	r�d|_t|�t|j
�kr`|}q�d}|t	d
t|�d�}n|jdkr�|jd|�n|jd|�y|j|t�Wn8tk
r	}	z|jd
|	��WYdd}	~	XnX|dkr|Sx�x!|j�r@|j|r |Sq W|rY||j�}n|jdkr�|jdt|��ny|j|�|jt�Wn8tk
r�}	z|jd
|	��WYdd}	~	XnX|sPqqW|S)Nz9command %s illegal in state %s, only allowed in states %sz, rUr��BADz	READ-ONLYz#mailbox status changed to READ-ONLYr[� z {%s}�z> %rzsocket error: %szwrite literal size %s)zOKzNOr�)rBrhrCr<r�rErGr>�_new_tag�bytesr�r��type�_commandrxrAr`�_logr{r�rNr=rbrDrF)
rOr�r�r��tagrz�argrCZ	literator�valr:r:r;r�ksh			


			 &

&zIMAP4._commandcCs|dkr|j�ny|j|�\}}Wn�|jk
ru}z|jd||f��WYdd}~XnA|jk
r�}z|jd||f��WYdd}~XnX|dkr�|j�n|dkr�|jd|||f��n||fS)Nrzcommand: %s => %sr�z%s command error: %s %s)r��_get_tagged_responser=r<)rOr�r�r�rzr�r:r:r;�_command_complete�s
+,
zIMAP4._command_completecCsk|j�\}}|dgkr3|jd��nt|dd�}|j�}t|j��|_dS)Nz"no CAPABILITY response from serverrTr[r)r�r<r�r��tuple�splitrd)rOr�r�r:r:r;rc�szIMAP4._get_capabilitiescCs�|j�}|j|j|�r�|jjd�}||jkrX|jd|��n|jjd�}t|d�}|jjd�}||gf|j|<n�d}|jt|�s�|jt	|�r�|jjd�}q�n|jdkr6|jt
|�r |jjd�|_dS|jd|��n|jjd�}t|d�}|jjd�}|dkr~d	}n|r�|d
|}nx�|jt|�rt
|jjd��}|jdkr�|jd
|�n|j|�}|j|||f�|j�}q�W|j||�|dkr�|jt|�r�|jjd�}t|d�}|j||jjd��n|jdkr�|dkr�|jd||f�n|S)Nr�zunexpected tagged response: %sr�r[rzZdata2zunexpected response: '%s'r�r�r�rur�zread literal size %srUr�r�rTr�z%s response: %r)zOK�NO�BAD)r�r�zBYE)�	_get_line�_matchr\�mo�grouprDr=r��Untagged_response�Untagged_status�ContinuationrF�Literal�intrAr`rtr��
Response_code)rO�respr�r�r�Zdat2rurzr:r:r;rb�sP	zIMAP4._get_responsecCs�x�|j|}|dk	r*|j|=|S|j�y|j�Wq|jk
r�}z$|jdkrv|j�n�WYdd}~XqXqWdS)NrT)rDr�rbr=rA�	print_log)rOr��resultr�r:r:r;r�"s



zIMAP4._get_tagged_responsecCs�|j�}|s$|jd��n|jd�sI|jd|��n|dd�}|jdkr||jd|�n|jd|�|S)Nzsocket error: EOFs
z#socket error: unterminated line: %rr�r�z< %r���)rvr=�endswithrAr`r�)rOryr:r:r;r�=szIMAP4._get_linecCsc|j|�|_|jdk	rV|jdkrV|jd|j|jj�f�n|jdk	S)Nr�z	matched r'%r' => %r)�matchrrAr`r��groups)rOZcre�sr:r:r;r�Ps&zIMAP4._matchcCs@|jtt|j�d�}|jd|_d|j|<|S)Nr[rT)rXr�r�rHrD)rOr�r:r:r;r�\s
zIMAP4._new_tagcCs0|jdd�}|jdd�}d|dS)N�\z\\�"z\")r�)rOr�r:r:r;r�dszIMAP4._quotecGs|j||j||��S)N)r�r�)rOr�r�r:r:r;r�lszIMAP4._simple_commandcCsw|dkr||fS||jkr2|dgfS|jj|�}|jdkrm|jd||f�n||fS)Nr�r�zuntagged_responses[%s] => %s)rE�poprAr`)rOr�r�r�rzr:r:r;r�qs

zIMAP4._untagged_responsecCsl|dkrtj�}ntjdtj|��}tjjd||dd|f�tjj�dS)Nz%M:%Sz
  %s.%02d %s
�d)�time�strftime�	localtimer��stderr�write�flush)rOrZsecsZtmr:r:r;r`s
%zIMAP4._mesgcCsU|j�}|sdSd}tdd�|�}|jd||j|�f�dS)Nz
		cSs3d|d|ddr+dj|d�p.dfS)Nz%s: "%s"rrTz" "r?)r�)�xr:r:r;�<lambda>�sz IMAP4._dump_ur.<locals>.<lambda>zuntagged responses dump:%s%s)�items�mapr`r�)rO�dict�l�tr:r:r;r��szIMAP4._dump_urcCsM|tj�f|j|j<|jd7_|j|jkrId|_ndS)NrTr)rr_r^r])rOryr:r:r;r��sz
IMAP4._logc	Cs�|jdt|j��|j|j}}xY|r�y|j|j|�WnYnX|d7}||jkr{d}n|d8}q0WdS)Nzlast %d IMAP4 interactions:rTr)r`rxr_r^r])rO�i�nr:r:r;r	�s	
	zIMAP4.print_log)Or7r8r9�__doc__rLr<r=r>�
IMAP4_PORTrRrKrmrorJrtrvr{rMrnr�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�r�r�r�r�r�r�r�r�r�r�r�rcrbr�r�r�r�r�r�r�r`r�r�r	r:r:r:r;rws�,*
			

 	
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��n|dk	rN|dk	rNtd��n||_||_|dkr�tjd|d|�}n||_tj|||�dS)Nz8ssl_context and keyfile arguments are mutually exclusivez9ssl_context and certfile arguments are mutually exclusive�certfile�keyfile)�
ValueErrorr'r&r�r�r�rrR)rOrPrQr'r&r�r:r:r;rR�s			zIMAP4_SSL.__init__cCs(tj|�}|jj|d|j�S)Nr�)rror�r�rP)rOrqr:r:r;ro�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)rrJ)rOrPrQr:r:r;rJ�szIMAP4_SSL.open)r7r8r9r#�IMAP4_SSL_PORTrRrorJr:r:r:r;r%�sr%c@sdeZdZdZdd�Zdddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)rz�IMAP4 client class over a stream

    Instantiate with: IMAP4_stream(command)

            where "command" is 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�rrR)rOr�r:r:r;rR�s	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)rPrQrqrs�
subprocess�Popenr�r�PIPEr�r+�	writefiler,�readfile)rOrPrQr:r:r;rJ�s				zIMAP4_stream.opencCs|jj|�S)zRead 'size' bytes from remote.)r2rt)rOrur:r:r;rt�szIMAP4_stream.readcCs
|jj�S)zRead line from remote.)r2rv)rOr:r:r;rv�szIMAP4_stream.readlinecCs!|jj|�|jj�dS)zSend data to remote.N)r1rr)rOrzr:r:r;r{szIMAP4_stream.sendcCs+|jj�|jj�|jj�dS)z Close I/O established in "open".N)r2r|r1r��wait)rOr:r:r;rM	s

zIMAP4_stream.shutdown)
r7r8r9r#rRrJrtrvr{rMr: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�)rOZmechinstr:r:r;rRsz_Authenticator.__init__cCs5|j|j|��}|dkr(dS|j|�S)N�*)r�r�r�)rOrzZretr:r:r;r�sz_Authenticator.processcCs�d}t|t�r'|jd�}nxw|r�t|�dkre|dd�}|dd�}n|}d}tj|�}|r*||dd�}q*q*W|S)Nr�r[�0rTr)r�r�r�rx�binasciiZ
b2a_base64)rO�inpZoupr r~r:r:r;r� s		z_Authenticator.encodecCs|s
dStj|�S)Nr�)r6Z
a2b_base64)rOr7r:r:r;r�8sz_Authenticator.decodeN)r7r8r9r#rRr�r�r�r:r:r:r;r�s
r�z0 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Decr�cCs)i|]\}}|d|j��qS)rT)r�)�.0r"rr:r:r;�
<dictcomp>>s	r9rTc	Cs7tj|�}|sdSt|jd�}|jd�}t|jd��}t|jd��}t|jd��}t|jd��}t|jd��}t|jd	��}	t|jd
��}
|	d|
d}|dkr�|}n||||||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�<�-rTrrr)	�InternalDater
�Mon2numrr�calendarZtimegmrr)rrr:r;r<r=r>r?r@rArBZzoneZtt�utcr:r:r;r@s$
!cCs\d}d}tt|��}x7|rWt|d�\}}|||d�|}q!W|S)z-Convert integer to A-P string representation.r�sABCDEFGHIJKLMNOP�rT)r�abs�divmod)Znumr�ZAP�modr:r:r;r	cs	cCs2tj|�}|sfSt|jd�j��S)z-Convert IMAP4 flags response to python tuple.r�)�Flagsr
r�rr�)rrr:r:r;r
pscCs�t|ttf�r3tj|tj�j�}n6t|t�r�y
|j	}Wntt
k
r�tjr�|d}|dkr�tj
tj|��d}ntjtjf|}n
tj}YnXtd|�}tdt|�|dd��}not|t�r0|jdkr'td��n|}n9t|t�r]|d|d
fdkr]|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.
    �rTZseconds�tzinfoN�zdate_time must be awarerrzdate_time not of a known typez"%d-{}-%Y %H:%M:%S %z"rr)rr)r�r�floatrZ
fromtimestamprrHZ
astimezoner�Z	tm_gmtoffrkrZdaylightrZmktimeZaltzonerrOr(r��format�MonthsZmonthr)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��
Zlfr�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�r�cCsitjd||f�tt|�|�\}}tjd|||f�|dkre|d�n|S)Nz%s %sz%s => %s %sr�r)�Mr`ri)�cmdr�r�r�r:r:r;�run�s
rZzPROTOCOL_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
)Sr#rar6r}rWrYrnr.r�rrGrrr�iorr�r��ImportError�__all__r�r@r$r)rerwrhrZrrMrEr[rr�rrrrr%r�rr�r�rS�	enumeraterFrr	r
rr7ZgetoptZgetpass�argvZoptlistr�r<r�Zstream_commandZoptrrPZgetuserZUSERZPASSWDZ	test_mesgZ	test_seq1Z	test_seq2rZrXrBr`rfrdrYZmlr
rr�pathr�r��printr:r:r:r;�<module>s8l

		


































����009,##
))%
					


?>