HOME


Mini Shell 1.0
DIR: /lib/python3/dist-packages/twisted/web/__pycache__/
Upload File :
Current File : //lib/python3/dist-packages/twisted/web/__pycache__/client.cpython-312.pyc
�

Ϫ�f���|�dZddlmZddlZddlZddlZddlZddlmZddl	m
Z
ddlmZddl
mZmZmZddlmZmZmZdd	lmZdd
lmZddlmZmZmZddlmZdd
l m!Z!ddl"m#Z#m$Z$ddl%m&Z&m'Z'ddl(m)Z)ddl*m+Z+m,Z,ddl-m.Z.ddl/m0Z0m1Z1ddl2m3Z3ddl4m5Z5m6Z6ddl7m8Z8m9Z9ddl:m;Z;ddl<m=Z=m>Z>m?Z?m@Z@mAZAmBZBerddlCmDZEddlFmGZHddlImJZKneLZKeLZHeLZEd�ZGd�de5j��ZNGd�d �ZOd!�ZPd^d"�ZQdd#l7mRZRmSZSmJZJmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[dd$l\m]Z]	dd%l^m_Z_dd&l`maZambZbmcZcd'�ZeGd(�d)�ZfeeA�Gd*�d+��Zge0ed,d-dd�e1efed,d-dd�eg�.�j�d/�d0efj�efj��eeA�Gd1�d2��Zkee&�Gd3�d4��ZleeA�Gd5�d6��Zmee@�Gd7�d8��ZnGd9�d:ej��ZpGd;�d<�ZqGd=�d>�ZrGd?�d@�Zsee?�GdA�dB��Ztee>�GdC�dDes��Zuee>�GdE�dFes��ZvGdG�dHeK�ZweGdI�dJeE��ZxGdK�dLeH�Zyee>�GdM�dN��ZzGdO�dPe.eB��Z{GdQ�dRe.e'��Z|ee>�GdS�dT��Z}e;�j�Ze�gdU��Z�ee>�GdV�dW��Z�GdX�dYe��Z�GdZ�d[e�j�Z�d_d\�Z�gd]�Z�y#ed$rdZ_Y��wxYw)`z
HTTP client.
�)�annotationsN)�	dataclass)�wraps)�	CookieJar)�
TYPE_CHECKING�Iterable�Optional)�	urldefrag�urljoin�
urlunparse)�implementer)�Version)�defer�protocol�task)�
isIPv6Address)�Deferred)�HostnameEndpoint�
wrapClientTLS)�IOpenSSLContextFactory�	IProtocol)�Logger)�nativeString�
networkString)�proxyForInterface)�deprecatedModuleAttribute�getDeprecationWarningString)�Failure)�error�http)�_ensureValidMethod�_ensureValidURI)�Headers)�UNKNOWN_LENGTH�IAgent�IAgentEndpointFactory�
IBodyProducer�IPolicyForHTTPS�	IResponse)�EmailMessage)�HTTPResponse)�Requestc�Z�ttd�|D���}|jd�S)Nc3�>K�|]}|jd����y�w)�charmapN)�decode)�.0�ps  �4/usr/lib/python3/dist-packages/twisted/web/client.py�	<genexpr>zurlunparse.<locals>.<genexpr>Bs����B�q�q�x�x�	�2�B�s�r/)�_urlunparse�tuple�encode)�parts�results  r3rrAs&��
��B�E�B�B�
C�F��=�=��#�#�c��eZdZdZy)�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:r3r<r<Fs��r:r<c�>�eZdZdZd�Zedd��Zd�Zed��Z	y)�URIzd
    A URI object.

    @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21}
    c	��||_||_|jd�|_||_||_||_||_||_y)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)	�selfrErFrHrIrJrKrLrMs	         r3�__init__zURI.__init__UsE��6�������J�J�u�%��	���	���	������
� ��
r:Nc
�
�|j�}tj|�\}}}}}}|�
|dk(rd}nd}d|vr"|jdd�\}	}
	t	|
�}
n||}
}	||||	|
||||�S#t
$r||}
}	Y�wxYw)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.
        �https��P�:�)rGr �urlparse�rsplit�int�
ValueError)�cls�uri�defaultPortrErFrJrKrLrMrHrIs           r3�	fromBytesz
URI.fromBytesys����i�i�k��8<�
�
�c�8J�5����f�e�X�����!�!�� ���6�>����t�Q�/�J�D�$�
1��4�y�� ��$�D��6�6�4��t�V�U�H�M�M��	�
1�#�[�d��
1�s�A2�2
B�Bc��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rErFrJrKrLrM�rNs r3�toByteszURI.toBytes�s@����������	�	�����
�
��
�
�

�	
�		
r:c�r�tdd|j|j|jdf�}|dk(rd}|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}
        r:�/)rrJrKrL)rNrJs  r3�
originFormzURI.originForm�s8���3��T�Y�Y����T�Z�Z��M�N���3�;��D��r:�N)
r=r>r?r@rO�classmethodr]r`�propertyrcrAr:r3rCrCNs=���"!�H�N��N�B
�$���r:rCc�t�t|�\}}tt||��\}}t|d|xs|z�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}
    �#)r
r)�base�url�baseFrag�urlFrags    r3�_urljoinrm�s=��.�t�_�N�D�(��W�T�3�/�0�L�C���3��� 3�8�4�5�5r:c��tjt|j���}||g|��i|��}ddlm}|jdk(rKddlm}|�|j�}|jt|j�|j||�|S|jt|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��reactorrQ)�ssl)rCr]r"rG�twisted.internetrprErq�ClientContextFactory�
connectSSLrrHrI�
connectTCP)	rj�factoryFactory�contextFactory�args�kwargsr[�factoryrprqs	         r3�_makeGetterFactoryr{�s����-�-���	�	��4�
5�C��S�2�4�2�6�2�G�(�
�z�z�X��(��!� �5�5�7�N����<����1�3�8�8�W�n�U��N�	���<����1�3�8�8�W�E��Nr:)�HTTP11ClientProtocol�PotentialDataLossr,�RequestGenerationFailed�RequestNotSent�RequestTransmissionFailed�Response�ResponseDone�ResponseFailed�ResponseNeverReceived�_WrapperException)�SchemeNotSupported)�SSL)�CertificateOptions�optionsForClientTLS�
platformTrustc�8�t�t|�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}
    c��td��)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�kws  r3�raiseNotImplementedz(_requireSSL.<locals>.raiseNotImplemented's��&�&?�@�@r:)r�r)�	decorateer�s  r3�_requireSSLr�s0���{�	�y�	�
	A�
�
	A�#�"��r:c�&�eZdZdZd�Zed��Zy)�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�H�ttjt���S)z�
        Return a L{CertificateOptions}.

        @param hostname: ignored

        @param port: ignored

        @return: A new CertificateOptions instance.
        @rtype: L{CertificateOptions}
        )�method�	trustRoot)r�r��
SSLv23_METHODr��rN�hostnamerIs   r3�_getCertificateOptionsz.WebClientContextFactory._getCertificateOptionsCs��"��):�):�m�o�V�Vr:c�B�|j||�j�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�s   r3r�z"WebClientContextFactory.getContextPs ���*�*�8�T�:�E�E�G�Gr:N)r=r>r?r@r�r�r�rAr:r3r�r�8s#���W��
H��
Hr:r�c�(�eZdZdZdd�Zed��Zy)�BrowserLikePolicyForHTTPSz1
    SSL connection creator for web clients.
    Nc��||_yrd)�
_trustRoot)rNr�s  r3rOz"BrowserLikePolicyForHTTPS.__init__ds	��#��r:c�N�t|jd�|j��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�)r�r0r�r�s   r3�creatorForNetlocz*BrowserLikePolicyForHTTPS.creatorForNetlocgs��$#�8�?�?�7�#;�t���W�Wr:rd)r=r>r?r@rOr�r�rAr:r3r�r�^s"���$��X��Xr:r��Twisted�)�replacementz; rUc��eZdZdZdd�Zd�Zy)�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
    c�R�||_tj�|_||_y)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)rN�policyforHTTPS�	cacheSizes   r3rOz#HostnameCachingHTTPSPolicy.__init__�s#�� .���!�-�-�/���#��r:c�P�|jd�}	|jj|�}||j|<t
|j�|jkDr|jjd��|S#t$r|jj||�}Y�vwxYw)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)	r0r��pop�KeyErrorr�r��lenr��popitem)rNr�rIrH�creators     r3r�z+HostnameCachingHTTPSPolicy.creatorForNetloc�s���"���w�'��	L��k�k�o�o�d�+�G�$����D���t�{�{��d�o�o�-��K�K���U��+�����	L��*�*�;�;�H�d�K�G�	L�s�A=�=%B%�$B%N)��r=r>r?r@rOr�rAr:r3r�r��s���*
$�r:r�c��eZdZdZd�Zd�Zy)�_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��||_y)z�
        Initialize a L{_ContextFactoryWithContext} with a context.

        @param context: An SSL context.
        @type context: L{OpenSSL.SSL.Context}
        N��_context)rN�contexts  r3rOz#_ContextFactoryWithContext.__init__�s�� ��
r:c��|jS)z�
        Return the context created by
        L{_DeprecatedToCurrentPolicyForHTTPS._webContextFactory}.

        @return: A context.
        @rtype: L{OpenSSL.SSL.Context}
        r�r_s r3r�z%_ContextFactoryWithContext.getContext�s���}�}�r:N)r=r>r?r@rOr�rAr:r3r�r��s��� �r:r�c��eZdZdZd�Zd�Zy)�"_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��||_y)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)rN�webContextFactorys  r3rOz+_DeprecatedToCurrentPolicyForHTTPS.__init__�s��#4��r:c�P�|jj||�}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�)rNr�rIr�s    r3r�z3_DeprecatedToCurrentPolicyForHTTPS.creatorForNetloc�s'���)�)�4�4�X�t�D��)�'�2�2r:Nr�rAr:r3r�r��s���	4�3r:r�c�@�eZdZdZedfd�Zd�Zd�Zd�Zd�Z	d�Z
d	�Zy
)�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.
    ic�n�||_|j|_||_|j	|�|_yrd)�
_inputFile�	cooperate�
_cooperate�	_readSize�_determineLength�length)rN�	inputFile�
cooperator�readSizes    r3rOzFileBodyProducer.__init__&s/��#���$�.�.���!����+�+�I�6��r:c���	|j}|j}|�}|dtj
�|�}||tj�||z
S#t$r	tcYSwxYw)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)rN�fObjr�r��originalPosition�ends      r3r�z!FileBodyProducer._determineLength,sj��	"��9�9�D��9�9�D� �6���Q������f���
�r�{�{�+��%�%�%��
�	"�!�!�	"�s�A�A-�,A-c��|jj�	|jj�y#tj
$rYywxYw)z�
        Permanently stop writing bytes from the file to the consumer by
        stopping the underlying L{CooperativeTask}.
        N)r��close�_task�stopr�TaskFinishedr_s r3�
stopProducingzFileBodyProducer.stopProducing=s?��
	
������	��J�J�O�O���� � �	��	�s�7�A
�A
c����j�j|���_�jj�}�fd�}|j	d�|�|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
        c���|jtj�r$�j�tj�S|jtj
�r	tj�S|Srd)�checkr�CancelledErrorr�r�TaskStoppedr)�reasonrNs �r3�maybeStoppedz5FileBodyProducer.startProducing.<locals>.maybeStoppedTs]����|�|�E�0�0�1��"�"�$��>�>�#�#�
���d�.�.�/��
�>�>�#�#��
r:c��yrdrA)�ignoreds r3�<lambda>z1FileBodyProducer.startProducing.<locals>.<lambda>_��r:)r��
_writeloopr��whenDone�addCallbacks)rN�consumer�dr�s`   r3�startProducingzFileBodyProducer.startProducingHsK����_�_�T�_�_�X�%>�?��
��J�J���!��		$�	
���+�\�:��r:c#�K�	|jj|j�}|s|jj�y|j	|�d���X�w)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)r��readr�r��write)rNr��bytess   r3r�zFileBodyProducer._writeloopbsO����
��O�O�(�(����8�E�����%�%�'���N�N�5�!��J�
�s�AAc�8�|jj�y)z�
        Temporarily suspend copying bytes from the input file to the consumer
        by pausing the L{CooperativeTask} which drives that activity.
        N)r��pauser_s r3�pauseProducingzFileBodyProducer.pauseProducingos��
	
�
�
���r:c�8�|jj�y)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��resumer_s r3�resumeProducingz FileBodyProducer.resumeProducingvs��	
�
�
���r:N)r=r>r?r@rrOr�r�r�r�r�r�rAr:r3r�r�s1���*.2�E�7�&�"	��4��r:r�c�$�eZdZdZd�Zdd�Zd�Zy)�_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� �||_||_yrd)�_quiescentCallback�	_metadata)rN�quiescentCallback�metadatas   r3rOz_HTTP11ClientFactory.__init__�s��"3���!��r:c�N�dj|j|j�S)Nz_HTTP11ClientFactory({}, {}))�formatrrr_s r3�__repr__z_HTTP11ClientFactory.__repr__�s$��-�4�4��#�#�T�^�^�
�	
r:c�,�t|j�Srd)r|r)rN�addrs  r3�
buildProtocolz"_HTTP11ClientFactory.buildProtocol�s��#�D�$;�$;�<�<r:N)�return�str)r=r>r?r@rOrrrAr:r3rrs��
�"�
�
=r:rc�"�eZdZdZd�Zd�Zd�Zy)�_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� �||_||_yrd)�_clientProtocol�_newConnection)rN�clientProtocol�
newConnections   r3rOz&_RetryingHTTP11ClientProtocol.__init__�s��-���+��r:c���|dvryt|tttf�syt|t�r2|j
D]#}|j
tj�s�#y|�yy)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�HEADsOPTIONSsDELETEsTRACEFT)	�
isinstancerr�r�r��reasonsr�rr�)rNr��	exception�bodyProducer�aFailures     r3�_shouldRetryz*_RetryingHTTP11ClientProtocol._shouldRetry�so���K�K����
�6�8M�N�
���i�!2�3�%�-�-�
!���>�>�%�"6�"6�7� �
!��#��r:c�n����jj��}��fd�}|j|�|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����j�j|j�j�r"�j	�j�fd��S|S)Nc�&��|j��Srd)�request)�
connectionr!s �r3r�zG_RetryingHTTP11ClientProtocol.request.<locals>.failed.<locals>.<lambda>�s���z�'9�'9�'�'B�r:)rr��valuerr�addCallback)r�r!rNs ��r3�failedz5_RetryingHTTP11ClientProtocol.request.<locals>.failed�sI���� � �������w�?S�?S�T��*�*�,�8�8�B����
r:)rr!�
addErrback)rNr!r�r%s``  r3r!z%_RetryingHTTP11ClientProtocol.request�s3���
� � �(�(��1��	�	
���V���r:N)r=r>r?r@rOrr!rAr:r3rr�s���,��8r:rc�T�eZdZdZeZdZdZdZe	�Z
dd�Zd�Zd�Z
d�Zd	�Zd
�Zy)
�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
    ���Tc�<�||_||_i|_i|_yrd)�_reactor�
persistent�_connections�	_timeouts)rNrpr-s   r3rOzHTTPConnectionPool.__init__s����
�$��������r:c�h�����jj��}|r�|jd�}�j|j	��j|=|j
dk(r4�jr���fd�}t||�}tj|�S|r���j���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�(���j���Srd)r)�endpoint�keyrNs���r3r�z2HTTPConnectionPool.getConnection.<locals>.<lambda>*s���D�,?�,?��X�,N�r:)r.�getr�r/�cancel�state�retryAutomaticallyrr�succeedr)rNr4r3�connectionsr"rs```   r3�
getConnectionz HTTPConnectionPool.getConnections����,�'�'�+�+�C�0���$����+�J��N�N�:�&�-�-�/����z�*����;�.��*�*�$N�M�!>�"�M�"�J��}�}�Z�0�0���"�"�3��1�1r:c�j�����fd�}�j|t|��}|j|�S)zv
        Create a new connection.

        This implements the new connection code path for L{getConnection}.
        c�*���j�|�yrd)�_putConnection)rr4rNs ��r3rz<HTTPConnectionPool._newConnection.<locals>.quiescentCallback9s�������X�.r:)�_factory�repr�connect)rNr4r3rrzs``   r3rz!HTTPConnectionPool._newConnection2s0���	/��-�-� 1�4��>�B������(�(r:c��|jj�|j|j|�|j|=y)zG
        Remove a connection from the cache and disconnect it.
        N)�	transport�loseConnectionr.�remover/)rNr4r"s   r3�_removeConnectionz$HTTPConnectionPool._removeConnection?s;��	���+�+�-����#��%�%�j�1��N�N�:�&r:c�D�|jdk7r	td��|j
j
|g�}t|�|jk(rU|jd�}|jj�|j|j�|j|=|j|�|jj!|j"|j$||�}||j|<y#t$r|jj	d�YywxYw)z�
        Return a persistent connection to the pool. This will be called by
        L{HTTP11ClientProtocol} when the connection becomes quiescent.
        r1z5BUG: Non-quiescent protocol added to connection pool.Nr)r7�RuntimeError�
BaseException�_log�failurer.�
setdefaultr��maxPersistentPerHostr�rCrDr/r6�appendr,�	callLater�cachedConnectionTimeoutrF)rNr4r"r:�dropped�cids      r3r>z!HTTPConnectionPool._putConnectionGs��
���{�*�
�"�K����'�'�2�2�3��;���{��t�8�8�8�!�o�o�a�(�G����,�,�.��N�N�7�#�*�*�,����w�'����:�&��m�m�%�%��(�(�$�*@�*@�#�z�
��&)����z�"��!�
��	�	�!�!�K��
�	
�s�C8�8$D�Dc�T�g}|jj�D](}|D]!}|j|j���#�*i|_|jj�D]}|j��i|_t
j|�jd��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��yrdrA)�igns r3r�z;HTTPConnectionPool.closeCachedConnections.<locals>.<lambda>rr�r:)	r.�valuesrN�abortr/r6r�
gatherResultsr$)rN�results�	protocolsr2�dcs     r3�closeCachedConnectionsz)HTTPConnectionPool.closeCachedConnectionscs������*�*�1�1�3�	*�I��
*�����q�w�w�y�)�
*�	*�����.�.�'�'�)�	�B��I�I�K�	�����"�"�7�+�7�7�8H�I�Ir:N)T)r=r>r?r@rr?rMrPr8rrJrOr;rrFr>r\rAr:r3r(r(�sH��$�L$�H���!�����8�D��$2�L)�'�)�8Jr:r(c�"�eZdZdZd�Zd�Zd�Zy)�
_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�<�|�t|d�}||_||_y�NF)r(r,�_pool)rNrp�pools   r3rOz_AgentBase.__init__s!���<�%�g�u�5�D���
���
r:c�X�tt|��rd|zdz}||fdvr|Sd||fzS)z�
        Compute the string to use for the value of the I{Host} header, based on
        the given scheme, host name, and port number.
        �[�]�)�httprS)rQrRs%b:%d)rr)rNrErHrIs    r3�_computeHostValuez_AgentBase._computeHostValue�s@��
��d�+�,��$�;��%�D��D�>�=�=��K��4��,�&�&r:c���������t�t�std��dt���d���t	�����
t���j
d�sQ�j���jd�j�j�j�j���jj||�}������fd�}	|j|	�|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 bytesshostc
���|jtj�����jj����S)N)r-�	parsedURI)r!r,�
_constructrar-)�protor�headersr�rk�requestPathrNs ������r3�cbConnectedz4_AgentBase._requestWithEndpoint.<locals>.cbConnected�s>����=�=��"�"���� �#�z�z�4�4�'�
�	�	
r:)rr��	TypeError�typer!r#�	hasHeader�copy�addRawHeaderrhrErHrIrar;r$)
rNr4r3r�rkrnrror�rps
`  `````  r3�_requestWithEndpointz_AgentBase._requestWithEndpoint�s�����&�%�(��g�f�Z�t�D��L�>�AT�U�V�V�#�F�+���?��i�G�� � ��)��l�l�n�G�� � ���&�&��$�$�i�n�n�i�n�n��
�
�J�J�$�$�S�(�3��
	�
	�	
�
�
�k�"��r:N)r=r>r?r@rOrhrvrAr:r3r^r^us����	'�'r:r^c��eZdZdZd�Zd�Zy)�_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�<�||_||_||_||_y)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)r,r��_connectTimeout�_bindAddress)rNrprw�connectTimeout�bindAddresss     r3rOz!_StandardEndpointFactory.__init__�s#��" ��
�-���-���'��r:c��i}|j�|j|d<|j|d<	t|j�}t|j||jfi|��}|jdk(r|S|jdk(r<|jj|j|j�}t||�Std|j����#t$rtdj
|����wxYw)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}
        �timeoutr}zdThe host of the provided URI ({uri.host!r}) contains non-ASCII octets, it should be ASCII decodable.�r[rgrQzUnsupported scheme: )rzr{rrH�UnicodeDecodeErrorrYrrr,rIrEr�r�rr�)rNr[ryrHr3�connectionCreators      r3�endpointForURIz'_StandardEndpointFactory.endpointForURI�s��������+� $� 4� 4�F�9�� $� 1� 1��}��		�����)�D�$�D�M�M�4����L�V�L���:�:�� ��O�
�Z�Z�8�
#� $� 4� 4� E� E����#�(�(�!��!�!2�H�=�=�$�';�C�J�J�>�%J�K�K��%"�	��!��&�S�&�/��
�	�s�C�%C>N)r=r>r?r@rOr�rAr:r3rxrx�s���(�,#Lr:rxc�P�eZdZdZe�dddfd�Zedd��Zd�Zd�Z	d	d�Z
y)
�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���tj|�s3tjt	|�dzdt
��t
|�}t||||�}|j|||�y)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�rx�_init)rNrprwr|r}rb�endpointFactorys       r3rOzAgent.__init__sk��D�)�)�.�9��M�M��^�$�6�6��+�

�@��O�N�2��^�^�[�
��	
�
�
�7�O�T�2r:c�N�|j|�}|j|||�|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�)rZrpr�rb�agents     r3�usingEndpointFactoryzAgent.usingEndpointFactoryDs'��,���C� ��
���G�_�d�3��r:c�@�tj|||�||_y)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^rO�_endpointFactory)rNrpr�rbs    r3r�zAgent._init^s��(	���D�'�4�0� /��r:c�8�|jj|�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�)rNr[s  r3�_getEndpointzAgent._getEndpointus���$�$�3�3�C�8�8r:c	�b�t|j��}tj|�}	|j	|�}|j|j|jf}|j|||||||j�S#t
$r t
jt��cYSwxYw)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}
        )r"rGrCr]r�r�r�failrrErHrIrvrc)rNr�r[rnrrkr3r4s        r3r!z
Agent.request�s����c�i�i�k�*���M�M�#�&�	�	)��(�(��3�H����������@���(�(�������� � �
�	
��"�	)��:�:�g�i�(�(�	)�s�B�&B.�-B.rd�NN)r=r>r?r@r�rOrer�r�r�r!rAr:r3r�r�sA��
�1�2���
�
/3�b����20�.	9�
r:r�c� �eZdZdZdd�Zdd�Zy)�
ProxyAgentz�
    An HTTP agent able to cross HTTP proxies.

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

    @since: 11.1
    Nc�P�|�ddlm}tj|||�||_y)Nrro)rrrpr^rO�_proxyEndpoint)rNr3rprbs    r3rOzProxyAgent.__init__�s$���?�0����D�'�4�0�&��r:c	��t|j��}d|jf}|j||j|tj|�|||�S)z?
        Issue a new request via the configured proxy.
        z
http-proxy)r"rGr�rvrCr])rNr�r[rnrr4s      r3r!zProxyAgent.request�s_���c�i�i�k�*���T�0�0�1��
�(�(�������M�M�#�����
�	
r:r�)r=r>r?r@rOr!rAr:r3r�r��s���'�
r:r�c�n�eZdZUdZded<ded<ded<ded<dd�Zd	�Zd
�Zd�Zdd
�Z	d�Z
d�Zd�Zy)�_FakeStdlibRequestau
    A fake L{urllib.request.Request} object for L{cookiejar} to work with.

    @see: U{urllib.request.Request
        <https://docs.python.org/3/library/urllib.request.html#urllib.request.Request>}

    @ivar uri: Request URI.

    @ivar headers: Request headers.

    @ivar type: The scheme of the URI.

    @ivar host: The host[:port] of the URI.

    @since: 11.1
    r
r[rrrHr#�_twistedHeadersc��t|�|_t�|_tj|�}t|j�|_t|j�|_|j|jfdvr+|xjdt|j�zz
c_t|j�|_d|_y)zK
        Create a fake  request.

        @param uri: Request URI.
        rf�:FN)
rr[r#r�rCr]rErrrHrIr
�origin_req_host�unverifiable)rNr[�_uris   r3rOz_FakeStdlibRequest.__init__�s��� ��$���&�y����}�}�S�!�� ����-��	� ����+��	��K�K����#�+K�K��I�I��s�4�9�9�~�-�-�I�+�D�I�I�6���!��r:c�J�|jjt|��Srd)r�rsr)rN�headers  r3�
has_headerz_FakeStdlibRequest.has_header�s���#�#�-�-�m�F�.C�D�Dr:c�`�|jjt|�t|��yrd)r�rur)rN�namer#s   r3�add_unredirected_headerz*_FakeStdlibRequest.add_unredirected_header�s"�����)�)�-��*=�}�U�?S�Tr:c��|jSrdr�r_s r3�get_full_urlz_FakeStdlibRequest.get_full_url�s���x�x�r:Nc��|jjt|�|�}|�|D�cgc]
}t|���}}|dSycc}w)Nr)r��
getRawHeadersrr)rNr��defaultrn�xs     r3�
get_headerz_FakeStdlibRequest.get_header�sN���&�&�4�4�]�4�5H�'�R����07�8�1�|�A��8�G�8��1�:����9s�Ac��|jSrd)rHr_s r3�get_hostz_FakeStdlibRequest.get_host����y�y�r:c��|jSrd)rrr_s r3�get_typez_FakeStdlibRequest.get_typer�r:c��yr`rAr_s r3�is_unverifiablez"_FakeStdlibRequest.is_unverifiables��r:)r[r�r�Nonerd)
r=r>r?r@�__annotations__rOr�r�r�r�r�r�r�rAr:r3r�r��sH���"

�H�

�I�

�I���"�(E�U�����r:r�c� �eZdZUded<dd�Zy)�_FakeUrllibResponseInfor)�responsec��|jjjt|�|�}|D�cgc]
}t	|���}}|Scc}wrd)r�rnr�rr)rNr�r�rnr��hs      r3�get_allz_FakeUrllibResponseInfo.get_allsD���-�-�'�'�5�5�m�D�6I�7�S��&-�.��\�!�_�.��.����
/s�A
N)r�r
r�r�rz	list[str])r=r>r?r�r�rAr:r3r�r�s
����r:r�c�,�eZdZUdZded<dd�Zdd�Zy)	�_FakeStdlibResponsez�
    A fake L{urllib.response.Response} object for L{http.cookiejar} to work
    with.

    @ivar response: Underlying Twisted Web response.

    @since: 11.1
    r)r�c��||_yrd)r��rNr�s  r3rOz_FakeStdlibResponse.__init__"s	�� ��
r:c�0�t|j�}|Srd)r�r�)rNr9s  r3�infoz_FakeStdlibResponse.info%s��(����7���
r:N)r�r)rr�)r�	_InfoType)r=r>r?r@r�rOr�rAr:r3r�r�s�����!�r:r�c�b�eZdZUdZded<ded<d
d�Z		d									dd�Z						d
d	�Zy)�CookieAgenta
    L{CookieAgent} extends the basic L{Agent} to add RFC-compliant handling of
    HTTP cookies.  Cookies are written to and extracted from a L{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.

    @ivar _agent: Underlying Twisted Web agent to issue requests through.

    @ivar cookieJar: Initialized cookie jar to read cookies from and store
        cookies to.

    @since: 11.1
    r%�_agentr�	cookieJarc� �||_||_yrd)r�r�)rNr�r�s   r3rOzCookieAgent.__init__?s�����"��r:Nc�z�|�|n	t�}t|�}|jd�sZ|jj	|�|jdd�}|�+|j
�}|jdt|��|jj||||�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)
r#r�rsr��add_cookie_headerr�rtrurr�r!r$�_extractCookies)rNr�r[rnr�
actualHeaders�lastRequest�cookieHeaders        r3r!zCookieAgent.requestCs���&$+�#6��G�I�
�(��-���&�&�y�1��N�N�,�,�[�9�&�1�1�(�D�A�L��'� -� 2� 2� 4�
��*�*�9�m�L�6Q�R��{�{�"�"��C���
�
�+�d�*�*�K�
8�	9r:c�P�|jjt|�|�|S)a
        Extract response cookies and store them in the cookie jar.

        @param response: the Twisted Web response that we are processing.

        @param request: A L{_FakeStdlibRequest} wrapping our Twisted request,
            for L{CookieJar} to extract cookies from.
        )r��extract_cookiesr�)rNr�r!s   r3r�zCookieAgent._extractCookieses#��	
���&�&�':�8�'D�g�N��r:)r�r%r�rrr�r�)
r�r�r[r�rnzOptional[Headers]rzOptional[IBodyProducer]rzDeferred[IResponse])r�r)r!r�rr))r=r>r?r@r�rOr!r�rAr:r3r�r�*st��� 
�N���#�&*�04� 9�� 9�� 9�#�	 9�
.� 9�
�
 9�D�!��,>��	�r:r�c��eZdZdZd�Zd�Zy)�GzipDecoderz�
    A wrapper for a L{Response} instance which handles gzip'ed body.

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

    @since: 11.1
    c�(�||_t|_yrd)�originalr$r�r�s  r3rOzGzipDecoder.__init__}s�� ��
�$��r:c�b�|jjt||j��y)zf
        Override C{deliverBody} to wrap the given C{protocol} with
        L{_GzipProtocol}.
        N)r��deliverBody�
_GzipProtocol)rNrs  r3r�zGzipDecoder.deliverBody�s!��
	
�
�
�!�!�-��$�-�-�"H�Ir:N)r=r>r?r@rOr�rAr:r3r�r�ts���%�Jr:r�c�"�eZdZdZd�Zd�Zd�Zy)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�v�||_||_tjdtjz�|_y)N�)r��	_response�zlib�
decompressobj�	MAX_WBITS�_zlibDecompress)rNrr�s   r3rOz_GzipProtocol.__init__�s,�� ��
�!���#�1�1�"�t�~�~�2E�F��r:c���	|jj|�}|r|jj|�yy#tj$r t	t�g|j��wxYw)zz
        Decompress C{data} with the zlib decompressor, forwarding the raw data
        to the original protocol.
        N)	r��
decompressr�rr�rr�r��dataReceived)rN�data�rawDatas   r3r�z_GzipProtocol.dataReceived�sc��
	>��*�*�5�5�d�;�G���M�M�&�&�w�/����z�z�	>� �'�)��d�n�n�=�=�	>�s	�<�3A/c��	|jj�}|r|jj|�|jj|�y#tj$r!t	|t�g|j��wxYw)zr
        Forward the connection lost event, flushing remaining data from the
        decompressor if any.
        N)
r��flushr�rr�rr�r�r��connectionLost)rNr�r�s   r3r�z_GzipProtocol.connectionLost�st��
	F��*�*�0�0�2�G���M�M�&�&�w�/��
�
�$�$�V�,��	�z�z�	F� �&�'�)�!4�d�n�n�E�E�	F�s�A�4B	N�r=r>r?r@rOr�r�rAr:r3r�r��s��
�G�

0�-r:r�c�$�eZdZdZd�Zdd�Zd�Zy)�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}
    c��||_t|�|_dj|D�cgc]}|d��	c}�|_ycc}w)N�,r)r��dict�	_decoders�join�
_supported)rNr��decoders�decoders    r3rOzContentDecoderAgent.__init__�s6������h�����)�)�x�$H�G�W�Q�Z�$H�I����$Hs�ANc���|�t�}n|j�}|jd|j�|jj||||�}|j
|j�S)zv
        Send a client request which declares supporting compressed content.

        @see: L{Agent.request}.
        saccept-encoding)r#rtrur�r�r!r$�_handleResponse�rNr�r[rnr�deferreds      r3r!zContentDecoderAgent.request�sa���?��i�G��l�l�n�G����/����A��;�;�&�&�v�s�G�\�J���#�#�D�$8�$8�9�9r:c���|jjdg�}dj|�jd�}|rY|j	�j�}|jj|�}|�	||�}n|j|�n|r�Y|r.|jjddj|�g�|S|jjd�|S)zX
        Check if the response is encoded, and wrap it to handle decompression.
        scontent-encodingr�)rnr�r��splitr�rGr�r5rN�
setRawHeaders�removeHeader)rNr��contentEncodingHeadersr�r�s     r3r�z#ContentDecoderAgent._handleResponse�s���"*�!1�!1�!?�!?�@S�UW�!X��!%���+A�!B�!H�!H��!N��$�)�-�-�/�5�5�7�D��n�n�(�(��.�G��"�"�8�,��'�-�-�d�3��%�"����*�*�#�d�i�i�0F�&G�%H�
�
��
���)�)�*=�>��r:r�)r=r>r?r@rOr!r�rAr:r3r�r��s���6J�
:�r:r�)s
AuthorizationsCookiesCookie2sProxy-AuthorizationsWWW-Authenticatec��eZdZdZej
ejejejgZ	ejgZ		d					d	d�Zd
d�Z
d�Zd�Zd�Zy)�
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
    c��||_||_|D�chc]
}t|���}}|jt�||_ycc}wrd)r��_redirectLimit�_canonicalHeaderName�update�_defaultSensitiveHeaders�_sensitiveHeaderNames)rNr��
redirectLimit�sensitiveHeaderNames�each�	sensitives      r3rOzRedirectAgent.__init__-sI�����+���<P�Q�D�)�$�/�Q�	�Q����1�2�%.��"��Rs�ANc�|�|jj||||�}|j|j|||d�S)zb
        Send a client request following HTTP redirects.

        @see: L{Agent.request}.
        r)r�r!r$r�r�s      r3r!zRedirectAgent.request9s>���;�;�&�&�v�s�G�\�J���#�#�D�$8�$8�&�#�w�PQ�R�Rr:c��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}.
        )rm)rN�
requestURI�locations   r3�_resolveLocationzRedirectAgent._resolveLocationBs���
�H�-�-r:c���||jk\r8tj�jd|��}t	t|�g����jjdg�}|s7tj�jd|�}t	t|�g���|j||d�}|r�tj|�}	tj|�}
|	j|
jk(xr4|	j|
jk(xr|	j|
jk(}|s;t|j!�D��
cic]\}}
||j"vr||
��c}
}�}|j$j'|||�}�fd�}|j)|�|j)|j*||||dz�Scc}
}w)z�
        Handle a redirect response, checking the number of redirects already
        followed, and extracting the location header fields.
        sInfinite redirection detected�rslocationsNo location header fieldrc�*��|j��|Srd)�setPreviousResponse)�newResponser�s �r3�_chainResponsez5RedirectAgent._handleRedirect.<locals>._chainResponsets����+�+�H�5��r:rU)rr�InfiniteRedirection�coder�rrnr��RedirectWithNoLocationrrCr]rErHrIr#�getAllRawHeadersr
r�r!r$r�)rNr�r�r[rn�
redirectCount�err�locationHeadersrrk�parsedLocation�
sameOrigin�rawName�rawValuer�rs `              r3�_handleRedirectzRedirectAgent._handleRedirectQs����
�D�/�/�/��+�+��
�
�?�#��C�!�'�#�,���:�:�"�*�*�8�8��b�I����.�.��
�
�:�C��C�!�'�#�,���:�:��(�(��o�a�.@�A����
�
�c�*�I� �]�]�8�4�N��!�!�^�%:�%:�:�<��^�^�~�':�':�:�<��^�^�~�':�':�:�
�
�!�29�1I�1I�1K��-�G�X�"�$�*D�*D�D� ��)�����;�;�&�&�v�x��A��	�	���^�,��#�#�� � �&�#�w�
��8I�
�	
��s�G
c�0�|j|jvrP|dvr7tj|j|��}t	t|�g|��|j
|||||�S|j|jvr|j
|d|||�S|S)zY
        Handle the response, making another request if it indicates a redirect.
        )rrrr)r�_redirectResponsesr�PageRedirectr�rr%�_seeOtherResponses)rNr�r�r[rnrrs       r3r�zRedirectAgent._handleResponse}s����=�=�D�3�3�3��.�.��(�(�����E��$�g�c�l�^�X�>�>��'�'��&�#�w�
�V�V�
�]�]�d�5�5�
5��'�'��&�#�w�
�V�V��r:)r�rA)r�r%rrXrzIterable[bytes]r�)r=r>r?r@r �MOVED_PERMANENTLY�FOUND�TEMPORARY_REDIRECT�PERMANENT_REDIRECTr'�	SEE_OTHERr)rOr!rr%r�rAr:r3rr	s����6	
����
�
�������	���.�.�)��
 �02�	
/��
/��
/�.�	
/�S�
.�*
�Xr:rc��eZdZdZej
gZejejejejgZy)�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)r=r>r?r@r r,r'r*r+r.r-r)rAr:r3r0r0�s@����1�1�2������
�
�������	�r:r0c�"�eZdZdZd�Zd�Zd�Zy)�_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�<�||_||_||_g|_y)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)rNr4r5r�s    r3rOz_ReadBodyProtocol.__init__�s ��!��
���������r:c�:�|jj|�y)z?
        Accumulate some more bytes from the response.
        N)r6rN)rNr�s  r3r�z_ReadBodyProtocol.dataReceived�s��	
�����t�$r:c	��|jt�r5|jjdj	|j
��y|jt�rT|jjt|j|jdj	|j
���y|jj|�y)z�
        Deliver the accumulated response bytes to the waiting L{Deferred}, if
        the response body has been completely received without error.
        r:N)r�r�r��callbackr�r6r}�errbackr<r4r5)rNr�s  r3r�z _ReadBodyProtocol.connectionLost�s���
�<�<��%��M�M�"�"�3�8�8�D�O�O�#<�=�
�\�\�+�
,��M�M�!�!�$��K�K����s�x�x����/H��
�
�M�M�!�!�&�)r:Nr�rAr:r3r2r2�s���� %�*r:r2c����d�fd�}tj|�}t|j|j|���fd��|j���j�#���tjdtd��|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�(����}|�|�yy)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}.
        NrA)r�rW�getAborts  �r3r6zreadBody.<locals>.cancel�s����
�����G�r:c�2��t�jdd�S)N�abortConnection)�getattrrC)rs�r3r=zreadBody.<locals>.getAbort�s����x�)�)�+<�d�C�Cr:zLUsing readBody with a transport that does not have an abortConnection methodr))r�r�)r��defer.Deferred[bytes]rr�)
rrr2r�phraser�rCr�r�r�)r�r6r�r=rs   @@r3�readBodyrC�su���	� %�~�~�f�5�A� ��������C�H�D�
����"����%�(�*�*<��
�
�
%�'��		
�
�Hr:)r�r�r0r�r�r�r(r<r�rCrr~r�r�r�r�r�rCrd)r�r)rrA)�r@�
__future__rr�r�r�r��dataclassesr�	functoolsr�http.cookiejarr�typingrrr	�urllib.parser
rrr5�zope.interfacer
�incrementalrrrrrr�twisted.internet.abstractr�twisted.internet.deferr�twisted.internet.endpointsrr�twisted.internet.interfacesrr�twisted.loggerr�twisted.python.compatrr�twisted.python.componentsr�twisted.python.deprecaterr�twisted.python.failurer�twisted.webrr �twisted.web._newclientr!r"�twisted.web.http_headersr#�twisted.web.iwebr$r%r&r'r(r)�
email.messager*r��http.clientr+�
_ResponseBase�urllib.requestr,�_RequestBase�object�Errorr<rCrmr{r|r}r~rr�r�r�r�r�r��twisted.web.errorr��OpenSSLr��twisted.internet.sslr�r�r��ImportErrorr�r�r�r�r>r=r�r�r�r��Factoryrrr(r^rxr�r�r�r�r�r�r�r�r��_canonicalNameCapsr�	frozensetr	rr0�Protocolr2rC�__all__rAr:r3�<module>ris���
�#��	���!��$�4�4�F�F�&��2�2�3�+�F�I�!�=�7��+�#�F�,����7�9�6��L��M��I�$�
�5�;�;��o�o�d6�8�D����1�	�����>#H�#H�L
�_��X�X��X�:��I�r�1�a� ����	�2�q�!�$�-���e�D�k�!�	�
�&�&��$�$�	�
�_��=�=��=�@
�
#�$���%��:
�_��$3�$3��$3�N
�]��l�l��l�^=�8�+�+�=�4=�=�@YJ�YJ�xB�B�J
�
"�#�GL�GL�$�GL�T
�V��T
�J�T
��T
�n
�V��$
��$
��$
�ND��D�N��i�����-��(
�V��F�F��F�RJ�#�I�.�J�*)-�%�i�0�)-�X
�V��D�D��D�N�y�3�3��$����
�V��~�~��~�B�}��.3*��)�)�3*�l)
�X���k/��
�C��s�L0�0L;�:L;