
    h:                       S r SSKJr  SSKrSSKrSSKrSSKrSSKJr  SSK	J
r
  SSKJr  SSKJrJrJrJr  SSKJrJrJr  SS	KJr  SS
KJr  SSKJrJrJr  SSKJ r   SSK!J"r"  SSK#J$r$J%r%  SSK&J'r'J(r(J)r)J*r*J+r+  SSK,J-r-  SSK.J/r/J0r0  SSK1J2r2  SSK3J4r4J5r5  SSK6J7r7  SSK8J9r9J:r:  SSK;J<r<J=r=  SSK>J?r?J@r@  SSKAJBrBJCrCJDrDJErEJFrFJGrG  \(       a  SSKHJIrJ  SSKKJLrM  SSKNJOrP  O\QrP\QrM\QrJS r " S S\9R                  5      rS " S S 5      rTS! rUS^S" jrVSS#K;JWrWJXrXJOrOJYrYJZrZJ[r[J\r\J]r]J^r^J_r_J`r`  SS$KaJbrb   SS%KcJdrd  SS&KeJfrfJgrgJhrh  S' rj " S( S)5      rk\" \F5       " S* S+5      5       rl\4" \" S,S-SS5      \5" \k\" S,S-SS5      \lS.9R                  S/5      S0   \kR                  \kR                  5        \" \F5       " S1 S25      5       rp\" \(5       " S3 S45      5       rq\" \F5       " S5 S65      5       rr\" \E5       " S7 S85      5       rs " S9 S:\R                  5      ru " S; S<5      rv " S= S>5      rw " S? S@5      rx\" \D5       " SA SB5      5       ry\" \C5       " SC SD\x5      5       rz\" \C5       " SE SF\x5      5       r{ " SG SH\P5      r|\ " SI SJ\J5      5       r} " SK SL\M5      r~\" \C5       " SM SN5      5       r " SO SP\2" \G5      5      r " SQ SR\2" \)5      5      r\" \C5       " SS ST5      5       r\@GR                  r\" / SUQ5      r\" \C5       " SV SW5      5       r " SX SY\5      r " SZ S[\GR                  5      rS_S\ jr/ S]Qrg! \i a    Srd GNf = f)`z
HTTP client.
    )annotationsN)	dataclass)wraps)	CookieJar)TYPE_CHECKINGHashableIterableOptional)	urldefragurljoin
urlunparse)implementer)Version)deferprotocoltask)isIPv6Address)Deferred)HostnameEndpointwrapClientTLS)IAddressIOpenSSLContextFactory	IProtocolIReactorTimeIStreamClientEndpoint)Logger)nativeStringnetworkString)proxyForInterface)deprecatedModuleAttributegetDeprecationWarningString)Failure)errorhttp)_ensureValidMethod_ensureValidURI)Headers_nameEncoder)UNKNOWN_LENGTHIAgentIAgentEndpointFactoryIBodyProducerIPolicyForHTTPS	IResponse)EmailMessage)HTTPResponse)Requestc                Z    [        [        S U  5       5      5      nUR                  S5      $ )Nc              3  B   #    U  H  oR                  S 5      v   M     g7f)charmapN)decode).0ps     Y/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/twisted/web/client.py	<genexpr>urlunparse.<locals>.<genexpr>H   s     BEqxx	22Es   r4   )_urlunparsetupleencode)partsresults     r8   r   r   G   s&    BEBBCF==##    c                      \ rS rSrSrSrg)PartialDownloadErrorL   z
Page was only partially downloaded, we got disconnected in middle.

@ivar response: All of the response body which was downloaded.
 N)__name__
__module____qualname____firstlineno____doc____static_attributes__rD   r@   r8   rB   rB   L   s    r@   rB   c                  H    \ rS rSrSrS r\S	S j5       rS r\	S 5       r
Srg)
URIT   zX
A URI object.

@see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21}
c	                    Xl         X l        UR                  S5      U l        X@l        XPl        X`l        Xpl        Xl        g)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)	selfrO   rP   rR   rS   rT   rU   rV   rW   s	            r8   __init__URI.__init__[   s7    6 JJu%			
 r@   Nc           
         UR                  5       n[        R                  " U5      u  p4pVpxUc  US;   a  SnOSnSU;   a!  UR                  SS5      u  p [	        U
5      n
OXBpU " X4XXVXx5      $ ! [
         a    XBp Nf = f)a  
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.
      wss   https  P      :   )rQ   r$   urlparsersplitint
ValueError)clsuridefaultPortrO   rP   rT   rU   rV   rW   rR   rS   s              r8   	fromBytesURI.fromBytes   s     iik8<c8J5e++! 6>tQ/JD14y  $64tUMM	  1#d1s   A- -A<;A<c                    [        U R                  U R                  U R                  U R                  U R
                  U R                  45      $ )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   rO   rP   rT   rU   rV   rW   rX   s    r8   toBytesURI.toBytes   s@     		

	
 		
r@   c                t    [        SSU R                  U R                  U R                  S45      nUS:X  a  SnU$ )z
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   rT   rU   rV   )rX   rT   s     r8   
originFormURI.originForm   s8     3TYYTZZMN3;Dr@   )rW   rR   rP   rU   rT   rS   rV   rO   N)rE   rF   rG   rH   rI   rY   classmethodrj   rn   propertyrr   rJ   rD   r@   r8   rL   rL   T   s=    "!H N NB
$  r@   rL   c                x    [        U 5      u  p[        [        X5      5      u  p[        USU=(       d    U-   5      $ )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       r8   _urljoinr}      s7    . t_NDWT/0LC3 38455r@   c                   [         R                  [        U R                  5       5      5      nU" U /UQ70 UD6nSSKJn  UR                  S:X  aK  SSKJn  Uc  UR                  5       nUR                  [        UR                  5      UR                  Xb5        U$ UR                  [        UR                  5      UR                  U5        U$ )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^   )ssl)rL   rj   r&   rQ   twisted.internetr   rO   r   ClientContextFactory
connectSSLr   rR   rS   
connectTCP)	rz   factoryFactorycontextFactoryargskwargsrh   factoryr   r   s	            r8   _makeGetterFactoryr      s     --		4
5CS24262G(
zzX(! 557N<1388WU N 	<1388WENr@   )HTTP11ClientProtocolPotentialDataLossr1   RequestGenerationFailedRequestNotSentRequestTransmissionFailedResponseResponseDoneResponseFailedResponseNeverReceived_WrapperException)SchemeNotSupported)SSL)CertificateOptionsoptionsForClientTLSplatformTrustc                :    [         c  [        U 5      S 5       nU$ U $ )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                     [        S5      e)z
pyOpenSSL is not available.

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

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

@raise NotImplementedError: Always.
zSSL support unavailable)NotImplementedError)akws     r8   raiseNotImplemented(_requireSSL.<locals>.raiseNotImplemented-  s     &&?@@r@   )r   r   )	decorateer   s     r8   _requireSSLr     s0     {	y	
	A 

	A #"r@   c                  .    \ rS rSrSrS r\S 5       rSrg)WebClientContextFactoryi>  a  
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                B    [        [        R                  [        5       S9$ )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   rX   hostnamerS   s      r8   _getCertificateOptions.WebClientContextFactory._getCertificateOptionsI  s     "):):moVVr@   c                @    U R                  X5      R                  5       $ )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      r8   r   "WebClientContextFactory.getContextV  s     **8:EEGGr@   rD   N)	rE   rF   rG   rH   rI   r   r   r   rJ   rD   r@   r8   r   r   >  s#    W 
H 
Hr@   r   c                  2    \ rS rSrSrSS jr\S 5       rSrg)BrowserLikePolicyForHTTPSid  z)
SSL connection creator for web clients.
Nc                    Xl         g rt   
_trustRoot)rX   r   s     r8   rY   "BrowserLikePolicyForHTTPS.__init__j  s    #r@   c                H    [        UR                  S5      U R                  S9$ )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   r5   r   r   s      r8   creatorForNetloc*BrowserLikePolicyForHTTPS.creatorForNetlocm  s    $ #8??7#;tWWr@   r   rt   )	rE   rF   rG   rH   rI   rY   r   r   rJ   rD   r@   r8   r   r   d  s"    $ X Xr@   r   Twisted   )replacementz; rb   c                  (    \ rS rSrSrSS jrS rSrg)HostnameCachingHTTPSPolicyi  a  
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                P    Xl         [        R                  " 5       U l        X l        g)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)rX   policyforHTTPS	cacheSizes      r8   rY   #HostnameCachingHTTPSPolicy.__init__  s      .!--/#r@   c                J   UR                  S5      n U R                  R                  U5      nX@R                  U'   [        U R                  5      U R                  :  a  U R                  R                  SS9  U$ ! [         a    U R                  R                  X5      n Nsf = f)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)	r5   r   popKeyErrorr   r   lenr   popitem)rX   r   rS   rR   creators        r8   r   +HostnameCachingHTTPSPolicy.creatorForNetloc  s    " w'	Lkkood+G $Dt{{doo-KKU+  	L**;;HKG	Ls   A: :%B"!B")r   r   r   N)   rE   rF   rG   rH   rI   rY   r   rJ   rD   r@   r8   r   r     s    *
$r@   r   c                  $    \ rS rSrSrS rS rSrg)_ContextFactoryWithContexti  z
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                    Xl         g)z
Initialize a L{_ContextFactoryWithContext} with a context.

@param context: An SSL context.
@type context: L{OpenSSL.SSL.Context}
N_context)rX   contexts     r8   rY   #_ContextFactoryWithContext.__init__  s	      r@   c                    U R                   $ )z
Return the context created by
L{_DeprecatedToCurrentPolicyForHTTPS._webContextFactory}.

@return: A context.
@rtype: L{OpenSSL.SSL.Context}
r   rm   s    r8   r   %_ContextFactoryWithContext.getContext  s     }}r@   r   N)rE   rF   rG   rH   rI   rY   r   rJ   rD   r@   r8   r   r     s     r@   r   c                  $    \ rS rSrSrS rS rSrg)"_DeprecatedToCurrentPolicyForHTTPSi  a  
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                    Xl         g)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)rX   webContextFactorys     r8   rY   +_DeprecatedToCurrentPolicyForHTTPS.__init__  s
     #4r@   c                N    U R                   R                  X5      n[        U5      $ )aK  
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   )rX   r   rS   r   s       r8   r   3_DeprecatedToCurrentPolicyForHTTPS.creatorForNetloc  s%     ))44XD)'22r@   r   Nr   rD   r@   r8   r   r     s    	43r@   r   c                  J    \ rS rSrSr\S4S jrS rS rS r	S r
S	 rS
 rSrg)FileBodyProduceri  a  
L{FileBodyProducer} produces bytes from an input file object incrementally
and writes them to a consumer.

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

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

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

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

@ivar _readSize: The number of bytes to read from C{_inputFile} at a time.
i   c                j    Xl         UR                  U l        X0l        U R	                  U5      U l        g rt   )
_inputFile	cooperate
_cooperate	_readSize_determineLengthlength)rX   	inputFile
cooperatorreadSizes       r8   rY   FileBodyProducer.__init__,  s+    #$..!++I6r@   c                     UR                   nUR                  nU" 5       nU" S[        R
                  5        U" 5       nU" U[        R                  5        XT-
  $ ! [         a	    [        s $ f = f)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)rX   fObjr   r   originalPositionends         r8   r   !FileBodyProducer._determineLength2  sg    	"99D99D  6Qfr{{+%%  	"!!	"s   A A-,A-c                    U R                   R                  5          U R                  R                  5         g! [        R
                   a     gf = f)zm
Permanently stop writing bytes from the file to the consumer by
stopping the underlying L{CooperativeTask}.
N)r   close_taskstopr   TaskFinishedrm   s    r8   stopProducingFileBodyProducer.stopProducingC  s?    
 		JJOO   		s   7 AAc                   ^  T R                  T R                  U5      5      T l        T R                  R                  5       nU 4S jnUR	                  S U5        U$ )a*  
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                   > U R                  [        R                  5      (       a  TR                  5         O'U R                  [        R
                  5      (       a  OU $ [        R                  " 5       $ rt   )checkr   CancelledErrorr  r   TaskStoppedr   )reasonrX   s    r8   maybeStopped5FileBodyProducer.startProducing.<locals>.maybeStoppedZ  sP    ||E0011""$d..// >>##r@   c                    g rt   rD   )ignoreds    r8   <lambda>1FileBodyProducer.startProducing.<locals>.<lambda>e  s    tr@   )r   
_writeloopr   whenDoneaddCallbacks)rX   consumerdr
  s   `   r8   startProducingFileBodyProducer.startProducingN  sK     __T__X%>?
JJ!		$ 	
+\:r@   c              #     #     U R                   R                  U R                  5      nU(       d  U R                   R                  5         gUR	                  U5        Sv   M^  7f)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)rX   r  bytess      r8   r  FileBodyProducer._writelooph  sN     
 OO((8E%%'NN5!J s   A A"c                8    U R                   R                  5         g)z
Temporarily suspend copying bytes from the input file to the consumer
by pausing the L{CooperativeTask} which drives that activity.
N)r   pauserm   s    r8   pauseProducingFileBodyProducer.pauseProducingu  s    
 	

r@   c                8    U R                   R                  5         g)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   resumerm   s    r8   resumeProducing FileBodyProducer.resumeProducing|  s     	

r@   )r   r   r   r   r   N)rE   rF   rG   rH   rI   r   rY   r   r  r  r  r  r"  rJ   rD   r@   r8   r   r     s1    * .2E 7&"	4r@   r   c                  2    \ rS rSrSrS rSS jrS	S jrSrg)
_HTTP11ClientFactoryi  aE  
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                    Xl         X l        g rt   )_quiescentCallback	_metadata)rX   quiescentCallbackmetadatas      r8   rY   _HTTP11ClientFactory.__init__  s    "3!r@   c                N    SR                  U R                  U R                  5      $ )Nz_HTTP11ClientFactory({}, {}))formatr'  r(  rm   s    r8   __repr___HTTP11ClientFactory.__repr__  s$    -44##T^^
 	
r@   c                ,    [        U R                  5      $ rt   )r   r'  )rX   addrs     r8   buildProtocol"_HTTP11ClientFactory.buildProtocol  s    #D$;$;<<r@   )r(  r'  N)returnstr)r1  r   r4  r   )	rE   rF   rG   rH   rI   rY   r.  r2  rJ   rD   r@   r8   r%  r%    s    
"

=r@   r%  c                  *    \ rS rSrSrS rS rS rSrg)_RetryingHTTP11ClientProtocoli  z
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                    Xl         X l        g rt   _clientProtocol_newConnection)rX   clientProtocolnewConnections      r8   rY   &_RetryingHTTP11ClientProtocol.__init__  s    -+r@   c                    US;  a  g[        U[        [        [        45      (       d  g[        U[        5      (       a9  UR
                   H)  nUR                  [        R                  5      (       d  M)    g   Ub  gg)ax  
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   HEADs   OPTIONSs   DELETEs   TRACEFT)	
isinstancer   r   r   r   reasonsr  r   r  )rX   r   	exceptionbodyProduceraFailures        r8   _shouldRetry*_RetryingHTTP11ClientProtocol._shouldRetry  su     KK68MN
 
 i!233%-->>%"6"677  . #r@   c                p   ^ ^ T R                   R                  T5      nUU 4S jnUR                  U5        U$ )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                   > TR                  TR                  U R                  TR                  5      (       a#  TR	                  5       R                  U4S j5      $ U $ )Nc                &   > U R                  T5      $ rt   )request)
connectionrL  s    r8   r  G_RetryingHTTP11ClientProtocol.request.<locals>.failed.<locals>.<lambda>  s    z'9'9''Br@   )rG  r   valuerE  r;  addCallback)r	  rL  rX   s    r8   failed5_RetryingHTTP11ClientProtocol.request.<locals>.failed  sL      w?S?STT**,88B  r@   )r:  rL  
addErrback)rX   rL  r  rQ  s   ``  r8   rL  %_RetryingHTTP11ClientProtocol.request  s3       ((1	 	
Vr@   r9  N)	rE   rF   rG   rH   rI   rY   rG  rL  rJ   rD   r@   r8   r7  r7    s    ,8r@   r7  c                  ~    \ rS rSrSr\rSrSrSr	\
" 5       rSS jr      SS jr      SS jrS	 rS
 rS rSrg)HTTPConnectionPooli  a  
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                8    Xl         X l        0 U l        0 U l        g rt   )_reactor
persistent_connections	_timeouts)rX   r   r[  s      r8   rY   HTTPConnectionPool.__init__  s    $r@   c                  ^ ^^ T R                   R                  T5      nU(       a  UR                  S5      nT R                  U   R	                  5         T R                  U	 UR
                  S:X  a:  T R                  (       a  UUU 4S jn[        XE5      n[        R                  " U5      $ U(       a  M  T R                  TT5      $ )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                 (   > TR                  TT 5      $ rt   )r;  )endpointkeyrX   s   r8   r  2HTTPConnectionPool.getConnection.<locals>.<lambda>2  s    D,?,?X,Nr@   )r\  getr   r]  cancelstateretryAutomaticallyr7  r   succeedr;  )rX   rc  rb  connectionsrM  r=  s   ```   r8   getConnection HTTPConnectionPool.getConnection  s    0 ''++C0$+JNN:&--/z*;.**$NM!>""J }}Z00 k ""311r@   c                p   ^ ^ UU 4S jnT R                  U[        U5      5      nUR                  U5      nU$ )z^
Create a new connection.

This implements the new connection code path for L{getConnection}.
c                *   > TR                  TU 5        g rt   )_putConnection)r   rc  rX   s    r8   r)  <HTTPConnectionPool._newConnection.<locals>.quiescentCallbackC  s    X.r@   )_factoryreprconnect)rX   rc  rb  r)  r   r?   s   ``    r8   r;  !HTTPConnectionPool._newConnection:  s9    	/ -- 14>B191A1A2
 r@   c                    UR                   R                  5         U R                  U   R                  U5        U R                  U	 g)z7
Remove a connection from the cache and disconnect it.
N)	transportloseConnectionr\  remover]  )rX   rc  rM  s      r8   _removeConnection$HTTPConnectionPool._removeConnectionL  s;     	++-#%%j1NN:&r@   c                F   UR                   S:w  a   [        S5      eU R
                  R                  U/ 5      n[        U5      U R                  :X  aU  UR                  S5      nUR                  R                  5         U R                  U   R                  5         U R                  U	 UR                  U5        U R                  R!                  U R"                  U R$                  X5      nXPR                  U'   g! [         a    U R                  R	                  S5         gf = f)z
Return a persistent connection to the pool. This will be called by
L{HTTP11ClientProtocol} when the connection becomes quiescent.
r`  z5BUG: Non-quiescent protocol added to connection pool.Nr   )rg  RuntimeErrorBaseException_logfailurer\  
setdefaultr   maxPersistentPerHostr   rv  rw  r]  rf  appendrZ  	callLatercachedConnectionTimeoutry  )rX   rc  rM  rj  droppedcids         r8   ro  !HTTPConnectionPool._putConnectionT  s   
 {*"K  ''223;{t888!ooa(G,,.NN7#**,w':&mm%%(($*@*@#
 &)z" ! 		!!K 	s   C8 8%D D c                b   / nU R                   R                  5        H+  nU H"  nUR                  UR                  5       5        M$     M-     0 U l         U R                  R                  5        H  nUR                  5         M     0 U l        [        R                  " U5      R                  S 5      $ )z
Close all persistent connections and remove them from the pool.

@return: L{defer.Deferred} that fires when all connections have been
    closed.
c                    g rt   rD   )igns    r8   r  ;HTTPConnectionPool.closeCachedConnections.<locals>.<lambda>  s    Dr@   )	r\  valuesr  abortr]  rf  r   gatherResultsrP  )rX   results	protocolsr7   dcs        r8   closeCachedConnections)HTTPConnectionPool.closeCachedConnectionsp  s     **113Iqwwy)  4 ..'')BIIK *""7+778HIIr@   )r\  rZ  r]  r[  N)T)rc  r   rb  r   r4  zDeferred[HTTP11ClientProtocol])rE   rF   rG   rH   rI   r%  rq  r  r  rh  r   r~  rY   rk  r;  ry  ro  r  rJ   rD   r@   r8   rV  rV    sx    $L $H!8D&2&2'<&2	'&2P'<	'$')8Jr@   rV  c                  R    \ rS rSrSrSS jrS r                S	S jrSrg)

_AgentBasei  a  
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                :    Uc  [        US5      nXl        X l        g NF)rV  rZ  _pool)rX   r   pools      r8   rY   _AgentBase.__init__  s    <%gu5D
r@   c                b    [        [        U5      5      (       a  SU-   S-   nX4S;   a  U$ SX#4-  $ )zw
Compute the string to use for the value of the I{Host} header, based on
the given scheme, host name, and port number.
   [   ])   httpr`   )r^   r_   s   %b:%d)r   r   )rX   rO   rR   rS   s       r8   _computeHostValue_AgentBase._computeHostValue  s?    
 d+,,$;%D>==K4,&&r@   c                  ^ ^^^^^ [        T[        5      (       d  [        ST< S[        T5       S35      e[	        T5      mTc
  [        5       mTR                  S5      (       dQ  TR                  5       mTR                  ST R                  TR                  TR                  TR                  5      5        T R                  R                  X5      nSUUUUUU 4S jjn	UR                  U	5      $ )zS
Issue a new request, given the endpoint and the path sent as part of
the request.
zmethod=z is z, but must be bytess   Hostc                |   > U R                  [        R                  " TTTTTR                  R                  TS95      $ )N)r[  	parsedURI)rL  r1   
_constructr  r[  )protorE  headersr   r  requestPathrX   s    r8   cbConnected4_AgentBase._requestWithEndpoint.<locals>.cbConnected  s>    =="" #zz44'	 	r@   )r  r   r4  Deferred[IResponse])rB  r  	TypeErrortyper%   r'   	hasHeadercopyaddRawHeaderr  rO   rR   rS   r  rk  rP  )
rX   rc  rb  r   r  r  rE  r  r  r  s
   `  `````  r8   _requestWithEndpoint_AgentBase._requestWithEndpoint  s     &%((gfZtDL>ATUVV#F+ ?iG  ))llnG  &&$$inninn JJ$$S3
	 
	 }}[))r@   )r  rZ  N)r   r   r  zHTTPConnectionPool | Noner4  None)rc  ztuple[bytes, bytes, int]rb  r   r   r  r  rL   r  zHeaders | NonerE  zIBodyProducer | Noner  r  r4  r  )	rE   rF   rG   rH   rI   rY   r  r  rJ   rD   r@   r8   r  r    sd    	'-*%-* (-* 	-*
 -*  -* +-* -* 
-*r@   r  c                  (    \ rS rSrSrS rSS jrSrg)_StandardEndpointFactoryi  a  
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                4    Xl         X l        X0l        X@l        g)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)rZ  r   _connectTimeout_bindAddress)rX   r   r   connectTimeoutbindAddresss        r8   rY   !_StandardEndpointFactory.__init__  s    "  --'r@   c                   0 nU R                   b  U R                   US'   U R                  US'    [        UR                  5      n[        U R                  X1R                  40 UD6nUR                  S;   a  U$ UR                  S;   a;  U R                  R                  UR                  UR                  5      n[        XT5      $ [        SUR                  < 35      e! [         a    [        SR                  US95      ef = f)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.
timeoutr  zdThe host of the provided URI ({uri.host!r}) contains non-ASCII octets, it should be ASCII decodable.rh   >      wsr  r\   zUnsupported scheme: )r  r  r   rR   UnicodeDecodeErrorrf   r-  r   rZ  rS   rO   r   r   r   r   )rX   rh   r   rR   rb  connectionCreators         r8   endpointForURI'_StandardEndpointFactory.endpointForURI  s     + $ 4 4F9 $ 1 1}		)D $DMM4LVL::))OZZ-- $ 4 4 E E#((! !!2==$';CJJ>%JKK% " 	! &S&/ 	s   C #C>)r  r  r   rZ  N)rh   rL   r4  r   )rE   rF   rG   rH   rI   rY   r  rJ   rD   r@   r8   r  r    s    (,"Lr@   r  c                  x    \ rS rSrSr\" 5       SSS4S jr\S
S j5       rS r	S r
  S         SS jjrS	rg)Agenti  a  
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                    [         R                  " U5      (       d1  [        R                  " [	        U5      S-   S[
        S9  [        U5      n[        XX45      nU R                  XU5        g)au  
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.rW  )
stacklevelcategoryN)	r-   
providedBywarningswarnrr  DeprecationWarningr   r  _init)rX   r   r   r  r  r  endpointFactorys          r8   rY   Agent.__init__%  sh    D )).99MM^$66 + @ON2^
 	

7T2r@   c                L    U R                  U 5      nUR                  XU5        U$ )aw  
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  )rg   r   r  r  agents        r8   usingEndpointFactoryAgent.usingEndpointFactoryV  s%    , C Gd3r@   c                <    [         R                  XU5        X l        g)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  rY   _endpointFactory)rX   r   r  r  s       r8   r  Agent._initp  s    ( 	D40 /r@   c                8    U R                   R                  U5      $ )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  )rX   rh   s     r8   _getEndpointAgent._getEndpoint  s     $$33C88r@   c           	     f   [        UR                  5       5      n[        R                  U5      n U R	                  U5      nUR                  UR                  UR                  4nU R                  UUUUUUUR                  5      $ ! [
         a!    [        R                  " [        5       5      s $ f = f)z
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&   rQ   rL   rj   r  r   r   failr"   rO   rR   rS   r  rr   )rX   r   rh   r  rE  r  rb  rc  s           r8   rL  Agent.request  s    " ciik*MM#&		)((3H @((  
 	
 " 	)::gi((	)s   B (B0/B0)r  rt   NN
r   r  rh   r  r  zOptional[Headers]rE  zOptional[IBodyProducer]r4  r  )rE   rF   rG   rH   rI   r   rY   ru   r  r  r  rL  rJ   rD   r@   r8   r  r    s~    
 12/3b  20.	9 &*04 
 
  
 #	 

 . 
 
 
  
r@   r  c                  ,    \ rS rSrSrSS jrSS jrSrg)
ProxyAgenti  z{
An HTTP agent able to cross HTTP proxies.

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

@since: 11.1
Nc                N    Uc  SSK Jn  [        R                  XU5        Xl        g )Nr   r   )r   r   r  rY   _proxyEndpoint)rX   rb  r   r  s       r8   rY   ProxyAgent.__init__  s     ?0D40&r@   c           	         [        UR                  5       5      nSU R                  4nU R                  UU R                  U[        R                  U5      UUU5      $ )z/
Issue a new request via the configured proxy.
z
http-proxy)r&   rQ   r  r  rL   rj   )rX   r   rh   r  rE  rc  s         r8   rL  ProxyAgent.request  s_     ciik* T001
 ((MM#
 	
r@   )r  r  )rE   rF   rG   rH   rI   rY   rL  rJ   rD   r@   r8   r  r    s    '
r@   r  c                  z    \ rS rSr% SrS\S'   S\S'   S\S'   S\S'   SS	 jrS
 rS rS r	SS jr
S rS rS rSrg)_FakeStdlibRequesti  aQ  
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
r5  rh   r  rR   r'   _twistedHeadersc                   [        U5      U l        [        5       U l        [        R                  U5      n[        UR                  5      U l        [        UR                  5      U l        UR                  UR                  4S;  a+  U =R                  S[        UR                  5      -   -  sl        [        UR                  5      U l        SU l        g)z3
Create a fake  request.

@param uri: Request URI.
r  :FN)r   rh   r'   r  rL   rj   rO   r  rR   rS   r5  origin_req_hostunverifiable)rX   rh   _uris      r8   rY   _FakeStdlibRequest.__init__  s      $&y}}S! -	 +	KK#+KKIIs499~--I+DII6!r@   c                J    U R                   R                  [        U5      5      $ rt   )r  r  r   )rX   headers     r8   
has_header_FakeStdlibRequest.has_header	  s    ##--mF.CDDr@   c                `    U R                   R                  [        U5      [        U5      5        g rt   )r  r  r   )rX   namerO  s      r8   add_unredirected_header*_FakeStdlibRequest.add_unredirected_header  s"    ))-*=}U?STr@   c                    U R                   $ rt   r  rm   s    r8   get_full_url_FakeStdlibRequest.get_full_url  s    xxr@   Nc                    U R                   R                  [        U5      U5      nUb   U Vs/ s H  n[        U5      PM     nnUS   $ g s  snf )Nr   )r  getRawHeadersr   r   )rX   r  defaultr  xs        r8   
get_header_FakeStdlibRequest.get_header  sO    &&44]45H'R0781|AG81: 9s   A
c                    U R                   $ rt   )rR   rm   s    r8   get_host_FakeStdlibRequest.get_host      yyr@   c                    U R                   $ rt   )r  rm   s    r8   get_type_FakeStdlibRequest.get_type  r  r@   c                    gr  rD   rm   s    r8   is_unverifiable"_FakeStdlibRequest.is_unverifiable  s    r@   )r  rR   r  r  r  rh   )rh   r  r4  r  rt   )rE   rF   rG   rH   rI   __annotations__rY   r  r  r  r  r  r  r	  rJ   rD   r@   r8   r  r    sH    " 
H
I
I"(EUr@   r  c                  *    \ rS rSr% S\S'   SS jrSrg)_FakeUrllibResponseInfoi$  r.   responsec                    U R                   R                  R                  [        U5      U5      nU Vs/ s H  n[	        U5      PM     nnU$ s  snf rt   )r  r  r  r   r   )rX   r  r  r  r  hs         r8   get_all_FakeUrllibResponseInfo.get_all(  sE    --''55mD6I7S&-.g\!_g. /s   ArD   N)r  r5  r  r  r4  z	list[str])rE   rF   rG   rH   r  r  rJ   rD   r@   r8   r  r  $  s    r@   r  c                  8    \ rS rSr% SrS\S'   S	S jrS
S jrSrg)_FakeStdlibResponsei.  z
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                    Xl         g rt   r  rX   r  s     r8   rY   _FakeStdlibResponse.__init__:  s     r@   c                0    [        U R                  5      nU$ rt   )r  r  )rX   r?   s     r8   info_FakeStdlibResponse.info=  s    (7r@   r  N)r  r.   r4  r  )r4  	_InfoType)	rE   rF   rG   rH   rI   r  rY   r  rJ   rD   r@   r8   r  r  .  s     !r@   r  c                  r    \ rS rSr% SrS\S'   S\S'   SS jr  S         SS	 jjr      SS
 jrSr	g)CookieAgentiB  a  
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                    Xl         X l        g rt   r  r   )rX   r  r   s      r8   rY   CookieAgent.__init__W  s    "r@   Nc                   Ub  UO	[        5       n[        U5      nUR                  S5      (       d[  U R                  R	                  U5        UR                  SS5      nUb+  UR                  5       nUR                  S[        U5      5        U R                  R                  XXT5      R                  U R                  U5      $ )aU  
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}
N   CookieCookie)r'   r  r  r   add_cookie_headerr  r  r  r   r  rL  rP  _extractCookies)rX   r   rh   r  rE  actualHeaderslastRequestcookieHeaders           r8   rL  CookieAgent.request[  s    & $+#6GI(- &&y11NN,,[9&11(DAL' - 2 2 4**9mL6QR{{""

+d**K
8	9r@   c                P    U R                   R                  [        U5      U5        U$ )z
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  )rX   r  rL  s      r8   r(  CookieAgent._extractCookies}  s#     	&&':8'DgNr@   r"  )r  r*   r   r   r4  r  r  r  )r  r.   rL  r  r4  r.   )
rE   rF   rG   rH   rI   r  rY   rL  r(  rJ   rD   r@   r8   r  r  B  st      N# &*04 9 9  9 #	 9
 . 9 
 9D!,>	r@   r  c                  $    \ rS rSrSrS rS rSrg)GzipDecoderi  z
A wrapper for a L{Response} instance which handles gzip'ed body.

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

@since: 11.1
c                &    Xl         [        U l        g rt   )originalr)   r   r  s     r8   rY   GzipDecoder.__init__  s     $r@   c                `    U R                   R                  [        XR                   5      5        g)zN
Override C{deliverBody} to wrap the given C{protocol} with
L{_GzipProtocol}.
N)r3  deliverBody_GzipProtocol)rX   r   s     r8   r6  GzipDecoder.deliverBody  s    
 	!!---"HIr@   )r   r3  N)rE   rF   rG   rH   rI   rY   r6  rJ   rD   r@   r8   r1  r1    s    %Jr@   r1  c                  *    \ rS rSrSrS rS rS rSrg)r7  i  a  
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                t    Xl         X l        [        R                  " S[        R                  -   5      U l        g )N   )r3  	_responsezlibdecompressobj	MAX_WBITS_zlibDecompress)rX   r   r  s      r8   rY   _GzipProtocol.__init__  s(     !#11"t~~2EFr@   c                     U R                   R                  U5      nU(       a  U R                  R                  U5        gg! [        R                   a     [	        [        5       /U R                  5      ef = f)zb
Decompress C{data} with the zlib decompressor, forwarding the raw data
to the original protocol.
N)	r@  
decompressr=  r#   r   r"   r<  r3  dataReceived)rX   datarawDatas      r8   rD  _GzipProtocol.dataReceived  sc    
	>**55d;G MM&&w/  zz 	> ')dnn==	>s   A 4A5c                $    U R                   R                  5       nU(       a  U R                  R                  U5        U R                  R                  U5        g! [        R                   a!    [	        U[        5       /U R                  5      ef = f)zZ
Forward the connection lost event, flushing remaining data from the
decompressor if any.
N)
r@  flushr=  r#   r   r"   r<  r3  rD  connectionLost)rX   r	  rF  s      r8   rJ  _GzipProtocol.connectionLost  st    
	F**002G MM&&w/$$V,	 zz 	F &')!4dnnEE	Fs   A 5B)r<  r@  r3  N	rE   rF   rG   rH   rI   rY   rD  rJ  rJ   rD   r@   r8   r7  r7    s    
G

0-r@   r7  c                  .    \ rS rSrSrS rSS jrS rSrg)	ContentDecoderAgenti  aE  
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                    Xl         [        U5      U l        SR                  U Vs/ s H  o3S   PM	     sn5      U l        g s  snf )N   ,r   )r  dict	_decodersjoin
_supported)rX   r  decodersdecoders       r8   rY   ContentDecoderAgent.__init__  s6    h))x$HxGQZx$HI$Hs   ANc                    Uc  [        5       nOUR                  5       nUR                  SU R                  5        U R                  R                  XX45      nUR                  U R                  5      $ )z^
Send a client request which declares supporting compressed content.

@see: L{Agent.request}.
s   Accept-Encoding)r'   r  r  rT  r  rL  rP  _handleResponserX   r   rh   r  rE  deferreds         r8   rL  ContentDecoderAgent.request  s]     ?iGllnG/A;;&&vGJ##D$8$899r@   c                   UR                   R                  S/ 5      nSR                  U5      R                  S5      nU(       a`  UR	                  5       R                  5       nU R                  R                  U5      nUb	  U" U5      nOUR                  U5        O	U(       a  M`  U(       a.  UR                   R                  SSR                  U5      /5        U$ UR                   R                  S5        U$ )zH
Check if the response is encoded, and wrap it to handle decompression.
s   Content-EncodingrP  )r  r  rS  splitr   rQ   rR  re  r  setRawHeadersremoveHeader)rX   r  contentEncodingHeadersr  rV  s        r8   rY  #ContentDecoderAgent._handleResponse  s     "*!1!1!?!?@SUW!X!%+A!B!H!H!N$)--/557Dnn((.G""8, '--d3 %$ "**#dii0F&G%H
  ))*=>r@   )r  rR  rT  r  )	rE   rF   rG   rH   rI   rY   rL  rY  rJ   rD   r@   r8   rN  rN    s    6J
:r@   rN  )s   Authorizationr%  s   Cookie2s   Proxy-Authorizations   WWW-Authenticatec                      \ rS rSrSr\R                  \R                  \R                  \R                  /r
\R                  /r  S
     SS jjrSS jrS rS rS rS	rg)RedirectAgenti!  a  
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                    Xl         X l        U Vs1 s H  n[        U5      iM     nnUR                  [        5        XPl        g s  snf rt   )r  _redirectLimit_canonicalHeaderNameupdate_defaultSensitiveHeaders_sensitiveHeaderNames)rX   r  redirectLimitsensitiveHeaderNameseach	sensitives         r8   rY   RedirectAgent.__init__E  sF     +<PQ<PD)$/<P	Q12%." Rs   ANc                v    U R                   R                  XX45      nUR                  U R                  XUS5      $ )zJ
Send a client request following HTTP redirects.

@see: L{Agent.request}.
r   )r  rL  rP  rY  rZ  s         r8   rL  RedirectAgent.requestQ  s8     ;;&&vGJ##D$8$8&wPQRRr@   c                    [        X5      $ )z
Resolve the redirect location against the request I{URI}.

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

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

@rtype: C{bytes}
@return: Final resolved I{URI}.
)r}   )rX   
requestURIlocations      r8   _resolveLocationRedirectAgent._resolveLocationZ  s     
--r@   c                  ^ XPR                   :  a6  [        R                  " TR                  SUS9n[	        [        U5      /T5      eTR                  R                  S/ 5      nU(       d8  [        R                  " TR                  SU5      n[	        [        U5      /T5      eU R                  X7S   5      nU(       a  [        R                  U5      n	[        R                  U5      n
U	R                  U
R                  :H  =(       a9    U	R                  U
R                  :H  =(       a    U	R                  U
R                  :H  nU(       d?  [        UR!                  5        VVs0 s H  u  pXR"                  ;  d  M  X_M     snn5      nU R$                  R'                  X(U5      nU4S jnUR)                  U5        UR)                  U R*                  X#XES-   5      $ s  snnf )z{
Handle a redirect response, checking the number of redirects already
followed, and extracting the location header fields.
s   Infinite redirection detectedrt  s   locations   No location header fieldr   c                *   > U R                  T5        U $ rt   )setPreviousResponse)newResponser  s    r8   _chainResponse5RedirectAgent._handleRedirect.<locals>._chainResponse  s    ++H5r@   rb   )rf  r#   InfiniteRedirectioncoder   r"   r  r  RedirectWithNoLocationru  rL   rj   rO   rR   rS   r'   getAllRawHeadersrj  r  rL  rP  rY  )rX   r  r   rh   r  redirectCounterrlocationHeadersrt  r  parsedLocation
sameOriginrawNamerawValuer[  r|  s    `              r8   _handleRedirectRedirectAgent._handleRedirecti  s   
 ///++?#C !'#,::"**88bI..:CC !'#,::((a.@Ac*I ]]84N!!^%:%:: <^^~':'::<^^~':':: 
 ! 291I1I1K1K-G"*D*DD *)1K ;;&&vA	 	^,##  &w8I
 	
s   G
8G
c                2   UR                   U R                  ;   aN  US;  a5  [        R                  " UR                   US9n[	        [        U5      /U5      eU R                  XX4U5      $ UR                   U R                  ;   a  U R                  USX4U5      $ U$ )zI
Handle the response, making another request if it indicates a redirect.
)r@  rA  rx  r@  )r  _redirectResponsesr#   PageRedirectr   r"   r  _seeOtherResponses)rX   r  r   rh   r  r  r  s          r8   rY  RedirectAgent._handleResponse  s     ==D333..((E$gcl^X>>''#VV]]d555''&#VVr@   )r  rf  rj  )r   rD   )r  r*   rk  re   rl  zIterable[bytes]r  )rE   rF   rG   rH   rI   r$   MOVED_PERMANENTLYFOUNDTEMPORARY_REDIRECTPERMANENT_REDIRECTr  	SEE_OTHERr  rY   rL  ru  r  rY  rJ   rD   r@   r8   rd  rd  !  s    6 	

	 ..)
  02	
/
/ 
/ .	
/S.*
Xr@   rd  c                      \ rS rSrSr\R                  /r\R                  \R                  \R                  \R                  /rSrg)BrowserLikeRedirectAgenti  a/  
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
rD   N)rE   rF   rG   rH   rI   r$   r  r  r  r  r  r  r  rJ   rD   r@   r8   r  r    s@     112

	r@   r  c                  *    \ rS rSrSrS rS rS rSrg)_ReadBodyProtocoli  aG  
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                6    X0l         Xl        X l        / U l        g)z
@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)rX   r  r  r[  s       r8   rY   _ReadBodyProtocol.__init__  s     !r@   c                :    U R                   R                  U5        g)z/
Accumulate some more bytes from the response.
N)r  r  )rX   rE  s     r8   rD  _ReadBodyProtocol.dataReceived  s     	t$r@   c           	        UR                  [        5      (       a5  U R                  R                  SR	                  U R
                  5      5        gUR                  [        5      (       aT  U R                  R                  [        U R                  U R                  SR	                  U R
                  5      5      5        gU R                  R                  U5        g)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[  callbackrS  r  r   errbackrB   r  r  )rX   r	  s     r8   rJ   _ReadBodyProtocol.connectionLost  s    
 <<%%MM""388DOO#<=\\+,,MM!!$KKsxx/H MM!!&)r@   )r  r[  r  r  NrL  rD   r@   r8   r  r    s     %*r@   r  c                  ^^ SU4S jjn[         R                  " U5      n[        U R                  U R                  U5      mU4S jmU R                  T5        TR                  b"  T" 5       c  [        R                  " S[        SS9  U$ )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                *   > T" 5       nUb  U" 5         gg)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}.
NrD   )r[  r  getAborts     r8   rf  readBody.<locals>.cancel  s     
G r@   c                 2   > [        T R                  SS 5      $ )NabortConnection)getattrrv  )r   s   r8   r  readBody.<locals>.getAbort  s    x))+<dCCr@   zLUsing readBody with a transport that does not have an abortConnection methodrW  )r  r  )r[  defer.Deferred[bytes]r4  r  )
r   r   r  r  phraser6  rv  r  r  r  )r  rf  r  r  r   s      @@r8   readBodyr    su    	  %~~f5A CHD "%(**<%'		
 Hr@   )r  r   r  rN  r  r1  rV  rB   r  r  rd  r   r   r   r   r   r   rL   rt   )r  r.   r4  r  )rI   
__future__r   r   r   r  r=  dataclassesr   	functoolsr   http.cookiejarr   typingr   r   r	   r
   urllib.parser   r   r   r;   zope.interfacer   incrementalr   r   r   r   r   twisted.internet.abstractr   twisted.internet.deferr   twisted.internet.endpointsr   r   twisted.internet.interfacesr   r   r   r   r   twisted.loggerr   twisted.python.compatr   r   twisted.python.componentsr   twisted.python.deprecater    r!   twisted.python.failurer"   twisted.webr#   r$   twisted.web._newclientr%   r&   twisted.web.http_headersr'   r(   twisted.web.iwebr)   r*   r+   r,   r-   r.   email.messager/   r  http.clientr0   _ResponseBaseurllib.requestr1   _RequestBaseobjectErrorrB   rL   r}   r   r   r   r   r   r   r   r   r   r   r   twisted.web.errorr   OpenSSLr   twisted.internet.sslr   r   r   ImportErrorr   r   r   r^  rF   rE   r   r   r   r   Factoryr%  r7  rV  r  r  r  r  r  r  r  r  r1  r7  rN  r=   rg  	frozensetri  rd  r  Protocolr  r  __all__rD   r@   r8   <module>r     s  
 #  	   !  $ > > F F &  2 2 3 + F  " = 7 + # F :  796LMI$
5;; o od68D    1	 >#H #HL _X X X: Ir1a 	2q!$- eDk!	
 &&$$	 _= = =@ #$  %: _$3 $3 $3N ]l l l^=8++ =4= =@`J `JFH* H*V "#FL FL $FLR VZ
J Z
 Z
z V$
 $
 $
ND DN i  - ( VF F FRJ#I. J*)-%i0 )-X VD D DN $** $  V~ ~ ~B} .3*)) 3*l)XO0  
Cs   .L: :MM