Spamworldpro Mini Shell
Spamworldpro


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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

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

�bs��	@sdZddlZddlZddlZddlZddlmZddlmZddl	m
Z
mZmZ
ddlmZddlmZddlmZmZmZdd	lmZdd
lmZmZddlmZmZddlmZdd
l m!Z!m"Z"ddl#m$Z$ddl%m&Z&m'Z'ddl(m)Z)ddl*m+Z+m,Z,ddl-m.Z.m/Z/ddl0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8dd�ZGdd�de+j9�Z:Gdd�d�Z;dd�Z<d\dd�Z=ddl-m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHdd lImJZJzdd!lKmLZLWneMy�dZLYnwdd"lNmOZOmPZPmQZQd#d$�ZRGd%d&�d&�ZSee7�Gd'd(�d(��ZTe&ed)d*dd�e'eSed)d*dd�eTd+��Ud,�d-eSjVeSjW�ee7�Gd.d/�d/��ZXee�Gd0d1�d1��ZYee7�Gd2d3�d3��ZZee6�Gd4d5�d5��Z[Gd6d7�d7ej\�Z]Gd8d9�d9�Z^Gd:d;�d;�Z_Gd<d=�d=�Z`ee5�Gd>d?�d?��Zaee4�Gd@dA�dAe`��Zbee4�GdBdC�dCe`��ZcGdDdE�dE�ZdGdFdG�dG�Zeee4�GdHdI�dI��ZfGdJdK�dKe$e8��ZgGdLdM�dMe$e��Zhee4�GdNdO�dO��Zie1�jjZkelgdP��Zmee4�GdQdR�dR��ZnGdSdT�dTen�ZoGdUdV�dVejp�ZqdWe8dXejresfdYdZ�Ztgd[�ZudS)]z
HTTP client.
�N)�wraps)�Iterable)�	urldefrag�urljoin�
urlunparse)�implementer)�Version)�defer�protocol�task)�
isIPv6Address)�HostnameEndpoint�
wrapClientTLS)�IOpenSSLContextFactory�	IProtocol)�Logger)�nativeString�
networkString)�proxyForInterface)�deprecatedModuleAttribute�getDeprecationWarningString)�Failure)�error�http)�_ensureValidMethod�_ensureValidURI)�Headers)�UNKNOWN_LENGTH�IAgent�IAgentEndpointFactory�
IBodyProducer�IPolicyForHTTPS�	IResponsecCs ttdd�|D���}|�d�S)Ncss�|]}|�d�VqdS)�charmapN)�decode)�.0�p�r'�4/usr/lib/python3/dist-packages/twisted/web/client.py�	<genexpr>0s�zurlunparse.<locals>.<genexpr>r#)�_urlunparse�tuple�encode)�parts�resultr'r'r(r/s
rc@seZdZdZdS)�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(r/4sr/c@s:eZdZdZdd�Zeddd��Zdd�Zed	d
��Z	dS)�URIzd
    A URI object.

    @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21}
    c		Cs:||_||_|�d�|_||_||_||_||_||_dS)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)	�scheme�netloc�strip�host�port�path�params�query�fragment)	�selfr5r6r8r9r:r;r<r=r'r'r(�__init__Cs
zURI.__init__Nc	Cs�|��}t�|�\}}}}}}|dur|dkrd}nd}d|vr=|�dd�\}	}
zt|
�}
Wnty<||}	}
Ynw||}	}
||||	|
||||�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.
        N�https��P�:�)r7r�urlparse�rsplit�int�
ValueError)�cls�uri�defaultPortr5r6r:r;r<r=r8r9r'r'r(�	fromBytesgs�
z
URI.fromBytescCs t|j|j|j|j|j|jf�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}.
        )rr5r6r:r;r<r=�r>r'r'r(�toBytes�s��zURI.toBytescCs*tdd|j|j|jdf�}|dkrd}|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}
        ��/)rr:r;r<)r>r:r'r'r(�
originForm�s
zURI.originForm�N)
r0r1r2r3r?�classmethodrLrN�propertyrQr'r'r'r(r4<s$!r4cCs0t|�\}}tt||��\}}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{urllib.parse.urljoin()}

    @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2}
    �#)rr)�base�url�baseFrag�urlFragr'r'r(�_urljoin�srZc	Os�t�t|����}||g|�Ri|��}ddlm}|jdkr;ddlm}|dur-|��}|�	t
|j�|j||�|S|�
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}
    r��reactorr@)�sslN)r4rLrr7�twisted.internetr\r5r]�ClientContextFactory�
connectSSLrr8r9�
connectTCP)	rW�factoryFactory�contextFactory�args�kwargsrJ�factoryr\r]r'r'r(�_makeGetterFactory�s
�rg)�HTTP11ClientProtocol�PotentialDataLoss�Request�RequestGenerationFailed�RequestNotSent�RequestTransmissionFailed�Response�ResponseDone�ResponseFailed�ResponseNeverReceived�_WrapperException)�SchemeNotSupported)�SSL)�CertificateOptions�optionsForClientTLS�
platformTrustcCs tdurt|�dd��}|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_std��)z�
            pyOpenSSL is not available.

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

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

            @raise NotImplementedError: Always.
            zSSL support unavailable)�NotImplementedError)�a�kwr'r'r(�raiseNotImplementedsz(_requireSSL.<locals>.raiseNotImplemented)rtr)�	decorateer{r'r'r(�_requireSSLs

r}c@s$eZdZdZdd�Zedd��ZdS)�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.
    cCsttjt�d�S)z�
        Return a L{CertificateOptions}.

        @param hostname: ignored

        @param port: ignored

        @return: A new CertificateOptions instance.
        @rtype: L{CertificateOptions}
        )�method�	trustRoot)rurt�
SSLv23_METHODrw�r>�hostnamer9r'r'r(�_getCertificateOptions1�z.WebClientContextFactory._getCertificateOptionscCs|�||���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�>r�z"WebClientContextFactory.getContextN)r0r1r2r3r�r}r�r'r'r'r(r~&s


r~c@s&eZdZdZddd�Zedd��ZdS)�BrowserLikePolicyForHTTPSz1
    SSL connection creator for web clients.
    NcC�
||_dSrR)�
_trustRoot)r>r�r'r'r(r?R�
z"BrowserLikePolicyForHTTPS.__init__cCst|�d�|jd�S)a 
        Create a L{client connection creator
        <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} for a
        given network location.

        @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�)rvr$r�r�r'r'r(�creatorForNetlocUsz*BrowserLikePolicyForHTTPS.creatorForNetlocrR)r0r1r2r3r?r}r�r'r'r'r(r�Ls

r��Twisted�)�replacementz; rDc@s"eZdZdZddd�Zdd�ZdS)	�HostnameCachingHTTPSPolicya�
    IPolicyForHTTPS that wraps a L{IPolicyForHTTPS} and caches the created
    L{IOpenSSLClientConnectionCreator}.

    This policy will cache up to C{cacheSize}
    L{client connection creators <twisted.internet.interfaces.
    IOpenSSLClientConnectionCreator>} for reuse in subsequent requests to
    the same hostname.

    @ivar _policyForHTTPS: See C{policyforHTTPS} parameter of L{__init__}.

    @ivar _cache: A cache associating hostnames to their
        L{client connection creators <twisted.internet.interfaces.
        IOpenSSLClientConnectionCreator>}.
    @type _cache: L{collections.OrderedDict}

    @ivar _cacheSize: See C{cacheSize} parameter of L{__init__}.

    @since: Twisted 19.2.0
    �cCs||_t��|_||_dS)z�
        @param policyforHTTPS: The IPolicyForHTTPS to wrap.
        @type policyforHTTPS: L{IPolicyForHTTPS}

        @param cacheSize: The maximum size of the hostname cache.
        @type cacheSize: L{int}
        N)�_policyForHTTPS�collections�OrderedDict�_cache�
_cacheSize)r>�policyforHTTPS�	cacheSizer'r'r(r?�s

z#HostnameCachingHTTPSPolicy.__init__cCsh|�d�}z|j�|�}Wnty|j�||�}Ynw||j|<t|j�|jkr2|jjdd�|S)a<
        Create a L{client connection creator
        <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} for a
        given network location and cache it for future use.

        @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>}
        r�F)�last)	r$r��pop�KeyErrorr�r��lenr��popitem)r>r�r9r8�creatorr'r'r(r��s
�
z+HostnameCachingHTTPSPolicy.creatorForNetlocN)r��r0r1r2r3r?r�r'r'r'r(r�vs
r�c@� eZdZdZdd�Zdd�ZdS)�_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}
    cC�
||_dS)z�
        Initialize a L{_ContextFactoryWithContext} with a context.

        @param context: An SSL context.
        @type context: L{OpenSSL.SSL.Context}
        N��_context)r>�contextr'r'r(r?�s
z#_ContextFactoryWithContext.__init__cC�|jS)z�
        Return the context created by
        L{_DeprecatedToCurrentPolicyForHTTPS._webContextFactory}.

        @return: A context.
        @rtype: L{OpenSSL.SSL.Context}
        r�rMr'r'r(r��sz%_ContextFactoryWithContext.getContextN)r0r1r2r3r?r�r'r'r'r(r��s	r�c@r�)�"_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).
    cCr�)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>�webContextFactoryr'r'r(r?�s
	z+_DeprecatedToCurrentPolicyForHTTPS.__init__cCs|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�r9r�r'r'r(r��sz3_DeprecatedToCurrentPolicyForHTTPS.creatorForNetlocNr�r'r'r'r(r��s	r�c@sNeZdZdZedfdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�ZdS)�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.
    icCs$||_|j|_||_|�|�|_dSrR)�
_inputFile�	cooperate�
_cooperate�	_readSize�_determineLength�length)r>�	inputFile�
cooperator�readSizer'r'r(r?szFileBodyProducer.__init__cCsTz|j}|j}WntytYSw|�}|dtj�|�}||tj�||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)�seek�tell�AttributeErrorr�os�SEEK_END�SEEK_SET)r>�fObjr�r��originalPosition�endr'r'r(r�s
�z!FileBodyProducer._determineLengthcCs2|j��z|j��WdStjyYdSw)z�
        Permanently stop writing bytes from the file to the consumer by
        stopping the underlying L{CooperativeTask}.
        N)r��close�_task�stopr�TaskFinishedrMr'r'r(�
stopProducing+s
�zFileBodyProducer.stopProducingcs<����|���_�j��}�fdd�}|�dd�|�|S)aZ
        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.  If this L{Deferred} is cancelled before it is
        fired, stop reading and writing bytes.

        @param consumer: Any L{IConsumer} provider
        cs6|�tj�r���t��S|�tj�r	t��S|SrR)�checkr	�CancelledErrorr�r�TaskStopped�Deferred��reasonrMr'r(�maybeStoppedBs��z5FileBodyProducer.startProducing.<locals>.maybeStoppedcS�dSrRr')�ignoredr'r'r(�<lambda>M�z1FileBodyProducer.startProducing.<locals>.<lambda>)r��
_writeloopr��whenDone�addCallbacks)r>�consumer�dr�r'rMr(�startProducing6s
	
zFileBodyProducer.startProducingccs6�	|j�|j�}|s|j��dS|�|�dVq)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.
        TN)r��readr�r��write)r>r��bytesr'r'r(r�Ps�

�zFileBodyProducer._writeloopcC�|j��dS)z�
        Temporarily suspend copying bytes from the input file to the consumer
        by pausing the L{CooperativeTask} which drives that activity.
        N)r��pauserMr'r'r(�pauseProducing]szFileBodyProducer.pauseProducingcCr�)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)r��resumerMr'r'r(�resumeProducingdsz FileBodyProducer.resumeProducingN)r0r1r2r3rr?r�r�r�r�r�r�r'r'r'r(r��s
r�c@s.eZdZdZdd�Zdefdd�Zdd�Zd	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
    cC�||_||_dSrR)�_quiescentCallback�	_metadata)r>�quiescentCallback�metadatar'r'r(r?z�
z_HTTP11ClientFactory.__init__�returncCsd�|j|j�S)Nz_HTTP11ClientFactory({}, {}))�formatr�r�rMr'r'r(�__repr__~s�z_HTTP11ClientFactory.__repr__cCs
t|j�SrR)rhr�)r>�addrr'r'r(�
buildProtocol�r�z"_HTTP11ClientFactory.buildProtocolN)r0r1r2r3r?�strr�r�r'r'r'r(r�ms
r�c@�(eZdZdZdd�Zdd�Zdd�ZdS)	�_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.
    cCr�rR)�_clientProtocol�_newConnection)r>�clientProtocol�
newConnectionr'r'r(r?�r�z&_RetryingHTTP11ClientProtocol.__init__cCsX|dvrdSt|tttf�sdSt|t�r$|jD]}|�tj�r#dSq|dur*dSdS)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}
        )�GET�HEADsOPTIONSsDELETEsTRACEFNT)	�
isinstancerlrmrqrr�reasonsr�r	r�)r>r�	exception�bodyProducer�aFailurer'r'r(�_shouldRetry�s
�

�z*_RetryingHTTP11ClientProtocol._shouldRetrycs(�j���}��fdd�}|�|�|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.
        cs.���j|j�j�r�����fdd��S|S)Ncs
|���SrR��request)�
connectionr�r'r(r��s
zG_RetryingHTTP11ClientProtocol.request.<locals>.failed.<locals>.<lambda>)r�r�valuer�r��addCallbackr��r�r>r'r(�failed�s

�z5_RetryingHTTP11ClientProtocol.request.<locals>.failed)r�r��
addErrback)r>r�r�r�r'r�r(r��s
z%_RetryingHTTP11ClientProtocol.requestN)r0r1r2r3r?r�r�r'r'r'r(r��s
	r�c@sXeZdZdZeZdZdZdZe	�Z
ddd�Zdd�Zd	d
�Z
dd�Zd
d�Zdd�ZdS)�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
    ���TcCs||_||_i|_i|_dSrR)�_reactor�
persistent�_connections�	_timeouts)r>r\rr'r'r(r?�s
zHTTPConnectionPool.__init__cst�j���}|r4|�d�}�j|���j|=|jdkr2�jr-���fdd�}t||�}t�	|�S|s��
���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�	QUIESCENTcs�����SrR)r�r'��endpoint�keyr>r'r(r�sz2HTTPConnectionPool.getConnection.<locals>.<lambda>)r�getr�r�cancel�state�retryAutomaticallyr�r	�succeedr�)r>rr�connectionsr�r�r'rr(�
getConnection�s

�
�
z HTTPConnectionPool.getConnectioncs(��fdd�}��|t|��}|�|�S)zv
        Create a new connection.

        This implements the new connection code path for L{getConnection}.
        cs���|�dSrR)�_putConnection�r
�rr>r'r(r�'�z<HTTPConnectionPool._newConnection.<locals>.quiescentCallback)�_factory�repr�connect)r>rrr�rfr'rr(r� s
z!HTTPConnectionPool._newConnectioncCs&|j��|j|�|�|j|=dS)zG
        Remove a connection from the cache and disconnect it.
        N)�	transport�loseConnectionr�remover)r>rr�r'r'r(�_removeConnection-s
z$HTTPConnectionPool._removeConnectioncCs�|jdkrztd��ty|j�d�YdSw|j�|g�}t|�|jkr=|�	d�}|j
��|j|�
�|j|=|�|�|j�|j|j||�}||j|<dS)z�
        Return a persistent connection to the pool. This will be called by
        L{HTTP11ClientProtocol} when the connection becomes quiescent.
        rz5BUG: Non-quiescent protocol added to connection pool.Nr)r�RuntimeError�
BaseException�_log�failurer�
setdefaultr��maxPersistentPerHostr�rrrr
�appendr�	callLater�cachedConnectionTimeoutr)r>rr�r�dropped�cidr'r'r(r5s,
���


�z!HTTPConnectionPool._putConnectioncCsdg}|j��D]}|D]	}|�|���qqi|_|j��D]}|��qi|_t�|��dd��S)z�
        Close all persistent connections and remove them from the pool.

        @return: L{defer.Deferred} that fires when all connections have been
            closed.
        cSr�rRr')�ignr'r'r(r�`r�z;HTTPConnectionPool.closeCachedConnections.<locals>.<lambda>)	r�valuesr!�abortrr
r	�
gatherResultsr�)r>�results�	protocolsr&�dcr'r'r(�closeCachedConnectionsQs�
z)HTTPConnectionPool.closeCachedConnectionsN)T)r0r1r2r3r�rr r#rrrr?rr�rrr-r'r'r'r(r��s&
&
r�c@r�)	�
_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.
    cCs"|dur	t|d�}||_||_dS�NF)r�r�_pool)r>r\�poolr'r'r(r?ms

z_AgentBase.__init__cCs4tt|��rd|d}||fdvr|Sd||fS)z�
        Compute the string to use for the value of the I{Host} header, based on
        the given scheme, host name, and port number.
        �[�]�)�httprB)r@rAs%b:%d)rr)r>r5r8r9r'r'r(�_computeHostValuess
z_AgentBase._computeHostValuec
s�t�t�std��dt���d���t����durt����d�s4������d��	�j
�j�j���j
�||�}������fdd�}	|�|	�|S)zk
        Issue a new request, given the endpoint and the path sent as part of
        the request.
        zmethod=z is z, but must be bytesNshostc
s |�tj�����jj�d��S)N)r�	parsedURI)r�rj�
_constructr0r)�proto�r��headersrr7�requestPathr>r'r(�cbConnected�s��z4_AgentBase._requestWithEndpoint.<locals>.cbConnected)r�r��	TypeError�typerr�	hasHeader�copy�addRawHeaderr6r5r8r9r0rr�)
r>rrrr7r;r�r<r�r=r'r:r(�_requestWithEndpoint~s"

��
z_AgentBase._requestWithEndpointN)r0r1r2r3r?r6rCr'r'r'r(r.cs
	r.c@r�)�_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.
    cCs||_||_||_||_dS)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)rr��_connectTimeout�_bindAddress)r>r\rc�connectTimeout�bindAddressr'r'r(r?�s
z!_StandardEndpointFactory.__init__cCs�i}|jdur|j|d<|j|d<zt|j�}Wnty'tdj|d���wt|j||j	fi|��}|j
dkr;|S|j
dkrN|j�|j|j	�}t
||�Std|j
����)	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}
        N�timeoutrHzdThe host of the provided URI ({uri.host!r}) contains non-ASCII octets, it should be ASCII decodable.�rJr5r@zUnsupported scheme: )rErFrr8�UnicodeDecodeErrorrHr�r
rr9r5r�r�rrs)r>rJrer8r�connectionCreatorr'r'r(�endpointForURI�s,



���	

�
z'_StandardEndpointFactory.endpointForURIN)r0r1r2r3r?rMr'r'r'r(rD�s
rDc@sLeZdZdZe�dddfdd�Zed
dd��Zdd�Zd	d
�Z	ddd�Z
dS)�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
    NcCsJt�|�stjt|�ddtd�t|�}t||||�}|�|||�dS)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)	r!�
providedBy�warnings�warnr�DeprecationWarningr�rD�_init)r>r\rcrGrHr1�endpointFactoryr'r'r(r?s
"���zAgent.__init__cCs|�|�}|�|||�|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__rU)rIr\rVr1�agentr'r'r(�usingEndpointFactory2s
zAgent.usingEndpointFactorycCst�|||�||_dS)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)r.r?�_endpointFactory)r>r\rVr1r'r'r(rULs
zAgent._initcCs|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.
        )rZrM)r>rJr'r'r(�_getEndpointcs	zAgent._getEndpointc	Cslt|���}t�|�}z|�|�}Wnty!t�t��YSw|j	|j
|jf}|�|||||||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}
        )rr7r4rLr[rsr	�failrr5r8r9rCrQ)r>rrJr;r�r7rrr'r'r(r�ns"
��z
Agent.requestrR�NN)r0r1r2r3r�r?rSrYrUr[r�r'r'r'r(rN�s
�1rNc@s$eZdZdZddd�Zddd�ZdS)�
ProxyAgentz�
    An HTTP agent able to cross HTTP proxies.

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

    @since: 11.1
    NcCs,|dur
ddlm}t�|||�||_dS)Nrr[)r^r\r.r?�_proxyEndpoint)r>rr\r1r'r'r(r?�s
zProxyAgent.__init__c	Cs4t|���}d|jf}|�||j|t�|�|||�S)z?
        Issue a new request via the configured proxy.
        z
http-proxy)rr7r_rCr4rL)r>rrJr;r�rr'r'r(r��s
�zProxyAgent.requestr])r0r1r2r3r?r�r'r'r'r(r^�s
r^c@sReZdZdZdd�Zdd�Zdd�Zdd	�Zddd�Zd
d�Z	dd�Z
dd�Zd
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
    cCsvt|�|_t�|_t�|�}t|j�|_t|j�|_|j|j	fdvr.|jdt
|j	�7_t|j�|_dd�|_dS)zn
        Create a fake Urllib2 request.

        @param uri: Request URI.
        @type uri: L{bytes}
        r4�:cS�dSr/r')�_r'r'r(r��r�z._FakeUrllib2Request.__init__.<locals>.<lambda>N)
rrJrr;r4rLr5r?r8r9r��origin_req_host�unverifiable)r>rJ�_urir'r'r(r?�s

z_FakeUrllib2Request.__init__cCs|j�t|��SrR)r;r@r)r>�headerr'r'r(�
has_header�rz_FakeUrllib2Request.has_headercCs|j�t|�t|��dSrR)r;rBr)r>�namer�r'r'r(�add_unredirected_header�sz+_FakeUrllib2Request.add_unredirected_headercCr�rRrJrMr'r'r(�get_full_url��z _FakeUrllib2Request.get_full_urlNcCs4|j�t|�|�}|durdd�|D�}|dSdS)NcS�g|]}t|��qSr'�r�r%�xr'r'r(�
<listcomp>��z2_FakeUrllib2Request.get_header.<locals>.<listcomp>r)r;�
getRawHeadersr)r>ri�defaultr;r'r'r(�
get_header�s
z_FakeUrllib2Request.get_headercCr�rR)r8rMr'r'r(�get_host�rlz_FakeUrllib2Request.get_hostcCr�rR)r?rMr'r'r(�get_type�rlz_FakeUrllib2Request.get_typecCrbr/r'rMr'r'r(�is_unverifiable�sz#_FakeUrllib2Request.is_unverifiablerR)r0r1r2r3r?rhrjrkrurvrwrxr'r'r'r(r`�s
r`c@r�)�_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
    cCr�rR��response�r>r{r'r'r(r?r�z_FakeUrllib2Response.__init__csG�fdd�d�}|�S)Ncs$eZdZ�fdd�Z�fdd�ZdS)z(_FakeUrllib2Response.info.<locals>._Metacs�jj�|g�}|SrR)r{r;rs)�zelfrir;rMr'r(�
getheaderssz3_FakeUrllib2Response.info.<locals>._Meta.getheaderscs&�jj�t|�|�}dd�|D�}|S)NcSrmr'rnror'r'r(rqrrzD_FakeUrllib2Response.info.<locals>._Meta.get_all.<locals>.<listcomp>)r{r;rsr)r}rirtr;�hrMr'r(�get_alls
�z0_FakeUrllib2Response.info.<locals>._Meta.get_allN)r0r1r2r~r�r'rMr'r(�_Metasr�r')r>r�r'rMr(�infosz_FakeUrllib2Response.infoN)r0r1r2r3r?r�r'r'r'r(ry�s	ryc@�*eZdZdZdd�Zd	dd�Zdd�ZdS)
�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
    cCr�rR)�_agent�	cookieJar)r>rXr�r'r'r(r?+r�zCookieAgent.__init__NcCs||durt�}t|�}|�d�s,|j�|�|�dd�}|dur,|��}|�dt|��|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}
        Nscookie�Cookie)
rr`r@r��add_cookie_headerrurArBrr�r�r��_extractCookies)r>rrJr;r��lastRequest�cookieHeaderr�r'r'r(r�/s

zCookieAgent.requestcCst|�}|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.
        )ryr��extract_cookies)r>r{r��respr'r'r(r�Ls	zCookieAgent._extractCookiesr])r0r1r2r3r?r�r�r'r'r'r(r�s

r�c@r�)�GzipDecoderz�
    A wrapper for a L{Response} instance which handles gzip'ed body.

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

    @since: 11.1
    cCs||_t|_dSrR)�originalrr�r|r'r'r(r?cr�zGzipDecoder.__init__cCs|j�t||j��dS)zf
        Override C{deliverBody} to wrap the given C{protocol} with
        L{_GzipProtocol}.
        N)r��deliverBody�
_GzipProtocol)r>r
r'r'r(r�gszGzipDecoder.deliverBodyN)r0r1r2r3r?r�r'r'r'r(r�Zsr�c@r�)	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
    cCs"||_||_t�dtj�|_dS)N�)r��	_response�zlib�
decompressobj�	MAX_WBITS�_zlibDecompress)r>r
r{r'r'r(r?|sz_GzipProtocol.__init__cCsJz|j�|�}Wntjytt�g|j��w|r#|j�|�dSdS)zz
        Decompress C{data} with the zlib decompressor, forwarding the raw data
        to the original protocol.
        N)	r��
decompressr�rrprr�r��dataReceived)r>�data�rawDatar'r'r(r��s��z_GzipProtocol.dataReceivedcCsRz|j��}Wntjyt|t�g|j��w|r!|j�|�|j�	|�dS)zr
        Forward the connection lost event, flushing remaining data from the
        decompressor if any.
        N)
r��flushr�rrprr�r�r��connectionLost)r>r�r�r'r'r(r��s�z_GzipProtocol.connectionLostN�r0r1r2r3r?r�r�r'r'r'r(r�os
r�c@r�)
�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 the I{Content-Encoding} header indicates a supported encoding.

    For example::

        agent = ContentDecoderAgent(Agent(reactor),
                                    [(b'gzip', GzipDecoder)])

    @param agent: The agent to wrap
    @type agent: L{IAgent}

    @param decoders: A sequence of (name, decoder) objects. The name
        declares which encoding the decoder supports. The decoder must accept
        an L{IResponse} and return an L{IResponse} when called. The order
        determines how the decoders are advertised to the server. Names must
        be unique.not be duplicated.
    @type decoders: sequence of (L{bytes}, L{callable}) tuples

    @since: 11.1

    @see: L{GzipDecoder}
    cCs*||_t|�|_d�dd�|D��|_dS)N�,cSsg|]}|d�qS)rr')r%�decoderr'r'r(rq�rrz0ContentDecoderAgent.__init__.<locals>.<listcomp>)r��dict�	_decoders�join�
_supported)r>rX�decodersr'r'r(r?�s
zContentDecoderAgent.__init__NcCsD|durt�}n|��}|�d|j�|j�||||�}|�|j�S)zv
        Send a client request which declares supporting compressed content.

        @see: L{Agent.request}.
        Nsaccept-encoding)rrArBr�r�r�r��_handleResponse�r>rrJr;r��deferredr'r'r(r��szContentDecoderAgent.requestcCs�|j�dg�}d�|��d�}|r.|����}|j�|�}|dur&||�}n|�|�n|s|r=|j�	dd�|�g�|S|j�
d�|S)zX
        Check if the response is encoded, and wrap it to handle decompression.
        scontent-encodingr�N)r;rsr��splitr�r7r�r	r!�
setRawHeaders�removeHeader)r>r{�contentEncodingHeadersrir�r'r'r(r��s"

�	��z#ContentDecoderAgent._handleResponser])r0r1r2r3r?r�r�r'r'r'r(r��s

r�)s
AuthorizationsCookiesCookie2sProxy-AuthorizationsWWW-Authenticatec@sneZdZdZejejejejgZ	ej
gZ		ddede
deefdd�Zdd
d�Zdd
�Zdd�Zdd�Zd	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'rX�
redirectLimit�sensitiveHeaderNamescCs.||_||_dd�|D�}|�t�||_dS)NcSsh|]}t|��qSr')�_canonicalHeaderName)r%�eachr'r'r(�	<setcomp>rrz)RedirectAgent.__init__.<locals>.<setcomp>)r��_redirectLimit�update�_defaultSensitiveHeaders�_sensitiveHeaderNames)r>rXr�r��	sensitiver'r'r(r?s


zRedirectAgent.__init__NcCs&|j�||||�}|�|j|||d�S)zb
        Send a client request following HTTP redirects.

        @see: L{Agent.request}.
        r)r�r�r�r�r�r'r'r(r�szRedirectAgent.requestcCs
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}.
        )rZ)r>�
requestURI�locationr'r'r(�_resolveLocation(s

zRedirectAgent._resolveLocationcs|�jkrtj�jd|d�}tt|�g����j�dg�}|s/t��jd|�}tt|�g�����	||d�}|rdt
�|�}	t
�|�}
|	j|
jkoT|	j
|
j
koT|	j|
jk}|sdt�fdd�|��D��}�j�|||�}�fdd	�}
|�|
�|��j||||d
�S)z�
        Handle a redirect response, checking the number of redirects already
        followed, and extracting the location header fields.
        sInfinite redirection detected�r�slocationsNo location header fieldrcs i|]\}}|�jvr||�qSr')r�)r%�rawName�rawValuerMr'r(�
<dictcomp>Rs

�z1RedirectAgent._handleRedirect.<locals>.<dictcomp>cs|���|SrR)�setPreviousResponse)�newResponserzr'r(�_chainResponseZs
z5RedirectAgent._handleRedirect.<locals>._chainResponserD)r�r�InfiniteRedirection�coderprr;rs�RedirectWithNoLocationr�r4rLr5r8r9r�getAllRawHeadersr�r�r�r�)r>r{rrJr;�
redirectCount�err�locationHeadersr�r7�parsedLocation�
sameOriginr�r�r')r{r>r(�_handleRedirect7s@
��


�
�
��
�zRedirectAgent._handleRedirectcCsh|j|jvr#|dvrtj|j|d�}tt|�g|��|�|||||�S|j|jvr2|�|d|||�S|S)zY
        Handle the response, making another request if it indicates a redirect.
        )r�r�r�r�)r��_redirectResponsesr�PageRedirectrprr��_seeOtherResponses)r>r{rrJr;r�r�r'r'r(r�cszRedirectAgent._handleResponse)r�r'r])r0r1r2r3r�MOVED_PERMANENTLY�FOUND�TEMPORARY_REDIRECT�PERMANENT_REDIRECTr��	SEE_OTHERr�rrGrr�r?r�r�r�r�r'r'r'r(r��s*����
�
	,r�c@s,eZdZdZejgZejejej	ej
gZdS)�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)r0r1r2r3rr�r�r�r�r�r�r�r'r'r'r(r�qs
�r�c@r�)	�_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}
    cCs||_||_||_g|_dS)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��status�message�
dataBuffer)r>r�r�r�r'r'r(r?�s
z_ReadBodyProtocol.__init__cCs|j�|�dS)z?
        Accumulate some more bytes from the response.
        N)r�r!)r>r�r'r'r(r��sz_ReadBodyProtocol.dataReceivedcCs`|�t�r|j�d�|j��dS|�t�r(|j�t|j	|j
d�|j���dS|j�|�dS)z�
        Deliver the accumulated response bytes to the waiting L{Deferred}, if
        the response body has been completely received without error.
        rON)r�ror��callbackr�r�ri�errbackr/r�r�)r>r�r'r'r(r��s

��z _ReadBodyProtocol.connectionLostNr�r'r'r'r(r��s
r�r{r�cspdtjddf�fdd�}t�|�}t|j|j|���fdd��|����jdur6��dur6tjdt	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.
    r�r�Ncs��}|dur|�dSdS)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�r()�getAbortr'r(r
�s
�zreadBody.<locals>.cancelcst�jdd�S)N�abortConnection)�getattrrr'rr'r(r��szreadBody.<locals>.getAbortzLUsing readBody with a transport that does not have an abortConnection methodr�)rPrO)
r	r�r�r��phraser�rrRrSrT)r{r
r�r')r�r
r(�readBody�s

�r�)rNr�r�r�r�r�r�r/r^r�r�rkrmrnrorprqr4rR)vr3r�r�rRr��	functoolsr�typingr�urllib.parserrrr*�zope.interfacer�incrementalrr^r	r
r�twisted.internet.abstractr�twisted.internet.endpointsr
r�twisted.internet.interfacesrr�twisted.loggerr�twisted.python.compatrr�twisted.python.componentsr�twisted.python.deprecaterr�twisted.python.failurer�twisted.webrr�twisted.web._newclientrr�twisted.web.http_headersr�twisted.web.iwebrrrr r!r"�Errorr/r4rZrgrhrirjrkrlrmrnrorprqrr�twisted.web.errorrs�OpenSSLrt�ImportError�twisted.internet.sslrurvrwr}r~r�r�r1r0r�r�r�r��Factoryr�r�r�r.rDrNr^r`ryr�r�r�r��_canonicalNameCapsr��	frozensetr�r�r��Protocolr�r�r�r��__all__r'r'r'r(�<module>s� 
r
4"
�&���@'o@EJ'EB,G�6,

Spamworldpro Mini