U
    s@g)                    @   s>  d Z ddlmZmZ ddlZddlZddlZzddlmZm	Z	m
Z
 W n8 ek
r|   ddlm	Z	m
Z
 ddlmZ dd ZY nX dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZmZmZ ddl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&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl#m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZCmDZD G dd de6jEZFG dd  d e$jGZHG d!d" d"eHZIG d#d$ d$e'jJZKG d%d& d&eKZLG d'd( d(eMZNd)d* ZOdxd+d,ZPd-ZQd.d/ ZReR  ee"d0d1d2deQdyd3d4ZSee"d0d1d2deQdzd5d6ZTdd7lUmVZV dd8lBmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZa zdd9lbmcZc W n ek
r   dZcY nX dd:ldmeZemfZfmgZg d;d< ZhG d=d> d>eMZiee<G d?d@ d@eMZjee"d0dAddeeie"d0dAddejdBkdCdD eijleijm ee.G dEdF dFeMZnee<G dGdH dHeMZoee;G dIdJ dJeMZpG dKdL dLe'jqZrG dMdN dNeMZsG dOdP dPeMZtG dQdR dReMZuee:G dSdT dTeMZvee9G dUdV dVeuZwee9G dWdX dXeuZxG dYdZ dZeMZyG d[d\ d\eMZzee9G d]d^ d^eMZ{G d_d` d`e5e=Z|G dadb dbe5e-Z}ee9G dcdd ddeMZ~e? jZededfdgdhdigZee9G djdk dkeMZG dldm dmeZG dndo doe'jZdpdq ZdVdmddd^d6d4d`d$dPd&d"d ddXdqdkdrdsdtdudvdwd(gZdS ){z
HTTP client.
    )divisionabsolute_importN)
urlunparseurljoin	urldefrag)r   r   )r   c                 C   s    t tdd | D }|dS )Nc                 S   s   g | ]}| d qS )charmap)decode).0p r   4/usr/lib/python3/dist-packages/twisted/web/client.py
<listcomp>   s     zurlunparse.<locals>.<listcomp>r   )_urlunparsetupleencode)partsresultr   r   r   r      s    r   )implementer)Iterable)wraps)_PY3networkString)nativeString
intToBytesunicode
itervalues)
deprecateddeprecatedModuleAttributegetDeprecationWarningString)Failure)Version)http)deferprotocoltaskreactor)isIPv6Address)	IProtocolIOpenSSLContextFactory)HostnameEndpointwrapClientTLS)InsensitiveDict)proxyForInterface)error)UNKNOWN_LENGTHIAgentIAgentEndpointFactoryIBodyProducerIPolicyForHTTPS	IResponse)Headers)Logger)_ensureValidURI_ensureValidMethodc                   @   s   e Zd ZdZdS )PartialDownloadErrorz
    Page was only partially downloaded, we got disconnected in middle.

    @ivar response: All of the response body which was downloaded.
    N)__name__
__module____qualname____doc__r   r   r   r   r8   ?   s   r8   c                   @   s   e Zd ZdZdZdZdZdZe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 S )!HTTPPageGettera  
    Gets a resource via HTTP, then quits.

    Typically used with L{HTTPClientFactory}.  Note that this class does not, by
    itself, do anything with the response.  If you want to download a resource
    into a file, use L{HTTPPageDownloader} instead.

    @ivar _completelyDone: A boolean indicating whether any further requests are
        necessary after this one completes in order to provide a result to
        C{self.factory.deferred}.  If it is C{False}, then a redirect is going
        to be followed.  Otherwise, this protocol's connection is the last one
        before firing the result Deferred.  This is used to make sure the result
        Deferred is only fired after the connection is cleaned up.
    r   T)   hosts
   user-agent   cookies   content-lengthc           	      C   s  t t| jdd}| |t| jj | jjdkrX| jjdkrX| jjd t	| jj }n:| jjdkr| jjdkr| jjd t	| jj }n| jj}| 
d| jjd	| | 
d
| jj t| jdd }|d k	r| 
dt	t| g }| jj D ]:\}}| | jkr| 
|| | dkr|| q| jj D ]\}}||d |  q<|rr| 
dd| |   i | _|d k	r| j| d S )Nmethod   GET   httpP      :   https  s   Hostr>   s
   User-Agentpostdata   Content-Lengthr?      =   Cookies   ; )r7   getattrfactoryZsendCommandr6   pathschemeporthostr   Z
sendHeaderheadersgetagentlenitemslower_specialHeadersappendcookiesjoinZ
endHeaders	transportwrite)	selfr@   rP   dataZ
cookieDatakeyvaluecookieZcookvalr   r   r   connectionMadea   s4    
zHTTPPageGetter.connectionMadec                 C   s$   |  }| j|g }|| dS )a(  
        Called every time a header is received. Stores the header information
        as key-value pairs in the C{headers} attribute.

        @type key: C{str}
        @param key: An HTTP header field name.

        @type value: C{str}
        @param value: An HTTP header field value.
        N)rV   rQ   
setdefaultrX   )r]   r_   r`   lr   r   r   handleHeader   s    zHTTPPageGetter.handleHeaderc                 C   s*   |||  | _ | _| _| j||| dS )aJ  
        Handle the HTTP status line.

        @param version: The HTTP version.
        @type version: L{bytes}
        @param status: The HTTP status code, an integer represented as a
            bytestring.
        @type status: L{bytes}
        @param message: The HTTP status message.
        @type message: L{bytes}
        N)versionstatusmessagerL   	gotStatusr]   rf   rg   rh   r   r   r   handleStatus   s    zHTTPPageGetter.handleStatusc                 C   s0   | j | j t| dt| j | j}|  d S )NZhandleStatus_)rL   
gotHeadersrQ   rK   r   rg   handleStatusDefault)r]   mr   r   r   handleEndHeaders   s
    zHTTPPageGetter.handleEndHeadersc                 C   s   d S Nr   r]   r   r   r   handleStatus_200   s    zHTTPPageGetter.handleStatus_200c                 C   s   |   S rp   rr   rq   r   r   r   <lambda>       zHTTPPageGetter.<lambda>c                 C   s   |   S rp   rs   rq   r   r   r   rt      ru   c                 C   s
   d| _ d S N   )failedrq   r   r   r   rm      s    z"HTTPPageGetter.handleStatusDefaultc                 C   s,  | j d}|s|   d S |d }| jr| j jd7  _| jj| jjkrtj| j	d|d}| j
t| d| _| j  d S d| _| j| | jjdkrdd	lm} | }tt| jj| jj| j| ntt| jj| jj| j n(|   | j
ttj| j	| j|d d| _| j  d S )
N   locationr   rw      Infinite redirection detectedlocationTFrE   ssl)rQ   rR   rm   followRedirectrL   _redirectCountredirectLimitr-   InfiniteRedirectionrg   noPager   	quietLossr[   loseConnection_completelyDonesetURLrN   twisted.internetr~   ClientContextFactoryr%   
connectSSLr   rP   rO   
connectTCPPageRedirectrh   )r]   rd   urlerrr~   contextFactoryr   r   r   handleStatus_301   sV    
   zHTTPPageGetter.handleStatus_301c                 C   s   | j r|   n|   d S rp   )afterFoundGethandleStatus_303r   rq   r   r   r   handleStatus_302   s    
zHTTPPageGetter.handleStatus_302c                 C   s   d| j _|   d S )NrA   )rL   r@   r   rq   r   r   r   r      s    zHTTPPageGetter.handleStatus_303c                 C   s8   | j s tj| | | j| | jr4| jjd dS )z
        When the connection used to issue the HTTP request is closed, notify the
        factory if we have not already, so it can produce a result.
        N)	r   r!   
HTTPClientconnectionLostrL   r   r   _disconnectedDeferredcallbackr]   reasonr   r   r   r      s
    zHTTPPageGetter.connectionLostc                 C   s   | j r
d S | jr.| jtt| j| j| | jj	dkrH| j
d n>| jd krz| jdkrz| jtt| j| j| n| j
| | j  d S )N   HEADru   r   )r   rx   rL   r   r   r-   Errorrg   rh   r@   pagelengthr8   r[   r   r]   responser   r   r   handleResponse   s(      zHTTPPageGetter.handleResponsec                 C   s6   d| _ | j  | jtd| jj| jjf  d S )NTz'Getting %s took longer than %s seconds.)	r   r[   abortConnectionrL   r   r"   TimeoutErrorr   timeoutrq   r   r   r   r     s    
zHTTPPageGetter.timeoutN)r9   r:   r;   r<   r   r   rx   r   setrW   rb   re   rk   ro   rr   ZhandleStatus_201ZhandleStatus_202rm   r   r   r   r   r   r   r   r   r   r   r=   G   s,    (r=   c                   @   s2   e Zd ZdZdddZdd Zdd Zdd	 Zd
S )HTTPPageDownloaderr   c                 C   s    t |  d| _| j| d S rv   )r=   rr   transmittingPagerL   	pageStartr]   partialContentr   r   r   rr     s    
z#HTTPPageDownloader.handleStatus_200c                 C   s   | j dd d S )Nrw   )r   rs   rq   r   r   r   handleStatus_206  s    z#HTTPPageDownloader.handleStatus_206c                 C   s   | j r| j| d S rp   )r   rL   pagePartr]   r^   r   r   r   handleResponsePart  s    z%HTTPPageDownloader.handleResponsePartc                 C   sj   | j r"d| _| jtt| j | jr8| j  d| _| jrf| jtt	
| j| jd  | j  d S Nr   )r   r   rL   r   r   r8   rg   pageEndrx   r-   r   rh   r[   r   rq   r   r   r   handleResponseEnd  s*    
  z$HTTPPageDownloader.handleResponseEndN)r   )r9   r:   r;   r   rr   r   r   r   r   r   r   r   r     s
   
r   c                	   @   s   e Zd ZdZeZdZdZdZdZ	dZ
d 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S )!HTTPClientFactorya  Download a given URL.

    @type deferred: Deferred
    @ivar deferred: A Deferred that will fire when the content has
          been retrieved. Once this is fired, the ivars `status', `version',
          and `message' will be set.

    @type status: bytes
    @ivar status: The status of the response.

    @type version: bytes
    @ivar version: The version of the response.

    @type message: bytes
    @ivar message: The text message returned with the status.

    @type response_headers: dict
    @ivar response_headers: The headers that were specified in the
          response from the server.

    @type method: bytes
    @ivar method: The HTTP method to use in the request.  This should be one of
        OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, or CONNECT (case
        matters).  Other values may be specified if the server being contacted
        supports them.

    @type redirectLimit: int
    @ivar redirectLimit: The maximum number of HTTP redirects that can occur
          before it is assumed that the redirection is endless.

    @type afterFoundGet: C{bool}
    @ivar afterFoundGet: Deviate from the HTTP 1.1 RFC by handling redirects
        the same way as most web browsers; if the request method is POST and a
        302 status is encountered, the redirect is followed with a GET method

    @type _redirectCount: int
    @ivar _redirectCount: The current number of HTTP redirects encountered.

    @ivar _disconnectedDeferred: A L{Deferred} which only fires after the last
        connection associated with the request (redirects may cause multiple
        connections to be required) has closed.  The result Deferred will only
        fire after this Deferred, so that callers can be assured that there are
        no more event sources in the reactor once they get the result.
    Nru   rA      Twisted PageGetterr   T   Fc                 C   s   || _ |	| _d| _|| _|| _|
| _|d kr0i }|| _|d k	rJt|| _nt | _|d k	r~| j	dt
t| | j	dd || _t|| _| | d| _t | _t | _| j| j d | _d S )Nr   rH   s
   connections   closerw   )r   r   r   r   rS   r   rY   r+   rQ   rc   r   rT   rG   r7   r@   r   waitingr"   Deferredr   deferredaddBoth_waitForDisconnectresponse_headers)r]   r   r@   rG   rQ   rS   r   rY   r   r   r   r   r   r   __init__d  s2    




zHTTPClientFactory.__init__c                    s   | j  fdd | j S )z
        Chain onto the _disconnectedDeferred, preserving C{passthrough}, so that
        the result is only available after the associated connection has been
        closed.
        c                    s    S rp   r   Zignoredpassthroughr   r   rt     ru   z6HTTPClientFactory._waitForDisconnect.<locals>.<lambda>)r   addCallback)r]   r   r   r   r   r     s    z$HTTPClientFactory._waitForDisconnectc                 C   s   d| j j| jf S )Nz<%s: %s>)	__class__r9   r   rq   r   r   r   __repr__  s    zHTTPClientFactory.__repr__c                 C   sL   t |  || _t|}|jr@|jr@|j| _|j| _|j| _|j| _	d S rp   )
r6   stripr   URI	fromBytesrN   rP   rO   
originFormrM   )r]   r   urir   r   r   r     s    
zHTTPClientFactory.setURLc                 C   sH   t j| |}| j|_| j|_| jrDt| j|j}| j	| j
| |S rp   )r#   ClientFactorybuildProtocolr   r   r   r%   	callLaterr   r   _cancelTimeout)r]   addrr
   timeoutCallr   r   r   r     s    zHTTPClientFactory.buildProtocolc                 C   s   |  r|  |S rp   )Zactivecancel)r]   r   r   r   r   r   r     s    z HTTPClientFactory._cancelTimeoutc                 C   sd   || _ d|kr`|d D ]H}d|kr|d}|d }|  |dd\}}| | j| < qdS )z
        Parse the response HTTP headers.

        @param headers: The response HTTP headers.
        @type headers: L{dict}
        s
   set-cookierI      ;r   rw   N)r   splitlstriprY   )r]   rQ   ra   Z	cookpartsZcookkvr   r   r   rl     s    
zHTTPClientFactory.gotHeadersc                 C   s   |||  | _ | _| _dS )aR  
        Set the status of the request on us.

        @param version: The HTTP version.
        @type version: L{bytes}
        @param status: The HTTP status code, an integer represented as a
            bytestring.
        @type status: L{bytes}
        @param message: The HTTP status message.
        @type message: L{bytes}
        N)rf   rg   rh   rj   r   r   r   ri     s    zHTTPClientFactory.gotStatusc                 C   s   | j rd| _ | j| d S r   )r   r   r   )r]   r   r   r   r   r     s    zHTTPClientFactory.pagec                 C   s   | j rd| _ | j| d S r   )r   r   errbackr   r   r   r   r     s    zHTTPClientFactory.noPagec                 C   s(   | j r$d| _ | jd | j| dS )z
        When a connection attempt fails, the request cannot be issued.  If no
        result has yet been provided to the result Deferred, provide the
        connection failure reason as an error result.
        r   N)r   r   r   r   r   )r]   _r   r   r   r   clientConnectionFailed  s    z(HTTPClientFactory.clientConnectionFailed)	rA   NNr   r   NTr   F)r9   r:   r;   r<   r=   r#   r   rN   rP   rO   rM   r   r   r   r   r   r   rl   ri   r   r   r   r   r   r   r   r   .  s2   -          
$

	r   c                
   @   sX   e Zd ZdZeZdZe Zdd	d
Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )HTTPDownloaderz
    Download to a file.
    NrA      Twisted clientFr   Tr   c                 C   s   d| _ t|ttfrl|| _d | _|rrtj| jrrtj	| j}|rr|| _ |d krVi }dt
| d |d< n|| _tj| |||||||	|
||d d S )Nr   s   bytes=   -s   range)	r@   rG   rQ   rS   r   rY   r   r   r   )requestedPartial
isinstancestrr   fileNamefileosrM   existsgetsizer   r   r   )r]   r   Z
fileOrNamer@   rG   rQ   rS   ZsupportPartialr   rY   r   r   r   Z
fileLengthr   r   r   r     s2           zHTTPDownloader.__init__c                 C   sT   t | | | jrP|dd }|s,d| _d S t|d \}}}|| jkrPd| _d S )Ns   content-ranger   )r   rl   r   rR   r!   ZparseContentRange)r]   rQ   ZcontentRangestartendZ
realLengthr   r   r   rl     s    
zHTTPDownloader.gotHeadersc                 C   s.   |rt | jd}|dd nt | jd}|S )Nzrb+r      wb)openr   seek)r]   r   r   r   r   r   openFile  s
    zHTTPDownloader.openFilec                 C   sV   |r| j std| jrRz| js,| || _W n" tk
rP   | jt  Y nX dS )zCalled on page download start.

        @param partialContent: tells us if the download is partial download we requested.
        z?we shouldn't get partial content response if we didn't want it!N)	r   
ValueErrorr   r   r   IOErrorr   r   r   r   r   r   r   r     s    
zHTTPDownloader.pageStartc                 C   sH   | j s
d S z| j | W n( tk
rB   d | _ | jt  Y nX d S rp   )r   r\   r   r   r   r   r   r   r   r   r   +  s    zHTTPDownloader.pagePartc                 C   sJ   | j rFd| _ | jr:z| j  W n   | jd Y nX | j| dS )zk
        Close the storage file and errback the waiting L{Deferred} with the
        given reason.
        r   z!Error closing HTTPDownloader fileN)r   r   close_logfailurer   r   r   r   r   r   r   6  s    zHTTPDownloader.noPagec                 C   sV   d| _ | jsd S z| j  W n$ tk
rB   | jt  Y d S X | j| j d S r   )	r   r   r   r   r   r   r   r   r`   rq   r   r   r   r   E  s    zHTTPDownloader.pageEnd)
rA   NNr   Fr   NTr   F)r9   r:   r;   r<   r   r#   r`   r5   r   r   rl   r   r   r   r   r   r   r   r   r   r     s*                   
r   c                   @   s:   e Zd ZdZdd ZedddZdd Zed	d
 Z	dS )r   zd
    A URI object.

    @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21}
    c	           	      C   s:   || _ || _|d| _|| _|| _|| _|| _|| _dS )a  
        @type scheme: L{bytes}
        @param scheme: URI scheme specifier.

        @type netloc: L{bytes}
        @param netloc: Network location component.

        @type host: L{bytes}
        @param host: Host name. For IPv6 address literals the brackets are
            stripped.

        @type port: L{int}
        @param port: Port number.

        @type path: L{bytes}
        @param path: Hierarchical path.

        @type params: L{bytes}
        @param params: Parameters for last path segment.

        @type query: L{bytes}
        @param query: Query string.

        @type fragment: L{bytes}
        @param fragment: Fragment identifier.
        s   []N)	rN   netlocr   rP   rO   rM   paramsqueryfragment)	r]   rN   r   rP   rO   rM   r   r   r   r   r   r   r   X  s    zURI.__init__Nc              	   C   s   |  }t|\}}}}}}|dkr8|dkr4d}nd}d|kr~|dd\}	}
zt|
}
W q tk
rz   || }	}
Y qX n
|| }	}
| |||	|
||||S )aN  
        Parse the given URI into a L{URI}.

        @type uri: C{bytes}
        @param uri: URI to parse.

        @type defaultPort: C{int} or L{None}
        @param defaultPort: An alternate value to use as the port if the URI
            does not include one.

        @rtype: L{URI}
        @return: Parsed URI instance.
        NrE   rF   rC   rD   rw   )r   r!   urlparsersplitintr   )clsr   ZdefaultPortrN   r   rM   r   r   r   rP   rO   r   r   r   r   ~  s    
zURI.fromBytesc                 C   s    t | j| j| j| j| j| jfS )z
        Assemble the individual parts of the I{URI} into a fully formed I{URI}.

        @rtype: C{bytes}
        @return: A fully formed I{URI}.
        )r   rN   r   rM   r   r   r   rq   r   r   r   toBytes  s
    zURI.toBytesc                 C   s*   t dd| j| j| jdf}|dkr&d}|S )a!  
        The absolute I{URI} path including I{URI} parameters, query string and
        fragment identifier.

        @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21#section-5.3}

        @return: The absolute path in original form.
        @rtype: L{bytes}
        ru      /)r   rM   r   r   )r]   rM   r   r   r   r     s    zURI.originForm)N)
r9   r:   r;   r<   r   classmethodr   r   propertyr   r   r   r   r   r   R  s   &"r   c                 C   s0   t | \} }t t| |\}}t|d|p*| S )a  
    Construct a full ("absolute") URL by combining a "base URL" with another
    URL. Informally, this uses components of the base URL, in particular the
    addressing scheme, the network location and (part of) the path, to provide
    missing components in the relative URL.

    Additionally, the fragment identifier is preserved according to the HTTP
    1.1 bis draft.

    @type base: C{bytes}
    @param base: Base URL.

    @type url: C{bytes}
    @param url: URL to combine with C{base}.

    @return: An absolute URL resulting from the combination of C{base} and
        C{url}.

    @see: L{urlparse.urljoin}

    @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2}
       #)r   r   )baser   ZbaseFragZurlFragr   r   r   _urljoin  s    r   c                 O   s|   t t|  }|| f||}|jdkrbddlm} |dkrH| }t	t
|j|j|| ntt
|j|j| |S )a  
    Create and connect an HTTP page getting factory.

    Any additional positional or keyword arguments are used when calling
    C{factoryFactory}.

    @param factoryFactory: Factory factory that is called with C{url}, C{args}
        and C{kwargs} to produce the getter

    @param contextFactory: Context factory to use when creating a secure
        connection, defaulting to L{None}

    @return: The factory created by C{factoryFactory}
    rE   r   r}   N)r   r   r6   r   rN   r   r~   r   r%   r   r   rP   rO   r   )r   factoryFactoryr   argskwargsr   rL   r~   r   r   r   _makeGetterFactory  s    
   r   z:https://pypi.org/project/treq/ or twisted.web.client.Agentc               
   C   sP   t tttfD ]>} ttddddt| tddddtddd | j	| j
 qdS )	zl
    Mark the protocols and factories associated with L{getPage} and
    L{downloadPage} as deprecated.
    Twisted      r   Zreplacement; rw   N)r=   r   r   r   r   r    r   _GETPAGE_REPLACEMENT_TEXTr   r:   r9   )klassr   r   r   _deprecateGetPageClasses  s&      r  r   r   r  c                 O   s   t | tf|d|i|jS )z
    Download a web page as a string.

    Download a page. Return a deferred, which will callback with a
    page (as a string) or errback with a description of the error.

    See L{HTTPClientFactory} to see what extra arguments can be passed.
    r   )r   r   r   )r   r   r   r   r   r   r   getPage  s    r  c                    s(    fdd}t | |f|d|i|jS )z
    Download a web page to a file.

    @param file: path to file on filesystem, or file-like object.

    See HTTPDownloader to see what extra args can be passed.
    c                    s   t |  f||S rp   )r   )r   akwr   r   r   rt   2  ru   zdownloadPage.<locals>.<lambda>r   )r   r   )r   r   r   r   r   r   r   r
  r   downloadPage(  s    
r  )SchemeNotSupported)HTTP11ClientProtocolPotentialDataLossRequestRequestGenerationFailedRequestNotSentRequestTransmissionFailedResponseResponseDoneResponseFailedResponseNeverReceived_WrapperException)SSL)CertificateOptionsplatformTrustoptionsForClientTLSc                 C   s    t dkrt| dd }|S | S )a}  
    The decorated method requires pyOpenSSL to be present, or it raises
    L{NotImplementedError}.

    @param decoratee: A function which requires pyOpenSSL.
    @type decoratee: L{callable}

    @return: A function which raises L{NotImplementedError} if pyOpenSSL is not
        installed; otherwise, if it is installed, simply return C{decoratee}.
    @rtype: L{callable}
    Nc                  _   s   t ddS )z
            pyOpenSSL is not available.

            @param a: The positional arguments for C{decoratee}.

            @param kw: The keyword arguments for C{decoratee}.

            @raise NotImplementedError: Always.
            zSSL support unavailableN)NotImplementedError)r  r	  r   r   r   raiseNotImplementedf  s    z(_requireSSL.<locals>.raiseNotImplemented)r  r   )Z	decorateer  r   r   r   _requireSSLY  s
    
r  c                   @   s$   e Zd ZdZdd Zedd ZdS )WebClientContextFactorya  
    This class is deprecated.  Please simply use L{Agent} as-is, or if you want
    to customize something, use L{BrowserLikePolicyForHTTPS}.

    A L{WebClientContextFactory} is an HTTPS policy which totally ignores the
    hostname and port.  It performs basic certificate verification, however the
    lack of validation of service identity (e.g.  hostname validation) means it
    is still vulnerable to man-in-the-middle attacks.  Don't use it any more.
    c                 C   s   t tjt dS )z
        Return a L{CertificateOptions}.

        @param hostname: ignored

        @param port: ignored

        @return: A new CertificateOptions instance.
        @rtype: L{CertificateOptions}
        )r@   	trustRoot)r  r  ZSSLv23_METHODr  r]   hostnamerO   r   r   r   _getCertificateOptions  s    z.WebClientContextFactory._getCertificateOptionsc                 C   s   |  || S )z
        Return an L{OpenSSL.SSL.Context}.

        @param hostname: ignored
        @param port: ignored

        @return: A new SSL context.
        @rtype: L{OpenSSL.SSL.Context}
        )r#  
getContextr!  r   r   r   r$    s    z"WebClientContextFactory.getContextN)r9   r:   r;   r<   r#  r  r$  r   r   r   r   r  w  s   
r  c                   @   s&   e Zd ZdZdddZedd ZdS )BrowserLikePolicyForHTTPSz1
    SSL connection creator for web clients.
    Nc                 C   s
   || _ d S rp   )
_trustRoot)r]   r   r   r   r   r     s    z"BrowserLikePolicyForHTTPS.__init__c                 C   s   t |d| jdS )a  
        Create a L{client connection creator
        <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} for a
        given network location.

        @param tls: The TLS protocol to create a connection for.
        @type tls: L{twisted.protocols.tls.TLSMemoryBIOProtocol}

        @param hostname: The hostname part of the URI.
        @type hostname: L{bytes}

        @param port: The port part of the URI.
        @type port: L{int}

        @return: a connection creator with appropriate verification
            restrictions set
        @rtype: L{client connection creator
            <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
        ascii)r   )r  r   r&  r!  r   r   r   creatorForNetloc  s    
z*BrowserLikePolicyForHTTPS.creatorForNetloc)N)r9   r:   r;   r<   r   r  r(  r   r   r   r   r%    s   
r%     r  r  rw   c                   @   s    e Zd ZdZdd Zdd ZdS )_ContextFactoryWithContextz
    A L{_ContextFactoryWithContext} is like a
    L{twisted.internet.ssl.ContextFactory} with a pre-created context.

    @ivar _context: A Context.
    @type _context: L{OpenSSL.SSL.Context}
    c                 C   s
   || _ dS )z
        Initialize a L{_ContextFactoryWithContext} with a context.

        @param context: An SSL context.
        @type context: L{OpenSSL.SSL.Context}
        NZ_context)r]   contextr   r   r   r     s    z#_ContextFactoryWithContext.__init__c                 C   s   | j S )z
        Return the context created by
        L{_DeprecatedToCurrentPolicyForHTTPS._webContextFactory}.

        @return: A context.
        @rtype context: L{OpenSSL.SSL.Context}
        r+  rq   r   r   r   r$    s    z%_ContextFactoryWithContext.getContextN)r9   r:   r;   r<   r   r$  r   r   r   r   r*    s   
r*  c                   @   s    e Zd ZdZdd Zdd ZdS )"_DeprecatedToCurrentPolicyForHTTPSa+  
    Adapt a web context factory to a normal context factory.

    @ivar _webContextFactory: An object providing a getContext method with
        C{hostname} and C{port} arguments.
    @type _webContextFactory: L{WebClientContextFactory} (or object with a
        similar C{getContext} method).
    c                 C   s
   || _ dS )a>  
        Wrap a web context factory in an L{IPolicyForHTTPS}.

        @param webContextFactory: An object providing a getContext method with
            C{hostname} and C{port} arguments.
        @type webContextFactory: L{WebClientContextFactory} (or object with a
            similar C{getContext} method).
        N)_webContextFactory)r]   ZwebContextFactoryr   r   r   r     s    	z+_DeprecatedToCurrentPolicyForHTTPS.__init__c                 C   s   | j ||}t|S )a  
        Called the wrapped web context factory's C{getContext} method with a
        hostname and port number and return the resulting context object.

        @param hostname: The hostname part of the URI.
        @type hostname: L{bytes}

        @param port: The port part of the URI.
        @type port: L{int}

        @return: A context factory.
        @rtype: L{IOpenSSLContextFactory}
        )r.  r$  r*  )r]   r"  rO   r,  r   r   r   r(    s    z3_DeprecatedToCurrentPolicyForHTTPS.creatorForNetlocN)r9   r:   r;   r<   r   r(  r   r   r   r   r-    s   r-  c                   @   sN   e Zd ZdZedfddZdd Zdd Zd	d
 Zdd Z	dd Z
dd ZdS )FileBodyProducera  
    L{FileBodyProducer} produces bytes from an input file object incrementally
    and writes them to a consumer.

    Since file-like objects cannot be read from in an event-driven manner,
    L{FileBodyProducer} uses a L{Cooperator} instance to schedule reads from
    the file.  This process is also paused and resumed based on notifications
    from the L{IConsumer} provider being written to.

    The file is closed after it has been read, or if the producer is stopped
    early.

    @ivar _inputFile: Any file-like object, bytes read from which will be
        written to a consumer.

    @ivar _cooperate: A method like L{Cooperator.cooperate} which is used to
        schedule all reads.

    @ivar _readSize: The number of bytes to read from C{_inputFile} at a time.
    i   c                 C   s$   || _ |j| _|| _| || _d S rp   )
_inputFileZ	cooperate
_cooperate	_readSize_determineLengthr   )r]   Z	inputFileZ
cooperatorZreadSizer   r   r   r   0  s    zFileBodyProducer.__init__c                 C   sV   z|j }|j}W n tk
r(   t Y S X | }|dtj | }||tj || S )z
        Determine how many bytes can be read out of C{fObj} (assuming it is not
        modified from this point on).  If the determination cannot be made,
        return C{UNKNOWN_LENGTH}.
        r   )r   tellAttributeErrorr.   r   SEEK_ENDSEEK_SET)r]   ZfObjr   r4  ZoriginalPositionr   r   r   r   r3  7  s    

z!FileBodyProducer._determineLengthc                 C   s   | j   | j  dS )z
        Permanently stop writing bytes from the file to the consumer by
        stopping the underlying L{CooperativeTask}.
        N)r0  r   _taskstoprq   r   r   r   stopProducingI  s    
zFileBodyProducer.stopProducingc                 C   s8   |  | || _| j }dd }|dd | |S )z
        Start a cooperative task which will read bytes from the input file and
        write them to C{consumer}.  Return a L{Deferred} which fires after all
        bytes have been written.

        @param consumer: Any L{IConsumer} provider
        c                 S   s   |  tj t S rp   )Ztrapr$   ZTaskStoppedr"   r   r   r   r   r   maybeStopped\  s    z5FileBodyProducer.startProducing.<locals>.maybeStoppedc                 S   s   d S rp   r   r   r   r   r   rt   a  ru   z1FileBodyProducer.startProducing.<locals>.<lambda>)r1  
_writeloopr8  ZwhenDoneZaddCallbacks)r]   consumerdr<  r   r   r   startProducingR  s
    
zFileBodyProducer.startProducingc                 c   s4   | j | j}|s| j   q0|| dV  q dS )z
        Return an iterator which reads one chunk of bytes from the input file
        and writes them to the consumer for each time it is iterated.
        N)r0  readr2  r   r\   )r]   r>  bytesr   r   r   r=  e  s    

zFileBodyProducer._writeloopc                 C   s   | j   dS )z
        Temporarily suspend copying bytes from the input file to the consumer
        by pausing the L{CooperativeTask} which drives that activity.
        N)r8  pauserq   r   r   r   pauseProducings  s    zFileBodyProducer.pauseProducingc                 C   s   | j   dS )z
        Undo the effects of a previous C{pauseProducing} and resume copying
        bytes to the consumer by resuming the L{CooperativeTask} which drives
        the write activity.
        N)r8  Zresumerq   r   r   r   resumeProducing{  s    z FileBodyProducer.resumeProducingN)r9   r:   r;   r<   r$   r   r3  r:  r@  r=  rD  rE  r   r   r   r   r/    s   	r/  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_HTTP11ClientFactoryaa  
    A factory for L{HTTP11ClientProtocol}, used by L{HTTPConnectionPool}.

    @ivar _quiescentCallback: The quiescent callback to be passed to protocol
        instances, used to return them to the connection pool.

    @ivar _metadata: Metadata about the low-level connection details,
        used to make the repr more useful.

    @since: 11.1
    c                 C   s   || _ || _d S rp   )_quiescentCallback	_metadata)r]   quiescentCallbackZmetadatar   r   r   r     s    z_HTTP11ClientFactory.__init__c                 C   s   d | j| jS )Nz_HTTP11ClientFactory({}, {}))formatrG  rH  rq   r   r   r   r     s    z_HTTP11ClientFactory.__repr__c                 C   s
   t | jS rp   )r  rG  )r]   r   r   r   r   r     s    z"_HTTP11ClientFactory.buildProtocolN)r9   r:   r;   r<   r   r   r   r   r   r   r   rF    s   rF  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_RetryingHTTP11ClientProtocolz
    A wrapper for L{HTTP11ClientProtocol} that automatically retries requests.

    @ivar _clientProtocol: The underlying L{HTTP11ClientProtocol}.

    @ivar _newConnection: A callable that creates a new connection for a
        retry.
    c                 C   s   || _ || _d S rp   )_clientProtocol_newConnection)r]   ZclientProtocolnewConnectionr   r   r   r     s    z&_RetryingHTTP11ClientProtocol.__init__c                 C   sX   |dkrdS t |tttfs dS t |trH|jD ]}|tjr0 dS q0|dk	rTdS dS )a  
        Indicate whether request should be retried.

        Only returns C{True} if method is idempotent, no response was
        received, the reason for the failed request was not due to
        user-requested cancellation, and no body was sent. The latter
        requirement may be relaxed in the future, and PUT added to approved
        method list.

        @param method: The method of the request.
        @type method: L{bytes}
        )rA   r   s   OPTIONSs   DELETEs   TRACEFNT)	r   r  r  r  r  Zreasonscheckr"   ZCancelledError)r]   r@   Z	exceptionbodyProducerZaFailurer   r   r   _shouldRetry  s    

z*_RetryingHTTP11ClientProtocol._shouldRetryc                    s(   j  } fdd}|| |S )z
        Do a request, and retry once (with a new connection) if it fails in
        a retryable manner.

        @param request: A L{Request} instance that will be requested using the
            wrapped protocol.
        c                    s2     j| j jr*  fddS | S d S )Nc                    s
   |   S rp   request)
connectionrR  r   r   rt     ru   zG_RetryingHTTP11ClientProtocol.request.<locals>.failed.<locals>.<lambda>)rQ  r@   r`   rP  rM  r   r;  rS  r]   r   r   rx     s    
z5_RetryingHTTP11ClientProtocol.request.<locals>.failed)rL  rS  Z
addErrback)r]   rS  r?  rx   r   rU  r   rS    s    
z%_RetryingHTTP11ClientProtocol.requestN)r9   r:   r;   r<   r   rQ  rS  r   r   r   r   rK    s   	rK  c                   @   sX   e Zd ZdZeZdZdZdZe	 Z
dddZdd Zd	d
 Zdd Zdd Zdd ZdS )HTTPConnectionPoolaU  
    A pool of persistent HTTP connections.

    Features:
     - Cached connections will eventually time out.
     - Limits on maximum number of persistent connections.

    Connections are stored using keys, which should be chosen such that any
    connections stored under a given key can be used interchangeably.

    Failed requests done using previously cached connections will be retried
    once if they use an idempotent method (e.g. GET), in case the HTTP server
    timed them out.

    @ivar persistent: Boolean indicating whether connections should be
        persistent. Connections are persistent by default.

    @ivar maxPersistentPerHost: The maximum number of cached persistent
        connections for a C{host:port} destination.
    @type maxPersistentPerHost: C{int}

    @ivar cachedConnectionTimeout: Number of seconds a cached persistent
        connection will stay open before disconnecting.

    @ivar retryAutomatically: C{boolean} indicating whether idempotent
        requests should be retried once if no response was received.

    @ivar _factory: The factory used to connect to the proxy.

    @ivar _connections: Map (scheme, host, port) to lists of
        L{HTTP11ClientProtocol} instances.

    @ivar _timeouts: Map L{HTTP11ClientProtocol} instances to a
        C{IDelayedCall} instance of their timeout.

    @since: 12.1
    r      Tc                 C   s   || _ || _i | _i | _d S rp   )_reactor
persistent_connections	_timeouts)r]   r%   rY  r   r   r   r     s    zHTTPConnectionPool.__init__c                    sr   j }|rf|d}j|   j|= |jdkrjrZ fdd}t||}t	|S q
 S )a  
        Supply a connection, newly created or retrieved from the pool, to be
        used for one HTTP request.

        The connection will remain out of the pool (not available to be
        returned from future calls to this method) until one HTTP request has
        been completed over it.

        Afterwards, if the connection is still open, it will automatically be
        added to the pool.

        @param key: A unique key identifying connections that can be used
            interchangeably.

        @param endpoint: An endpoint that can be used to open a new connection
            if no cached connection is available.

        @return: A C{Deferred} that will fire with a L{HTTP11ClientProtocol}
           (or a wrapper) that can be used to send a single HTTP request.
        r   	QUIESCENTc                      s     S rp   )rM  r   endpointr_   r]   r   r   rt   3  ru   z2HTTPConnectionPool.getConnection.<locals>.<lambda>)rZ  rR   popr[  r   stateretryAutomaticallyrK  r"   ZsucceedrM  )r]   r_   r^  connectionsrT  rN  r   r]  r   getConnection  s    

 z HTTPConnectionPool.getConnectionc                    s(    fdd} |t|}||S )zv
        Create a new connection.

        This implements the new connection code path for L{getConnection}.
        c                    s     |  d S rp   )_putConnectionr#   r_   r]   r   r   rI  A  s    z<HTTPConnectionPool._newConnection.<locals>.quiescentCallback)_factoryreprZconnect)r]   r_   r^  rI  rL   r   rf  r   rM  ;  s    z!HTTPConnectionPool._newConnectionc                 C   s&   |j   | j| | | j|= dS )zG
        Remove a connection from the cache and disconnect it.
        N)r[   r   rZ  remover[  )r]   r_   rT  r   r   r   _removeConnectionG  s    
z$HTTPConnectionPool._removeConnectionc                 C   s   |j dkr4ztdW n   | jd Y nX dS | j|g }t|| jkrz|d}|j	
  | j|   | j|= || | j| j| j||}|| j|< dS )z
        Return a persistent connection to the pool. This will be called by
        L{HTTP11ClientProtocol} when the connection becomes quiescent.
        r\  z5BUG: Non-quiescent protocol added to connection pool.Nr   )r`  RuntimeErrorr   r   rZ  rc   rT   maxPersistentPerHostr_  r[   r   r[  r   rX   rX  r   cachedConnectionTimeoutrj  )r]   r_   rT  rb  ZdroppedZcidr   r   r   rd  P  s.    





 z!HTTPConnectionPool._putConnectionc                 C   sd   g }t | jD ]}|D ]}||  qqi | _t | jD ]}|  q<i | _t|dd S )z
        Close all persistent connections and remove them from the pool.

        @return: L{defer.Deferred} that fires when all connections have been
            closed.
        c                 S   s   d S rp   r   )Zignr   r   r   rt   z  ru   z;HTTPConnectionPool.closeCachedConnections.<locals>.<lambda>)	r   rZ  rX   abortr[  r   r"   ZgatherResultsr   )r]   ZresultsZ	protocolsr
   Zdcr   r   r   closeCachedConnectionsk  s    
z)HTTPConnectionPool.closeCachedConnectionsN)T)r9   r:   r;   r<   rF  rg  rl  rm  ra  r5   r   r   rc  rM  rj  rd  ro  r   r   r   r   rV    s   &
&	rV  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	
_AgentBasea  
    Base class offering common facilities for L{Agent}-type classes.

    @ivar _reactor: The C{IReactorTime} implementation which will be used by
        the pool, and perhaps by subclasses as well.

    @ivar _pool: The L{HTTPConnectionPool} used to manage HTTP connections.
    c                 C   s"   |d krt |d}|| _|| _d S NF)rV  rX  _pool)r]   r%   poolr   r   r   r     s    
z_AgentBase.__init__c                 C   s8   t t|rd| d }||fdkr(|S |d t| S )z
        Compute the string to use for the value of the I{Host} header, based on
        the given scheme, host name, and port number.
           [   ])rB   rC   )rE   rF   rD   )r&   r   r   )r]   rN   rP   rO   r   r   r   _computeHostValue  s
    z_AgentBase._computeHostValuec           
         sv   t dkrt dsD djjj j	
||} fdd}	||	 |S )zk
        Issue a new request, given the endpoint and the path sent as part of
        the request.
        Nr>   c              
      s    |  tj jjdS )N)rY  	parsedURI)rS  r  Z
_constructrr  rY  )protorP  rQ   r@   rx  requestPathr]   r   r   cbConnected  s    z4_AgentBase._requestWithEndpoint.<locals>.cbConnected)r7   r4   	hasHeadercopyaddRawHeaderrw  rN   rP   rO   rr  rc  r   )
r]   r_   r^  r@   rx  rQ   rP  r{  r?  r|  r   rz  r   _requestWithEndpoint  s     
 
z_AgentBase._requestWithEndpointN)r9   r:   r;   r<   r   rw  r  r   r   r   r   rp  ~  s   	rp  c                   @   s    e Zd ZdZdd Zdd ZdS )_StandardEndpointFactorya  
    Standard HTTP endpoint destinations - TCP for HTTP, TCP+TLS for HTTPS.

    @ivar _policyForHTTPS: A web context factory which will be used to create
        SSL context objects for any SSL connections the agent needs to make.

    @ivar _connectTimeout: If not L{None}, the timeout passed to
        L{HostnameEndpoint} for specifying the connection timeout.

    @ivar _bindAddress: If not L{None}, the address passed to
        L{HostnameEndpoint} for specifying the local address to bind to.
    c                 C   s   || _ || _|| _|| _dS )a  
        @param reactor: A provider to use to create endpoints.
        @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
            types.

        @param contextFactory: A factory for TLS contexts, to control the
            verification parameters of OpenSSL.
        @type contextFactory: L{IPolicyForHTTPS}.

        @param connectTimeout: The amount of time that this L{Agent} will wait
            for the peer to accept a connection.
        @type connectTimeout: L{float} or L{None}

        @param bindAddress: The local address for client sockets to bind to.
        @type bindAddress: L{bytes} or L{None}
        N)rX  _policyForHTTPS_connectTimeout_bindAddress)r]   r%   r   connectTimeoutbindAddressr   r   r   r     s    z!_StandardEndpointFactory.__init__c                 C   s   i }| j dk	r| j |d< | j|d< zt|j}W n$ tk
rT   tdj|dY nX t| j||j	f|}|j
dkrx|S |j
dkr| j|j|j	}t||S td|j
f dS )	z
        Connect directly over TCP for C{b'http'} scheme, and TLS for
        C{b'https'}.

        @param uri: L{URI} to connect to.

        @return: Endpoint to connect to.
        @rtype: L{IStreamClientEndpoint}
        Nr   r  zdThe host of the provided URI ({uri.host!r}) contains non-ASCII octets, it should be ASCII decodable.r   rB   rE   zUnsupported scheme: %r)r  r  r   rP   UnicodeDecodeErrorr   rJ  r)   rX  rO   rN   r  r(  r*   r  )r]   r   r   rP   r^  ZconnectionCreatorr   r   r   endpointForURI  s&    







z'_StandardEndpointFactory.endpointForURIN)r9   r:   r;   r<   r   r  r   r   r   r   r    s   r  c                   @   sL   e Zd ZdZe dddfddZedddZdd Zd	d
 Z	dddZ
dS )Agenta+  
    L{Agent} is a very basic HTTP client.  It supports I{HTTP} and I{HTTPS}
    scheme URIs.

    @ivar _pool: An L{HTTPConnectionPool} instance.

    @ivar _endpointFactory: The L{IAgentEndpointFactory} which will
        be used to create endpoints for outgoing connections.

    @since: 9.0
    Nc                 C   sJ   t |s*tjt|d dtd t|}t||||}| ||| dS )a  
        Create an L{Agent}.

        @param reactor: A reactor for this L{Agent} to place outgoing
            connections.
        @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
            types.

        @param contextFactory: A factory for TLS contexts, to control the
            verification parameters of OpenSSL.  The default is to use a
            L{BrowserLikePolicyForHTTPS}, so unless you have special
            requirements you can leave this as-is.
        @type contextFactory: L{IPolicyForHTTPS}.

        @param connectTimeout: The amount of time that this L{Agent} will wait
            for the peer to accept a connection.
        @type connectTimeout: L{float}

        @param bindAddress: The local address for client sockets to bind to.
        @type bindAddress: L{bytes}

        @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which
            case a non-persistent L{HTTPConnectionPool} instance will be
            created.
        @type pool: L{HTTPConnectionPool}
        z was passed as the HTTPS policy for an Agent, but it does not provide IPolicyForHTTPS.  Since Twisted 14.0, you must pass a provider of IPolicyForHTTPS.r   )
stacklevelcategoryN)	r2   Z
providedBywarningswarnrh  DeprecationWarningr-  r  _init)r]   r%   r   r  r  rs  endpointFactoryr   r   r   r     s     
    zAgent.__init__c                 C   s   |  | }|||| |S )a  
        Create a new L{Agent} that will use the endpoint factory to figure
        out how to connect to the server.

        @param reactor: A reactor for this L{Agent} to place outgoing
            connections.
        @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
            types.

        @param endpointFactory: Used to construct endpoints which the
            HTTP client will connect with.
        @type endpointFactory: an L{IAgentEndpointFactory} provider.

        @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which
            case a non-persistent L{HTTPConnectionPool} instance will be
            created.
        @type pool: L{HTTPConnectionPool}

        @return: A new L{Agent}.
        )__new__r  )r   r%   r  rs  rS   r   r   r   usingEndpointFactory:  s    
zAgent.usingEndpointFactoryc                 C   s   t | || || _dS )a  
        Initialize a new L{Agent}.

        @param reactor: A reactor for this L{Agent} to place outgoing
            connections.
        @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
            types.

        @param endpointFactory: Used to construct endpoints which the
            HTTP client will connect with.
        @type endpointFactory: an L{IAgentEndpointFactory} provider.

        @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which
            case a non-persistent L{HTTPConnectionPool} instance will be
            created.
        @type pool: L{HTTPConnectionPool}

        @return: A new L{Agent}.
        N)rp  r   _endpointFactory)r]   r%   r  rs  r   r   r   r  U  s    zAgent._initc                 C   s   | j |S )z
        Get an endpoint for the given URI, using C{self._endpointFactory}.

        @param uri: The URI of the request.
        @type uri: L{URI}

        @return: An endpoint which can be used to connect to given address.
        )r  r  )r]   r   r   r   r   _getEndpointm  s    	zAgent._getEndpointc              	   C   sn   t | }t|}z| |}W n  tk
rD   tt  Y S X |j	|j
|jf}| |||||||jS )a)  
        Issue a request to the server indicated by the given C{uri}.

        An existing connection from the connection pool may be used or a new
        one may be created.

        I{HTTP} and I{HTTPS} schemes are supported in C{uri}.

        @see: L{twisted.web.iweb.IAgent.request}
        )r6   r   r   r   r  r  r"   Zfailr   rN   rP   rO   r  r   )r]   r@   r   rQ   rP  rx  r^  r_   r   r   r   rS  y  s    
 zAgent.request)N)NN)r9   r:   r;   r<   r%  r   r   r  r  r  rS  r   r   r   r   r     s    
,r  c                   @   s$   e Zd ZdZdddZdddZdS )	
ProxyAgentz
    An HTTP agent able to cross HTTP proxies.

    @ivar _proxyEndpoint: The endpoint used to connect to the proxy.

    @since: 11.1
    Nc                 C   s,   |d krddl m} t| || || _d S )Nr   )r%   )r   r%   rp  r   _proxyEndpoint)r]   r^  r%   rs  r   r   r   r     s    zProxyAgent.__init__c              	   C   s4   t | }d| jf}| || j|t||||S )z?
        Issue a new request via the configured proxy.
        z
http-proxy)r6   r   r  r  r   r   )r]   r@   r   rQ   rP  r_   r   r   r   rS    s    
  zProxyAgent.request)NN)NN)r9   r:   r;   r<   r   rS  r   r   r   r   r    s   
r  c                   @   sR   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZdd Z	dd Z
dd Zd
S )_FakeUrllib2Requesta  
    A fake C{urllib2.Request} object for C{cookielib} to work with.

    @see: U{http://docs.python.org/library/urllib2.html#request-objects}

    @type uri: native L{str}
    @ivar uri: Request URI.

    @type headers: L{twisted.web.http_headers.Headers}
    @ivar headers: Request headers.

    @type type: native L{str}
    @ivar type: The scheme of the URI.

    @type host: native L{str}
    @ivar host: The host[:port] of the URI.

    @since: 11.1
    c                 C   sz   t || _t | _t|}t |j| _t |j| _|j|j	fdkr\|  jdt
|j	 7  _trvt |j| _dd | _dS )zn
        Create a fake Urllib2 request.

        @param uri: Request URI.
        @type uri: L{bytes}
        rv  :c                 S   s   dS rq  r   )r   r   r   r   rt     ru   z._FakeUrllib2Request.__init__.<locals>.<lambda>N)r   r   r4   rQ   r   r   rN   typerP   rO   r   r   Zorigin_req_hostZunverifiable)r]   r   Z_urir   r   r   r     s    

z_FakeUrllib2Request.__init__c                 C   s   | j t|S rp   )rQ   r}  r   )r]   headerr   r   r   
has_header  s    z_FakeUrllib2Request.has_headerc                 C   s   | j t|t| d S rp   )rQ   r  r   )r]   namer`   r   r   r   add_unredirected_header  s    z+_FakeUrllib2Request.add_unredirected_headerc                 C   s   | j S rp   r  rq   r   r   r   get_full_url  s    z _FakeUrllib2Request.get_full_urlNc                 C   s4   | j t||}|d k	r0dd |D }|d S d S )Nc                 S   s   g | ]}t |qS r   r   r	   xr   r   r   r     s     z2_FakeUrllib2Request.get_header.<locals>.<listcomp>r   )rQ   getRawHeadersr   )r]   r  defaultrQ   r   r   r   
get_header  s
    z_FakeUrllib2Request.get_headerc                 C   s   | j S rp   )rP   rq   r   r   r   get_host  s    z_FakeUrllib2Request.get_hostc                 C   s   | j S rp   )r  rq   r   r   r   get_type  s    z_FakeUrllib2Request.get_typec                 C   s   dS rq  r   rq   r   r   r   is_unverifiable  s    z#_FakeUrllib2Request.is_unverifiable)N)r9   r:   r;   r<   r   r  r  r  r  r  r  r  r   r   r   r   r    s   
r  c                   @   s    e Zd ZdZdd Zdd ZdS )_FakeUrllib2Responsez
    A fake C{urllib2.Response} object for C{cookielib} to work with.

    @type response: C{twisted.web.iweb.IResponse}
    @ivar response: Underlying Twisted Web response.

    @since: 11.1
    c                 C   s
   || _ d S rp   r   r   r   r   r   r     s    z_FakeUrllib2Response.__init__c                    s   G  fdddt }| S )Nc                       s$   e Zd Z fddZ fddZdS )z(_FakeUrllib2Response.info.<locals>._Metac                    s    j j|g }|S rp   )r   rQ   r  )zelfr  rQ   rq   r   r   
getheaders  s    z3_FakeUrllib2Response.info.<locals>._Meta.getheadersc                    s&    j jt||}dd |D }|S )Nc                 S   s   g | ]}t |qS r   r  r  r   r   r   r     s     zD_FakeUrllib2Response.info.<locals>._Meta.get_all.<locals>.<listcomp>)r   rQ   r  r   )r  r  r  rQ   hrq   r   r   get_all  s     z0_FakeUrllib2Response.info.<locals>._Meta.get_allN)r9   r:   r;   r  r  r   rq   r   r   _Meta  s   r  )object)r]   r  r   rq   r   info  s    z_FakeUrllib2Response.infoN)r9   r:   r;   r<   r   r  r   r   r   r   r    s   r  c                   @   s*   e Zd ZdZdd Zd	ddZdd ZdS )
CookieAgentaj  
    L{CookieAgent} extends the basic L{Agent} to add RFC-compliant
    handling of HTTP cookies.  Cookies are written to and extracted
    from a C{cookielib.CookieJar} instance.

    The same cookie jar instance will be used for any requests through this
    agent, mutating it whenever a I{Set-Cookie} header appears in a response.

    @type _agent: L{twisted.web.client.Agent}
    @ivar _agent: Underlying Twisted Web agent to issue requests through.

    @type cookieJar: C{cookielib.CookieJar}
    @ivar cookieJar: Initialized cookie jar to read cookies from and store
        cookies to.

    @since: 11.1
    c                 C   s   || _ || _d S rp   )_agent	cookieJar)r]   rS   r  r   r   r   r   2  s    zCookieAgent.__init__Nc                 C   s|   |dkrt  }t|}|dsX| j| |dd}|dk	rX| }|dt| | j	
||||}|| j| |S )a  
        Issue a new request to the wrapped L{Agent}.

        Send a I{Cookie} header if a cookie for C{uri} is stored in
        L{CookieAgent.cookieJar}. Cookies are automatically extracted and
        stored from requests.

        If a C{'cookie'} header appears in C{headers} it will override the
        automatic cookie header obtained from the cookie jar.

        @see: L{Agent.request}
        Nr?   ZCookie)r4   r  r}  r  Zadd_cookie_headerr  r~  r  r   r  rS  r   _extractCookies)r]   r@   r   rQ   rP  ZlastRequestZcookieHeaderr?  r   r   r   rS  7  s    
zCookieAgent.requestc                 C   s   t |}| j|| |S )z
        Extract response cookies and store them in the cookie jar.

        @type response: L{twisted.web.iweb.IResponse}
        @param response: Twisted Web response.

        @param request: A urllib2 compatible request object.
        )r  r  Zextract_cookies)r]   r   rS  Zrespr   r   r   r  U  s    	zCookieAgent._extractCookies)NN)r9   r:   r;   r<   r   rS  r  r   r   r   r   r    s   
r  c                   @   s    e Zd ZdZdd Zdd ZdS )GzipDecoderz
    A wrapper for a L{Response} instance which handles gzip'ed body.

    @ivar original: The original L{Response} object.

    @since: 11.1
    c                 C   s   || _ t| _d S rp   )originalr.   r   r   r   r   r   r   m  s    zGzipDecoder.__init__c                 C   s   | j t|| j  dS )zf
        Override C{deliverBody} to wrap the given C{protocol} with
        L{_GzipProtocol}.
        N)r  deliverBody_GzipProtocol)r]   r#   r   r   r   r  r  s    zGzipDecoder.deliverBodyN)r9   r:   r;   r<   r   r  r   r   r   r   r  d  s   r  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	r  a0  
    A L{Protocol} implementation which wraps another one, transparently
    decompressing received data.

    @ivar _zlibDecompress: A zlib decompress object used to decompress the data
        stream.

    @ivar _response: A reference to the original response, in case of errors.

    @since: 11.1
    c                 C   s"   || _ || _tdtj | _d S )Nr   )r  	_responsezlibZdecompressobjZ	MAX_WBITS_zlibDecompress)r]   r#   r   r   r   r   r     s    z_GzipProtocol.__init__c                 C   sL   z| j |}W n& tjk
r6   tt g| jY nX |rH| j| dS )zz
        Decompress C{data} with the zlib decompressor, forwarding the raw data
        to the original protocol.
        N)	r  
decompressr  r-   r  r   r  r  dataReceived)r]   r^   rawDatar   r   r   r    s    z_GzipProtocol.dataReceivedc                 C   sX   z| j  }W n( tjk
r6   t|t g| jY nX |rH| j| | j	| dS )zr
        Forward the connection lost event, flushing remaining data from the
        decompressor if any.
        N)
r  flushr  r-   r  r   r  r  r  r   )r]   r   r  r   r   r   r     s    z_GzipProtocol.connectionLostNr9   r:   r;   r<   r   r  r   r   r   r   r   r  {  s   r  c                   @   s*   e Zd ZdZdd Zd	ddZdd ZdS )
ContentDecoderAgenta^  
    An L{Agent} wrapper to handle encoded content.

    It takes care of declaring the support for content in the
    I{Accept-Encoding} header, and automatically decompresses the received data
    if it's effectively using compression.

    @param decoders: A list or tuple of (name, decoder) objects. The name
        declares which decoding the decoder supports, and the decoder must
        return a response object when called/instantiated. For example,
        C{(('gzip', GzipDecoder))}. The order determines how the decoders are
        going to be advertized to the server.

    @since: 11.1
    c                 C   s*   || _ t|| _ddd |D | _d S )N   ,c                 S   s   g | ]}|d  qS )r   r   )r	   decoderr   r   r   r     s     z0ContentDecoderAgent.__init__.<locals>.<listcomp>)r  dict	_decodersrZ   
_supported)r]   rS   Zdecodersr   r   r   r     s    
zContentDecoderAgent.__init__Nc                 C   sD   |dkrt  }n| }|d| j | j||||}|| jS )zv
        Send a client request which declares supporting compressed content.

        @see: L{Agent.request}.
        Ns   accept-encoding)r4   r~  r  r  r  rS  r   _handleResponser]   r@   r   rQ   rP  r   r   r   r   rS    s    zContentDecoderAgent.requestc                 C   s   |j dg }d|d}|rZ|  }| j|}|dk	rL||}q|| qZq|rv|j 	dd|g n|j 
d |S )zX
        Check if the response is encoded, and wrap it to handle decompression.
        s   content-encodingr  N)rQ   r  rZ   r   r_  r   r  rR   rX   ZsetRawHeadersZremoveHeader)r]   r   ZcontentEncodingHeadersr  r  r   r   r   r    s&     

 
z#ContentDecoderAgent._handleResponse)NN)r9   r:   r;   r<   r   rS  r  r   r   r   r   r    s   
r  s   AuthorizationrJ   s   Cookie2s   Proxy-Authorizations   WWW-Authenticatec                   @   sb   e Zd ZdZejejejgZej	gZ
deeee dddZddd	Zd
d Zdd Zdd ZdS )RedirectAgenta  
    An L{Agent} wrapper which handles HTTP redirects.

    The implementation is rather strict: 301 and 302 behaves like 307, not
    redirecting automatically on methods different from I{GET} and I{HEAD}.

    See L{BrowserLikeRedirectAgent} for a redirecting Agent that behaves more
    like a web browser.

    @param redirectLimit: The maximum number of times the agent is allowed to
        follow redirects before failing with a L{error.InfiniteRedirection}.

    @param sensitiveHeaderNames: An iterable of C{bytes} enumerating the names
        of headers that must not be transmitted when redirecting to a different
        origins.  These will be consulted in addition to the protocol-specified
        set of headers that contain sensitive information.

    @cvar _redirectResponses: A L{list} of HTTP status codes to be redirected
        for I{GET} and I{HEAD} methods.

    @cvar _seeOtherResponses: A L{list} of HTTP status codes to be redirected
        for any method and the method altered to I{GET}.

    @since: 11.1
    r   r   )rS   r   sensitiveHeaderNamesc                 C   s.   || _ || _dd |D }|t || _d S )Nc                 S   s   h | ]}t |qS r   )_canonicalHeaderName)r	   Zeachr   r   r   	<setcomp>  s     z)RedirectAgent.__init__.<locals>.<setcomp>)r  _redirectLimitupdate_defaultSensitiveHeaders_sensitiveHeaderNames)r]   rS   r   r  Z	sensitiver   r   r   r     s
    
zRedirectAgent.__init__Nc                 C   s&   | j ||||}|| j|||dS )zb
        Send a client request following HTTP redirects.

        @see: L{Agent.request}.
        r   )r  rS  r   r  r  r   r   r   rS  #  s        zRedirectAgent.requestc                 C   s
   t ||S )a2  
        Resolve the redirect location against the request I{URI}.

        @type requestURI: C{bytes}
        @param requestURI: The request I{URI}.

        @type location: C{bytes}
        @param location: The redirect location.

        @rtype: C{bytes}
        @return: Final resolved I{URI}.
        )r   )r]   Z
requestURIr|   r   r   r   _resolveLocation.  s    zRedirectAgent._resolveLocationc                    s  |j kr,tj jd|d}tt|g  jdg }|s^t jd|}tt|g 	||d }|rt
|}	t
|}
|	j|
jko|	j|
jko|	j|
jk}|stfdd| D }j|||} fdd	}|| |j||||d
 S )z
        Handle a redirect response, checking the number of redirects already
        followed, and extracting the location header fields.
        rz   r{   ry   s   No location header fieldr   c                    s    i | ]\}}| j kr||qS r   )r  )r	   ZrawNameZrawValuerq   r   r   
<dictcomp>Y  s   
 z1RedirectAgent._handleRedirect.<locals>.<dictcomp>c                    s   |    | S rp   )ZsetPreviousResponse)ZnewResponser  r   r   _chainResponse`  s    
z5RedirectAgent._handleRedirect.<locals>._chainResponserw   )r  r-   r   coder  r   rQ   r  ZRedirectWithNoLocationr  r   r   rN   rP   rO   r4   ZgetAllRawHeadersr  rS  r   r  )r]   r   r@   r   rQ   redirectCountr   ZlocationHeadersr|   rx  ZparsedLocationZ
sameOriginr   r  r   )r   r]   r   _handleRedirect>  sP    
  





    zRedirectAgent._handleRedirectc                 C   sh   |j | jkrF|dkr4tj|j |d}tt|g|| |||||S |j | jkrd| |d|||S |S )zY
        Handle the response, making another request if it indicates a redirect.
        )rA   r   r{   rA   )r  _redirectResponsesr-   r   r  r   r  _seeOtherResponses)r]   r   r@   r   rQ   r  r   r   r   r   r  h  s    zRedirectAgent._handleResponse)r   r   )NN)r9   r:   r;   r<   r!   MOVED_PERMANENTLYFOUNDTEMPORARY_REDIRECTr  	SEE_OTHERr  r/   r   r   rB  r   rS  r  r  r  r   r   r   r   r    s      
*r  c                   @   s(   e Zd ZdZejgZejejej	gZ
dS )BrowserLikeRedirectAgentaO  
    An L{Agent} wrapper which handles HTTP redirects in the same fashion as web
    browsers.

    Unlike L{RedirectAgent}, the implementation is more relaxed: 301 and 302
    behave like 303, redirecting automatically on any method and altering the
    redirect request to a I{GET}.

    @see: L{RedirectAgent}

    @since: 13.1
    N)r9   r:   r;   r<   r!   r  r  r  r  r  r  r   r   r   r   r  y  s   r  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_ReadBodyProtocolak  
    Protocol that collects data sent to it.

    This is a helper for L{IResponse.deliverBody}, which collects the body and
    fires a deferred with it.

    @ivar deferred: See L{__init__}.
    @ivar status: See L{__init__}.
    @ivar message: See L{__init__}.

    @ivar dataBuffer: list of byte-strings received
    @type dataBuffer: L{list} of L{bytes}
    c                 C   s   || _ || _|| _g | _dS )a#  
        @param status: Status of L{IResponse}
        @ivar status: L{int}

        @param message: Message of L{IResponse}
        @type message: L{bytes}

        @param deferred: deferred to fire when response is complete
        @type deferred: L{Deferred} firing with L{bytes}
        N)r   rg   rh   
dataBuffer)r]   rg   rh   r   r   r   r   r     s    z_ReadBodyProtocol.__init__c                 C   s   | j | dS )z?
        Accumulate some more bytes from the response.
        N)r  rX   r   r   r   r   r    s    z_ReadBodyProtocol.dataReceivedc                 C   s\   | tr | jd| j n8| trL| jt| j	| j
d| j n| j| dS )z
        Deliver the accumulated response bytes to the waiting L{Deferred}, if
        the response body has been completely received without error.
        ru   N)rO  r  r   r   rZ   r  r  r   r8   rg   rh   r   r   r   r   r     s    



z _ReadBodyProtocol.connectionLostNr  r   r   r   r   r    s   r  c                    sd    fdd}t |}t| j| j|fdd |  jdk	r`  dkr`tjdt	dd |S )	a  
    Get the body of an L{IResponse} and return it as a byte string.

    This is a helper function for clients that don't want to incrementally
    receive the body of an HTTP response.

    @param response: The HTTP response for which the body will be read.
    @type response: L{IResponse} provider

    @return: A L{Deferred} which will fire with the body of the response.
        Cancelling it will close the connection to the server immediately.
    c                    s     }|dk	r|  dS )z
        Cancel a L{readBody} call, close the connection to the HTTP server
        immediately, if it is still open.

        @param deferred: The cancelled L{defer.Deferred}.
        Nr   )r   rn  )getAbortr   r   r     s    zreadBody.<locals>.cancelc                      s   t  jdd S )Nr   )rK   r[   r   re  r   r   r    s    zreadBody.<locals>.getAbortNzLUsing readBody with a transport that does not have an abortConnection methodr   )r  r  )
r"   r   r  r  phraser  r[   r  r  r  )r   r   r?  r   )r  r#   r   readBody  s    

r  r  r  r  r  r  r  )N)N)N)r<   Z
__future__r   r   r   r  r  r   r   r   r   ImportErrorZurllib.parser   Zzope.interfacer   typingr   	functoolsr   Ztwisted.python.compatr   r   r   r   r   r   Ztwisted.python.deprecater   r   r   Ztwisted.python.failurer   Zincrementalr    Ztwisted.webr!   r   r"   r#   r$   r%   Ztwisted.internet.abstractr&   Ztwisted.internet.interfacesr'   r(   Ztwisted.internet.endpointsr)   r*   Ztwisted.python.utilr+   Ztwisted.python.componentsr,   r-   Ztwisted.web.iwebr.   r/   r0   r1   r2   r3   Ztwisted.web.http_headersr4   Ztwisted.loggerr5   Ztwisted.web._newclientr6   r7   r   r8   r   r=   r   r   r   r   r  r   r   r   r  r  r  r  Ztwisted.web.errorr  r  r  r  r  r  r  r  r  r  r  r  ZOpenSSLr  Ztwisted.internet.sslr  r  r  r  r  r%  r   r:   r9   r*  r-  r/  ZFactoryrF  rK  rV  rp  r  r  r  r  r  r  r  r  r  Z_canonicalNameCapsr  	frozensetr  r  r  ZProtocolr  r  __all__r   r   r   r   <module>   s   	 G! 8mp
4
+"(kA ;F #MD/> 7+