U
    W+d3                     @   s  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddlZddl	Z
ddlZddlmZ ddlmZ ddlZddlZddlZddlZddlmZmZ ddlmZmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlm Z  ddl!m"Z" dZ#z(ddl$Z$ddlm%Z% e&e$dr.dZ#W n e'k
rF   Y nX zddl(Z(W n e'k
rr   ddl)Z(Y nX e*dd dD Z+dddZ,ej-.ej-/ej-0ej1j2dZ3G dd de4Z5G dd de4Z6G dd de4Z7G dd  d ej8Z8G d!d" d"e4Z9G d#d$ d$e9Z:dS )%z"
Handles basic connections to AWS
    )datetimeN)auth)auth_handler)config	UserAgent)sixhttp_clienturlparsequoteencodebytes)AWSConnectionError)BotoClientError)BotoServerError)PleaseRetryException)Provider)	ResultSetF)https_connectionSSLErrorTc                 c   s   | ]}|t jkV  qd S N)osenviron).0key r   3/tmp/pip-unpacked-wheel-dlxw5sjy/boto/connection.py	<genexpr>W   s     r   )ZUSER_IS_ADMINZCURRENT_VERSION_IDZAPPLICATION_ID  P   )TFzcacerts.txtc                   @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )HostConnectionPoola  
    A pool of connections for one remote (host,port,is_secure).

    When connections are added to the pool, they are put into a
    pending queue.  The _mexe method returns connections to the pool
    before the response body has been read, so they connections aren't
    ready to send another request yet.  They stay in the pending queue
    until they are ready for another request, at which point they are
    returned to the pool of ready connections.

    The pool of ready connections is an ordered list of
    (connection,time) pairs, where the time is the time the connection
    was returned from _mexe.  After a certain period of time,
    connections are considered stale, and discarded rather than being
    reused.  This saves having to wait for the connection to time out
    if AWS has decided to close it on the other end because of
    inactivity.

    Thread Safety:

        This class is used only from ConnectionPool while it's mutex
        is held.
    c                 C   s
   g | _ d S r   )queueselfr   r   r   __init__z   s    zHostConnectionPool.__init__c                 C   s
   t | jS )z
        Returns the number of connections in the pool for this host.
        Some of the connections may still be in use, and may not be
        ready to be returned by get().
        )lenr   r    r   r   r   size}   s    zHostConnectionPool.sizec                 C   s   | j |t f dS )zZ
        Adds a connection to the pool, along with the time it was
        added.
        N)r   appendtime)r!   connr   r   r   put   s    zHostConnectionPool.putc                 C   sL   |    tt| jD ]0}| jd\}}| |r<|  S | | qdS )z
        Returns the next connection in this pool that is ready to be
        reused.  Returns None if there aren't any.
        r   N)cleanranger#   r   pop_conn_readyr(   )r!   _r'   r   r   r   get   s    
zHostConnectionPool.getc                 C   s(   t rdS t|dd}|dkp"| S dS )aZ  
        There is a nice state diagram at the top of http_client.py.  It
        indicates that once the response headers have been read (which
        _mexe does before adding the connection to the pool), a
        response is attached to the connection, and it stays there
        until it's done reading.  This isn't entirely true: even after
        the client is done reading, the response may be closed, but
        not removed from the connection yet.

        This is ugly, reading a private instance variable, but the
        state we care about isn't available in any public methods.
        F_HTTPConnection__responseN)ON_APP_ENGINEgetattrisclosed)r!   r'   responser   r   r   r,      s    zHostConnectionPool._conn_readyc                 C   s0   t | jdkr,| | jd r,| jd q dS )z/
        Get rid of stale connections.
        r   N)r#   r   _pair_staler+   r    r   r   r   r)      s    zHostConnectionPool.cleanc                 C   s   |\}}t   }|tj |k S )z[
        Returns true of the (connection,time) pair is too old to be
        used.
        )r&   ConnectionPoolSTALE_DURATION)r!   pairZ_connZreturn_timenowr   r   r   r4      s    zHostConnectionPool._pair_staleN)__name__
__module____qualname____doc__r"   r$   r(   r.   r,   r)   r4   r   r   r   r   r   `   s   	r   c                   @   sP   e Zd ZdZdZdZdd Zdd Zdd	 Zd
d Z	dd Z
dd Zdd ZdS )r5   z
    A connection pool that expires connections after a fixed period of
    time.  This saves time spent waiting for a connection that AWS has
    timed out on the other end.

    This class is thread-safe.
    g      @g      N@c                 C   s,   i | _ d| _t | _tddtjt_d S )Ng        BotoZconnection_stale_duration)	host_to_poollast_clean_time	threadingLockmutexr   getfloatr5   r6   r    r   r   r   r"      s    
zConnectionPool.__init__c                 C   s   t  | j}i |d< |d= |S )Nr>   rB   )copy__dict__)r!   Zpickled_dictr   r   r   __getstate__   s    zConnectionPool.__getstate__c                 C   s   |    d S r   )r"   )r!   dctr   r   r   __setstate__   s    zConnectionPool.__setstate__c                 C   s   t dd | j D S )z@
        Returns the number of connections in the pool.
        c                 s   s   | ]}|  V  qd S r   )r$   )r   poolr   r   r   r      s     z&ConnectionPool.size.<locals>.<genexpr>)sumr>   valuesr    r   r   r   r$      s    zConnectionPool.sizec              
   C   sV   |    | j> |||f}|| jkr2W 5 Q R  dS | j|  W  5 Q R  S Q R X dS )z
        Gets a connection from the pool for the named host.  Returns
        None if there is no connection that can be reused. It's the caller's
        responsibility to call close() on the connection when it's no longer
        needed.
        N)r)   rB   r>   r.   )r!   hostport	is_securer   r   r   r   get_http_connection  s    

z"ConnectionPool.get_http_connectionc              	   C   sF   | j 6 |||f}|| jkr(t | j|< | j| | W 5 Q R X dS )zm
        Adds a connection to the pool of connections that can be
        reused for the named host.
        N)rB   r>   r   r(   )r!   rL   rM   rN   r'   r   r   r   r   put_http_connection  s
    

z"ConnectionPool.put_http_connectionc              	   C   s|   | j l t }| j| j |k rng }| j D ]&\}}|  | dkr.|| q.|D ]}| j|= qZ|| _W 5 Q R X dS )a+  
        Clean up the stale connections in all of the pools, and then
        get rid of empty pools.  Pools clean themselves every time a
        connection is fetched; this cleaning takes care of pools that
        aren't being used any more, so nothing is being gotten from
        them.
        r   N)	rB   r&   r?   CLEAN_INTERVALr>   itemsr)   r$   r%   )r!   r8   Z	to_removerL   rI   r   r   r   r)     s    
zConnectionPool.cleanN)r9   r:   r;   r<   rQ   r6   r"   rF   rH   r$   rO   rP   r)   r   r   r   r   r5      s   r5   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )HTTPRequestc
           
      C   s|   || _ || _|| _|| _|| _|dkr*|}|| _|| _|rld|krl|d dkrl| j dkrl| | _| jd= n|| _|	| _	dS )ay  Represents an HTTP request.

        :type method: string
        :param method: The HTTP method name, 'GET', 'POST', 'PUT' etc.

        :type protocol: string
        :param protocol: The http protocol used, 'http' or 'https'.

        :type host: string
        :param host: Host to which the request is addressed. eg. abc.com

        :type port: int
        :param port: port on which the request is being sent. Zero means unset,
            in which case default port will be chosen.

        :type path: string
        :param path: URL path that is being accessed.

        :type auth_path: string
        :param path: The part of the URL path used when creating the
            authentication string.

        :type params: dict
        :param params: HTTP url query parameters, with key as name of
            the param, and value as value of param.

        :type headers: dict
        :param headers: HTTP headers, with key as name of the header and value
            as value of header.

        :type body: string
        :param body: Body of the HTTP request. If not present, will be None or
            empty string ('').
        NTransfer-EncodingchunkedPUT)
methodprotocolrL   rM   path	auth_pathparamsrD   headersbody)
r!   rW   rX   rL   rM   rY   rZ   r[   r\   r]   r   r   r   r"   1  s$    $


zHTTPRequest.__init__c              	   C   s(   d| j | j| j| j| j| j| j| jf S )NzTmethod:(%s) protocol:(%s) host(%s) port(%s) path(%s) params(%s) headers(%s) body(%s))rW   rX   rL   rM   rY   r[   r\   r]   r    r   r   r   __str__h  s         zHTTPRequest.__str__c                 K   s   t | ddsT| jD ]4}| j| }t|tjrd}t|d|| j|< qt| dd t| jd< |j	j
| f| d| jkrd| jks| jd d	krtt| j| jd< d S )
NZ_headers_quotedFz!"#$%&'()*+,/:;<=>?@[\]^`{|}~ utf-8Tz
User-AgentzContent-LengthrT   rU   )r1   r\   
isinstancer   	text_typer
   encodesetattrr   _auth_handlerZadd_authstrr#   r]   )r!   
connectionkwargsr   valsafer   r   r   	authorizen  s    




zHTTPRequest.authorizeN)r9   r:   r;   r"   r^   rj   r   r   r   r   rS   /  s   7rS   c                   @   s   e Zd Zdd ZdddZdS )HTTPResponsec                 O   s   t jj| f|| d| _d S )N )r   rk   r"   _cached_response)r!   argsrg   r   r   r   r"     s    zHTTPResponse.__init__Nc                 C   s4   |dkr"| j stj| | _ | j S tj| |S dS )a<  Read the response.

        This method does not have the same behavior as
        http_client.HTTPResponse.read.  Instead, if this method is called with
        no ``amt`` arg, then the response body will be cached.  Subsequent
        calls to ``read()`` with no args **will return the cached response**.

        N)rm   r   rk   read)r!   amtr   r   r   ro     s
    	zHTTPResponse.read)N)r9   r:   r;   r"   ro   r   r   r   r   rk     s   rk   c                   @   s@  e Zd Zd?ddZdd	 Zd
d Zdd Zdd ZeeeZ	dd Z
dd Zee
eZdd ZeeZdd ZeeZeZeZdd ZeeZeZeZdd ZeeZd@ddZdAddZd d! Zd"d# Zd$d% Zd&d' Zd(d) ZdBd*d+ZdCd,d-Zd.d/ Zd0d1 Zd2d3 Z d4d5 Z!dDd6d7Z"dEd9d:Z#dFd;d<Z$d=d> Z%dS )GAWSAuthConnectionNTr   /awsc                 C   s8  || _ d| _tddr$tdd}|| _tdd|| _| jrLtsLt	dt
ddt}|dkrfd}|| _|rx|| _n
t| | _| ||||	 tjtjtjtjf| _g | _tr| jtj tjf| _|dk	r|d	 | _|  j|d
 7  _nd| _|rd| _nd| _|| _ || _!t"|
t#j$s(d	}
t%dd|
| _&d| _'i | _(t)j*d	 t)j*d
 fdkrrt%ddd| j(d< t"|t+r|| _,n|| _-t+| j-||||| _,| j,j r| j,j | _ | j,jr| j,j| _| j,j'r| j,j'| _'t. | _/| j | j| jf| _0d| _1t23|t| j,| 4 | _5t6| dddk	r.| j7| _8d| _9dS )a0  
        :type host: str
        :param host: The host to make the connection to

        :keyword str aws_access_key_id: Your AWS Access Key ID (provided by
            Amazon). If none is specified, the value in your
            ``AWS_ACCESS_KEY_ID`` environmental variable is used.
        :keyword str aws_secret_access_key: Your AWS Secret Access Key
            (provided by Amazon). If none is specified, the value in your
            ``AWS_SECRET_ACCESS_KEY`` environmental variable is used.
        :keyword str security_token: The security token associated with
            temporary credentials issued by STS.  Optional unless using
            temporary credentials.  If none is specified, the environment
            variable ``AWS_SECURITY_TOKEN`` is used if defined.

        :type is_secure: boolean
        :param is_secure: Whether the connection is over SSL

        :type https_connection_factory: list or tuple
        :param https_connection_factory: A pair of an HTTP connection
            factory and the exceptions to catch.  The factory should have
            a similar interface to L{http_client.HTTPSConnection}.

        :param str proxy: Address/hostname for a proxy server

        :type proxy_port: int
        :param proxy_port: The port to use when connecting over a proxy

        :type proxy_user: str
        :param proxy_user: The username to connect with on the proxy

        :type proxy_pass: str
        :param proxy_pass: The password to use when connection over a proxy.

        :type port: int
        :param port: The port to use to connect

        :type suppress_consec_slashes: bool
        :param suppress_consec_slashes: If provided, controls whether
            consecutive slashes will be suppressed in key paths.

        :type validate_certs: bool
        :param validate_certs: Controls whether SSL certificates
            will be validated or not.  Defaults to True.

        :type profile_name: str
        :param profile_name: Override usual Credentials section in config
            file to use a named set of keys instead.
           r=   rN   https_validate_certificateszSSL server certificate validation is enabled in boto configuration, but Python dependencies required to support this feature are not available. Certificate validation is only supported when running under Python 2.6 or later.ca_certificates_filesystemNr      httpshttpdebug)   rt   Zhttp_socket_timeoutF   timeoutAuthServiceName):suppress_consec_slashesnum_retriesr   
has_option
getbooleanrN   getboolru   HAVE_HTTPS_CONNECTIONr   	get_valueDEFAULT_CA_CERTS_FILErv   rM   PORTS_BY_SECURITYhandle_proxyr   HTTPExceptionsocketerrorgaierrorBadStatusLinehttp_exceptionshttp_unretryable_exceptionsr%   r   InvalidCertificateExceptionerrnoZEINTRZsocket_exception_valueshttps_connection_factoryrX   rL   rY   r`   r   integer_typesgetintr{   host_headerhttp_connection_kwargssysversion_infor   providerZ_provider_typer5   _pool_connectionZ_last_rsr   Zget_auth_handler_required_auth_capabilityrd   r1   r   auth_service_namerequest_hook)r!   rL   aws_access_key_idaws_secret_access_keyrN   rM   proxy
proxy_port
proxy_user
proxy_passr{   r   rY   r   security_tokenr   validate_certsprofile_nameZ
certs_filer   r   r   r"     s    9 
  
 

  






   zAWSAuthConnection.__init__c                 C   s   d| j j| jf S )Nz%s:%s)	__class__r9   rL   r    r   r   r   __repr__>  s    zAWSAuthConnection.__repr__c                 C   s   g S r   r   r    r   r   r   r   A  s    z+AWSAuthConnection._required_auth_capabilityc                 C   s   t | jdS )Nservice_namer1   rd   r    r   r   r   _get_auth_service_nameD  s    z(AWSAuthConnection._get_auth_service_namec                 C   s   || j _d S r   )rd   r   r!   valuer   r   r   _set_auth_service_nameJ  s    z(AWSAuthConnection._set_auth_service_namec                 C   s   t | jdS )Nregion_namer   r    r   r   r   _get_auth_region_nameN  s    z'AWSAuthConnection._get_auth_region_namec                 C   s   || j _d S r   )rd   r   r   r   r   r   _set_auth_region_nameQ  s    z'AWSAuthConnection._set_auth_region_namec                 C   s   | j | j S r   )rO   r   r    r   r   r   rf   U  s    zAWSAuthConnection.connectionc                 C   s   | j jS r   )r   
access_keyr    r   r   r   r   Y  s    z#AWSAuthConnection.aws_access_key_idc                 C   s   | j jS r   )r   
secret_keyr    r   r   r   r   _  s    z'AWSAuthConnection.aws_secret_access_keyc                 C   s   | j jS r   )r   r   r    r   r   r   r   e  s    zAWSAuthConnection.profile_namec                 C   s   | j s| jtdd| S |d}|dkrF||d  }|d | }nd }|d dkr\d}nd}| jd}||d d	d
 |D }dd| }|d dkr|r|d7 }|r|| }|S )Nz^(/*)/z\1?r   rr   TFc                 S   s   g | ]}|r|qS r   r   )r   pr   r   r   
<listcomp>|  s      z.AWSAuthConnection.get_path.<locals>.<listcomp>)r   rY   resubfindsplitextendjoin)r!   rY   posr[   Zneed_trailingZpath_elementsr   r   r   get_pathi  s&    
zAWSAuthConnection.get_pathc                 C   sd   |s
| j }|dkr| j}nFtr0tjd d dksBtjd d dkrR|dkrR| j}nd| j|f }|S )Nr      z2.5)z2.6z2.7r   %s:%d)rM   rL   r0   r   version)r!   rM   Zsignature_hostr   r   r   server_name  s    	zAWSAuthConnection.server_namec                 C   s  || _ || _|| _|| _dtjkrx| j sxtd}|tjd }|r|	d| _ |	d| _|	d| _|	d| _nX| j st
ddd | _ | jst
dd	d | _| jst
dd
d | _| jst
ddd | _| js| j rtd | j| _tjddptjdd| _| j d k	| _d S )NZ
http_proxyzX(?:http://)?(?:(?P<user>[\w\-\.]+):(?P<pass>.*)@)?(?P<host>[\w\-\.]+)(?::(?P<port>\d+))?rL   rM   userpassr=   r   r   r   r   zFhttp_proxy environment variable does not specify a port, using defaultno_proxyrl   ZNO_PROXY)r   r   r   r   r   r   r   compilematchgroupr   r   printrM   r.   r   	use_proxy)r!   r   r   r   r   patternr   r   r   r   r     s6     zAWSAuthConnection.handle_proxyc                 C   s.   | j |||}|d k	r|S | |||S d S r   )r   rO   new_http_connection)r!   rL   rM   rN   r'   r   r   r   rO     s    z%AWSAuthConnection.get_http_connectionc                 C   s^   | j s
dS | j dkrdS |}|dd }| j dD ]"}|r6||sR||r6 dS q6dS )NF*T:r   ,)r   r   endswith)r!   rL   hostonlynamer   r   r   
skip_proxy  s    
zAWSAuthConnection.skip_proxyc                 C   sZ  |d kr|   }tj|}| j }||d< | jrV|sV| |sV| j}t	| j
|d< |rtjd|| | jr| |s| ||rdpd}nD| jr| |}n2| jrtrtj|fd| ji|}ntj|f|}n4tjd|  | jr| j|f|}ntj|f|}| jdkr"|| j |dd	 | jkrP|| jkrP|||f| _t|_|S )
NrM   z1establishing HTTPS connection: host=%s, kwargs=%sr   r   ca_certsz'establishing HTTP connection: kwargs=%srx   r   r   )r   botoutilsZ
parse_hostr   rD   r   r   r   intr   logr{   	proxy_sslr   ru   r   r   ZCertValidatingHTTPSConnectionrv   r   HTTPSConnectionHTTPConnectionset_debuglevelr   rL   rN   r   rk   response_class)r!   rL   rM   rN   r   rf   r   r   r   r     sj    

 
"z%AWSAuthConnection.new_http_connectionc                 C   s   | j |||| d S r   )r   rP   )r!   rL   rM   rN   rf   r   r   r   rP     s    z%AWSAuthConnection.put_http_connectionc                 C   s,  |r|rd||f }nd| j | jf }| jd}|d k	rTt| jt| jf|}nt| jt| jf}t	j
d| |d|  |dt  | jr| jr|   D ]\}}|d||f  qtddd	r|d
 n
|d
 tj|d| jd}|  |jdkr2tdd| j| j|j|jf |  t|}| jrtrd}	| jrn|	d| j 7 }	n|	d7 }	t	j
|	 | jdd }
| jdd }tj ||
|tj!| jd}|" }| j #ddd }t$%||s"t$&||dn4t'tdrtj(|}nt|d d }t)||}||_*|S )Nr   r~   z'Proxy connection: CONNECT %s HTTP/1.0
zCONNECT %s HTTP/1.0
zUser-Agent: %s
z%s: %s
r=   Z"send_crlf_after_proxy_auth_headersFz
T)strict
debuglevel   iz*Error talking to HTTP proxy %s:%s: %s (%s)z,wrapping ssl socket for proxied connection; zCA certificate file=%szusing system provided SSL certskey_file	cert_file)keyfilecertfile	cert_reqsr   r   r   zhostname mismatchssl)+rL   rM   r   r.   r   create_connectionr   r   r   r   r   r{   sendallr   r   r   get_proxy_auth_headerrR   r   r   r   rk   beginstatusr   reasoncloser   ru   r   rv   r   wrap_socketCERT_REQUIREDgetpeercertr   r   ZValidateCertificateHostnamer   hasattr	SSLSocketZ
FakeSocketsock)r!   rL   rM   r~   r   kvresphmsgr   r   ZsslSockcerthostnamer   r   r   r     sx    
 
  zAWSAuthConnection.proxy_sslc                 C   s   | j d |p|   | }|S )N://)rX   r   )r!   rY   rL   r   r   r   prefix_proxy_to_pathU  s    z&AWSAuthConnection.prefix_proxy_to_pathc                 C   s    t | jd | j }dd| iS )Nr   zProxy-AuthorizationzBasic %s)r   r   r   )r!   r   r   r   r   r   Y  s    z'AWSAuthConnection.get_proxy_auth_headerc                 C   sZ   | j s
d S | js| jr:| jr.d| j| jf }q>d| j }nd}d|| jt| jpR| jf S )Nz%s:%s@z%s@rl   zhttp://%s%s:%s)r   r   r   r   re   r   rM   )r!   Z
login_infor   r   r   get_proxy_url_with_auth^  s    z)AWSAuthConnection.get_proxy_url_with_authc                 C   sL   z| j | j||jd< W n, tk
rF   | jddd |jd< Y nX d S )NHostr   rx   r   )rd   r   rL   r\   AttributeErrorr   )r!   requestr   r   r   set_host_headerl  s
    z!AWSAuthConnection.set_host_headerc                 C   s
   || _ d S r   )r   )r!   hookr   r   r   set_request_hooks  s    z"AWSAuthConnection.set_request_hookc              
   C   s  t jd|j  t jd|j  t jd|j  t jd|j  t jd|j  t jd|j  t jd|j	  d}d}d}|dkrt
d	d
| j}n|}d}	| |j|j| j}
t|jtst|jdr|jd|_|	|krtt d|	  t j
d	dd}zt jd| jj  |j| d d|  krjt| ddsj|jdsj| | t jd|j  t |_t|r||
|j|j|j|j}n |
 |j|j|j|j |
! }t jd|"   |#d}|jdkrt|ddrd|_$t|rN|||	|}|rN|\}}	}|r@t j| t%&| W q|j'dkrd|j' }|d| 7 }t j| |( }t|tr|)d}n
|j'dk s|j'd ks|s|#d!}|d"kr|
*  n| +|j|j| j|
 | j,dk	r
| j,-|| |W S t.|\}|_|_}}}|r@| jd#| 7  _d$|jkrb|j/d$d%\|_|_d&| d' }||j|j 7 }t j| | |j|j|d(k}
d}W qW n t0k
r } z2t jd)|  | 1|j|j| j}
|j2}|}W 5 d}~X Y n | j3k
r| } z`| j4D ](}t||rt jd*|j5j6   qt jd+|j5j6  | 1|j|j| j}
|}W 5 d}~X Y nX t%&| |	d%7 }	q| j,dk	r| j,j-||d,d- |rt7|j'|j8|n|r|nd.}t9|dS )/a>  
        mexe - Multi-execute inside a loop, retrying multiple times to handle
               transient Internet errors by simply trying again.
               Also handles redirects.

        This code was inspired by the S3Utils classes posted to the boto-users
        Google group by Larry Bates.  Thanks!

        z
Method: %szPath: %szData: %szHeaders: %szHost: %szPort: %sz
Params: %sNr=   r   r   rb   r_   r|   Zmax_retry_delay<   z	Token: %s)rf   Zs3ZanonFr  zFinal headers: %szResponse headers: %slocationHEADrU   )i  i  i  i  zReceived %d response.  zRetrying in %3.1f secondsi,  i  rf   r   r   r   rx   zRedirecting: %sr   ry   z!encountered a retry exception: %sz0encountered unretryable %s exception, re-raisingz&encountered %s exception, reconnectingT)r   z-Please report this exception as a Boto Issue!):r   r   r{   rW   rY   r]   r\   rL   rM   r[   r   r   r   rO   rN   r`   bytesr   rb   minrandomr.   r   r   rj   r   r1   r  r   r8   
start_timecallabler  getresponse
getheaders	getheaderrU   r&   sleepr   ro   decoder   rP   r   Zhandle_request_datar	   r   r   r   r3   r   r   r   r9   r   r   r   )r!   r  senderoverride_num_retriesretry_handlerr3   r]   exr   irf   Z
next_sleepr  r   r   Zconn_header_valueschemer[   queryfragmenteZunretryabler   r   r   _mexev  s   



  
 






   


zAWSAuthConnection._mexerl   c              
   C   s   |  |}|d k	r|  |}|d kr*i }n| }|d kr@i }n| }| jrftjd|sf| j|d< |pn| j}| jr| |s|s|}| 	||}| j
r| jr| js||   t|| j|| j|||||	S )NrL   )r   rD   r   r   r   Zfind_matching_headersrL   r   r   r   r   r   rN   updater   rS   rX   rM   )r!   rW   rY   rZ   r[   r\   datarL   r   r   r   build_base_http_request  s2    



    z)AWSAuthConnection.build_base_http_requestc              	   C   s4   |	dkri }	|  ||||	|||}| j||||
dS )z?Makes a request to the server, with stock multiple-retry logic.N)r  )r   r  )r!   rW   rY   r\   r  rL   rZ   r  r  r[   r  http_requestr   r   r   make_request&  s    
   
zAWSAuthConnection.make_requestc                 C   s   t jd d| _dS )z(Optional) Close any open HTTP connections.  This is non-destructive,
        and making a new request will open a connection again.zclosing all HTTP connectionsN)r   r   r{   r   r    r   r   r   r   1  s    zAWSAuthConnection.close)NNTNNNNNr   Nrr   rs   NTTN)rr   )N)NN)N)NNN)NNrl   N)Nrl   NNNNNN)&r9   r:   r;   r"   r   r   r   r   propertyr   r   r   Zauth_region_namerf   r   Zgs_access_key_idr   r   Zgs_secret_access_keyr   r   r   r   r   rO   r   r   rP   r   r   r   r   r  r  r  r   r"  r   r   r   r   r   rq     s                           
 



$9
F
  
        
         
rq   c                       sn   e Zd ZdZeZd fdd	Zd	d
 Zdd ZdddZ	dd Z
dd ZdddZdddZdddZ  ZS )AWSQueryConnectionrl   NTr   rr   rs   c                    s4   t t| j|	|||||||||
||||||d d S )N)r   r   r   r   )superr$  r"   )r!   r   r   rN   rM   r   r   r   r   rL   r{   r   rY   r   r   r   r   r   r   r   r"   >  s$    
       zAWSQueryConnection.__init__c                 C   s   g S r   r   r    r   r   r   r   N  s    z,AWSQueryConnection._required_auth_capabilityc                 C   s   t j|S r   )r   r   get_utf8_valuer   r   r   r   r'  Q  s    z!AWSQueryConnection.get_utf8_valueGETc              	   C   sB   |  ||d |i d| j}|r&||jd< | jr8| j|jd< | |S )Nrl   ActionVersion)r   rL   r[   
APIVersionr  )r!   actionr[   rY   verbr!  r   r   r   r"  T  s    
  
zAWSQueryConnection.make_requestc                 C   sF   t |tjr|g}tdt|d D ]}||d  |d||f < q$d S )Nrx   z%s.%d)r`   r   string_typesr*   r#   )r!   r[   rR   labelr  r   r   r   build_list_params^  s    z$AWSQueryConnection.build_list_paramsc                 C   sL   t |dD ]<\}}d||f }t||D ]\}}	d||f }
|	||
< q(q
dS )a  Serialize a list of structures.

        For example::

            items = [('foo', 'bar', 'baz'), ('foo2', 'bar2', 'baz2')]
            label = 'ParamName.member'
            names = ('One', 'Two', 'Three')
            self.build_complex_list_params(params, items, label, names)

        would result in the params dict being updated with these params::

            ParamName.member.1.One = foo
            ParamName.member.1.Two = bar
            ParamName.member.1.Three = baz

            ParamName.member.2.One = foo2
            ParamName.member.2.Two = bar2
            ParamName.member.2.Three = baz2

        :type params: dict
        :param params: The params dict.  The complex list params
            will be added to this dict.

        :type items: list of tuples
        :param items: The list to serialize.

        :type label: string
        :param label: The prefix to apply to the parameter.

        :type names: tuple of strings
        :param names: The names associated with each tuple element.

        rx   z%s.%sN)	enumeratezip)r!   r[   rR   r/  namesr  itemZcurrent_prefixr   r   Zfull_keyr   r   r   build_complex_list_paramsd  s
    "z,AWSQueryConnection.build_complex_list_paramsc                 C   s   |s| }|  ||||}| }tj| |sTtjd|  | |j|j|n|jdkrt	|}	tj
|	|}
t|tjr|d}tj||
 |	S tjd|j|jf  tjd|  | |j|j|d S NNull body %sr   r_   %s %s%s)r"  ro   r   r   r{   r   ResponseErrorr   r   r   handler
XmlHandlerr`   r   ra   rb   xmlsaxparseString)r!   r,  r[   markersrY   parentr-  r3   r]   rsr   r   r   r   get_list  s$    

zAWSQueryConnection.get_listc                 C   s   |s| }|  ||||}| }tj| |sTtjd|  | |j|j|n|jdkr||}	tj	
|	|}
t|tjr|d}tj||
 |	S tjd|j|jf  tjd|  | |j|j|d S r6  )r"  ro   r   r   r{   r   r:  r   r   r;  r<  r`   r   ra   rb   r=  r>  r?  )r!   r,  r[   clsrY   rA  r-  r3   r]   objr   r   r   r   
get_object  s$    

zAWSQueryConnection.get_objectc           
      C   s   |s| }|  ||||}| }tj| |sTtjd|  | |j|j|nl|jdkrt	 }tj
||}	tj||	 |jS tjd|j|jf  tjd|  | |j|j|d S )Nr7  r   r8  r9  )r"  ro   r   r   r{   r   r:  r   r   r   r;  r<  r=  r>  r?  )
r!   r,  r[   rY   rA  r-  r3   r]   rB  r   r   r   r   
get_status  s     
zAWSQueryConnection.get_status)NNTNNNNNNr   Nrr   NTNrs   )Nrr   r(  )rr   Nr(  )rr   Nr(  )rr   Nr(  )r9   r:   r;   r+  r   r:  r"   r   r'  r"  r0  r5  rC  rF  rG  __classcell__r   r   r&  r   r$  9  s@                            

*    
    
r$  );r<   r   r   r   r  r   r   r   r&   Zxml.saxr=  rD   r   r   r   Z
boto.utilsZboto.handlerZboto.cacertsr   r   Zboto.compatr   r   r	   r
   r   Zboto.exceptionr   r   r   r   Zboto.providerr   Zboto.resultsetr   r   r   r   r   ImportErrorr@   Zdummy_threadingallr0   r   rY   r   dirnameabspathZcacerts__file__r   objectr   r5   rS   rk   rq   r$  r   r   r   r   <module>*   sh   "jeT     