Ϫf |dZddlmZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZmZmZddlmZmZmZdd lmZdd lmZdd lmZmZmZdd 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;ddlZ>m?Z?m@Z@mAZAmBZBerddlCmDZEddlFmGZHddlImJZKneLZKeLZHeLZEdZGdde5jZNGdd ZOd!ZPd^d"ZQdd#l7mRZRmSZSmJZJmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[dd$l\m]Z] dd%l^m_Z_dd&l`maZambZbmcZcd'ZeGd(d)ZfeeAGd*d+Zge0ed,d-dde1efed,d-ddeg.jd/d0efjefjeeAGd1d2Zkee&Gd3d4ZleeAGd5d6Zmee@Gd7d8ZnGd9d:ejZpGd;d<ZqGd=d>ZrGd?d@Zsee?GdAdBZtee>GdCdDesZuee>GdEdFesZvGdGdHeKZweGdIdJeEZxGdKdLeHZyee>GdMdNZzGdOdPe.eBZ{GdQdRe.e'Z|ee>GdSdTZ}e;jZegdUZee>GdVdWZGdXdYeZGdZd[ejZd_d\Zgd]Zy#ed$rdZ_Y wxYw)`z HTTP client. ) annotationsN) dataclass)wraps) CookieJar) TYPE_CHECKINGIterableOptional) urldefragurljoin urlunparse) implementer)Version)deferprotocoltask) isIPv6Address)Deferred)HostnameEndpoint wrapClientTLS)IOpenSSLContextFactory IProtocol)Logger) nativeString networkString)proxyForInterface)deprecatedModuleAttributegetDeprecationWarningString)Failure)errorhttp)_ensureValidMethod_ensureValidURI)Headers)UNKNOWN_LENGTHIAgentIAgentEndpointFactory IBodyProducerIPolicyForHTTPS IResponse) EmailMessage) HTTPResponse)RequestcZttd|D}|jdS)Nc3>K|]}|jdyw)charmapN)decode).0ps 4/usr/lib/python3/dist-packages/twisted/web/client.py zurlunparse..BsBqqxx 2Bsr/) _urlunparsetupleencode)partsresults r3r r As& BEBB CF == ##ceZdZdZy)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<Fsr:r<c>eZdZdZdZeddZdZedZ 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) schemenetlocstriphostportpathparamsqueryfragment) selfrErFrHrIrJrKrLrMs r3__init__z URI.__init__UsE6  JJu%       r:Nc  |j}tj|\}}}}}}| |dk(rd}nd}d|vr"|jdd\} } t | } n||} } |||| | ||||S#t $r||} } YwxYw)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. httpsP:)rGr urlparsersplitint ValueError) clsuri defaultPortrErFrJrKrLrMrHrIs r3 fromBytesz URI.fromBytesysiik8< c8J5feX  !!  6>tQ/JD$ 14y $D664tVUHMM  1#[d 1s A22 BBct|j|j|j|j|j |j fS)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 rErFrJrKrLrMrNs r3toBytesz URI.toBytess@         r:crtdd|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.originForms83TYY TZZMN 3;D r:N) r=r>r?r@rO classmethodr]r`propertyrcrAr:r3rCrCNs= "!HNNB $r:rCctt|\}}tt||\}}t|d|xs|zS)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 )baseurlbaseFragurlFrags r3_urljoinrms=.t_ND(WT3/0LC 3 384 55r:ctjt|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} rreactorrQ)ssl)rCr]r"rGtwisted.internetrprErqClientContextFactory connectSSLrrHrI connectTCP) rjfactoryFactorycontextFactoryargskwargsr[factoryrprqs r3_makeGetterFactoryr{s -- 4 5CS24262G( zzX(  ! 557N<1388WnU N <1388WE Nr:) HTTP11ClientProtocolPotentialDataLossr,RequestGenerationFailedRequestNotSentRequestTransmissionFailedResponse ResponseDoneResponseFailedResponseNeverReceived_WrapperException)SchemeNotSupported)SSL)CertificateOptionsoptionsForClientTLS platformTrustc8tt|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} ctd)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)akws r3raiseNotImplementedz(_requireSSL..raiseNotImplemented's&&?@ @r:)rr) decorateers r3 _requireSSLrs0 { y  A  A#" r:c&eZdZdZdZedZy)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. cHttjtS)z Return a L{CertificateOptions}. @param hostname: ignored @param port: ignored @return: A new CertificateOptions instance. @rtype: L{CertificateOptions} )method trustRoot)rr SSLv23_METHODrrNhostnamerIs r3_getCertificateOptionsz.WebClientContextFactory._getCertificateOptionsCs"):):moVVr:cB|j||jS)z Return an L{OpenSSL.SSL.Context}. @param hostname: ignored @param port: ignored @return: A new SSL context. @rtype: L{OpenSSL.SSL.Context} )r getContextrs r3rz"WebClientContextFactory.getContextPs **8T:EEGGr:N)r=r>r?r@rrrrAr:r3rr8s# W H Hr:rc(eZdZdZddZedZy)BrowserLikePolicyForHTTPSz1 SSL connection creator for web clients. Nc||_yrd) _trustRoot)rNrs r3rOz"BrowserLikePolicyForHTTPS.__init__ds #r:cNt|jd|jS)a  Create a L{client connection creator } 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 } ascii)r)rr0rrs r3creatorForNetlocz*BrowserLikePolicyForHTTPS.creatorForNetlocgs$#8??7#;tWWr:rd)r=r>r?r@rOrrrAr:r3rr^s"$XXr:rTwisted) replacementz; rUceZdZdZddZdZy)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 } 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 }. @type _cache: L{collections.OrderedDict} @ivar _cacheSize: See C{cacheSize} parameter of L{__init__}. @since: Twisted 19.2.0 cR||_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)rNpolicyforHTTPS cacheSizes r3rOz#HostnameCachingHTTPSPolicy.__init__s# .!--/ #r:cP|jd} |jj|}||j|<t |j|jkDr|jjd|S#t$r|jj ||}YvwxYw)a< Create a L{client connection creator } 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 } rF)last) r0rpopKeyErrorrrlenrpopitem)rNrrIrHcreators r3rz+HostnameCachingHTTPSPolicy.creatorForNetlocs"w' Lkkood+G$ D t{{ doo - KK  U  + L**;;HdKG LsA==%B%$B%N)r=r>r?r@rOrrAr:r3rrs* $r:rceZdZdZdZdZy)_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)rNcontexts r3rOz#_ContextFactoryWithContext.__init__s   r:c|jS)z Return the context created by L{_DeprecatedToCurrentPolicyForHTTPS._webContextFactory}. @return: A context. @rtype: L{OpenSSL.SSL.Context} rr_s r3rz%_ContextFactoryWithContext.getContexts}}r:N)r=r>r?r@rOrrAr:r3rrs r:rceZdZdZdZdZy)"_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)rNwebContextFactorys r3rOz+_DeprecatedToCurrentPolicyForHTTPS.__init__s #4r:cP|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} )rrr)rNrrIrs r3rz3_DeprecatedToCurrentPolicyForHTTPS.creatorForNetlocs'))44XtD)'22r:NrrAr:r3rrs 43r:rc@eZdZdZedfdZdZdZdZdZ dZ d Z y ) 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. icn||_|j|_||_|j ||_yrd) _inputFile cooperate _cooperate _readSize_determineLengthlength)rN inputFile cooperatorreadSizes r3rOzFileBodyProducer.__init__&s/#$..!++I6 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)seektellAttributeErrorr$osSEEK_ENDSEEK_SET)rNfObjrroriginalPositionends r3rz!FileBodyProducer._determineLength,sj  "99D99D 6 Q f r{{+%%%  "! ! "sAA-,A-c|jj |jjy#tj $rYywxYw)z Permanently stop writing bytes from the file to the consumer by stopping the underlying L{CooperativeTask}. N)rclose_taskstopr TaskFinishedr_s r3 stopProducingzFileBodyProducer.stopProducing=s?   JJOO      s7A  A cjj|_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|jtjr$jtj S|jtj r tj S|Srd)checkrCancelledErrorrr TaskStoppedr)reasonrNs r3 maybeStoppedz5FileBodyProducer.startProducing..maybeStoppedTs]||E001""$>># # d../ >># # r:cyrdrA)ignoreds r3z1FileBodyProducer.startProducing.._r:)r _writelooprwhenDone addCallbacks)rNconsumerdrs` r3startProducingzFileBodyProducer.startProducingHsK__T__X%>? JJ   ! $ +\:r:c#K |jj|j}|s|jjy|j |dXw)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)rreadrrwrite)rNrbytess r3rzFileBodyProducer._writeloopbsO OO((8E%%' NN5 !J sAAc8|jjy)z Temporarily suspend copying bytes from the input file to the consumer by pausing the L{CooperativeTask} which drives that activity. N)rpauser_s r3pauseProducingzFileBodyProducer.pauseProducingos r:c8|jjy)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)rresumer_s r3resumeProducingz FileBodyProducer.resumeProducingvs r:N) r=r>r?r@rrOrrrrrrrAr:r3rrs1*.2E7 &" 4 r:rc$eZdZdZdZddZdZy)_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)rNquiescentCallbackmetadatas r3rOz_HTTP11ClientFactory.__init__s"3!r:cNdj|j|jS)Nz_HTTP11ClientFactory({}, {}))formatrrr_s r3__repr__z_HTTP11ClientFactory.__repr__s$-44  # #T^^  r:c,t|jSrd)r|r)rNaddrs r3 buildProtocolz"_HTTP11ClientFactory.buildProtocols#D$;$;<r?r@rOrr rAr:r3rrs " =r:rc"eZdZdZdZdZdZy)_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)rNclientProtocol newConnections r3rOz&_RetryingHTTP11ClientProtocol.__init__s-+r:c|dvryt|tttfsyt|tr2|j D]#}|j tjs#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} )GETHEADsOPTIONSsDELETEsTRACEFT) isinstancerrrrreasonsrrr)rNr exception bodyProduceraFailures r3 _shouldRetryz*_RetryingHTTP11ClientProtocol._shouldRetryso K K  68M N  i!2 3%-- !>>%"6"67  !  #r:cnjj}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. cjj|jjr"j j fdS|S)Nc&|jSrd)request) connectionr!s r3rzG_RetryingHTTP11ClientProtocol.request..failed..sz'9'9''Br:)rrvaluerr addCallback)rr!rNs r3failedz5_RetryingHTTP11ClientProtocol.request..failedsI  w?S?ST**,88B r:)rr! addErrback)rNr!rr%s`` r3r!z%_RetryingHTTP11ClientProtocol.requests3  ( ( 1  Vr:N)r=r>r?r@rOrr!rAr:r3rrs,8r:rcTeZdZdZeZdZdZdZe Z d dZ dZ dZ dZd 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:chjj}|r|jd}j|j j|=|j dk(r4j rfd}t||}tj|S|rjS)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(jSrd)r)endpointkeyrNsr3rz2HTTPConnectionPool.getConnection..*sD,?,?X,Nr:) r.getrr/cancelstateretryAutomaticallyrrsucceedr)rNr4r3 connectionsr"rs``` r3 getConnectionz HTTPConnectionPool.getConnection s,''++C0 $+J NN: & - - /z*;.**$NM!>"M"J}}Z00""311r:cjfd}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.quiescentCallback9s   X .r:)_factoryreprconnect)rNr4r3rrzs`` r3rz!HTTPConnectionPool._newConnection2s0 /-- 14>B((r:c|jj|j|j||j|=y)zG Remove a connection from the cache and disconnect it. N) transportloseConnectionr.remover/)rNr4r"s r3_removeConnectionz$HTTPConnectionPool._removeConnection?s; ++- #%%j1 NN: &r:cD|jdk7r td|j j |g}t||jk(rU|jd}|jj|j|j|j|=|j||jj!|j"|j$||}||j|<y#t$r|jj dYywxYw)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_logfailurer. setdefaultrmaxPersistentPerHostrrCrDr/r6appendr, callLatercachedConnectionTimeoutrF)rNr4r"r:droppedcids r3r>z!HTTPConnectionPool._putConnectionGs   { * "K''223; { t88 8!ooa(G    , , . NN7 # * * ,w':&mm%%  ( ($*@*@#z &)z"!  !!K   s C88$DDcTg}|jjD](}|D]!}|j|j#*i|_|jjD]}|j i|_t j|jdS)z Close all persistent connections and remove them from the pool. @return: L{defer.Deferred} that fires when all connections have been closed. cyrdrA)igns r3rz;HTTPConnectionPool.closeCachedConnections..rrr:) r.valuesrNabortr/r6r gatherResultsr$)rNresults protocolsr2dcs r3closeCachedConnectionsz)HTTPConnectionPool.closeCachedConnectionscs**113 *I *qwwy) * *..'') B IIK ""7+778HIIr:N)T)r=r>r?r@rr?rMrPr8rrJrOr;rrFr>r\rAr:r3r(r(sH$L$H! 8D $2L )')8Jr:r(c"eZdZdZdZdZdZy) _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}||_||_yNF)r(r,_pool)rNrppools r3rOz_AgentBase.__init__s! <%gu5D  r:cXtt|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._computeHostValues@ d+ ,$;%D D>= =K4,&&r:cttstddtdt  t j dsQjjdjjjjjj||}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 |jtjjjS)N)r- parsedURI)r!r, _constructrar-)protorheadersrrk requestPathrNs r3 cbConnectedz4_AgentBase._requestWithEndpoint..cbConnecteds>=="" #zz44'   r:)rr TypeErrortyper!r# hasHeadercopy addRawHeaderrhrErHrIrar;r$) rNr4r3rrkrnrrorrps ` ````` r3_requestWithEndpointz_AgentBase._requestWithEndpoints&%(gfZtDL>ATUV V#F+ ?iG  )llnG  &&$$inninn  JJ $ $S( 3   k"r:N)r=r>r?r@rOrhrvrAr:r3r^r^us ''r:r^ceZdZdZdZdZy)_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)rNrprwconnectTimeout bindAddresss r3rOz!_StandardEndpointFactory.__init__s#"  --'r:ci}|j|j|d<|j|d< t|j}t|j||jfi|}|jdk(r|S|jdk(r<|jj|j|j}t||Std|j#t$rt dj |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{rrHUnicodeDecodeErrorrYrrr,rIrErrrr)rNr[ryrHr3connectionCreators r3endpointForURIz'_StandardEndpointFactory.endpointForURIs    + $ 4 4F9  $ 1 1} )D$DMM4LVL :: O ZZ8 # $ 4 4 E E#((! !!2H= =$';CJJ>%JK K%" !&S&/   s C%C>N)r=r>r?r@rOrrAr:r3rxrxs (,#Lr:rxcPeZdZdZedddfdZeddZdZdZ d dZ 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 Nctj|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)) stacklevelcategoryN) r( providedBywarningswarnr@DeprecationWarningrrx_init)rNrprwr|r}rbendpointFactorys r3rOzAgent.__init__skD)).9 MM^$66+  @ON2 ^^[  7OT2r:cN|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)rZrprrbagents r3usingEndpointFactoryzAgent.usingEndpointFactoryDs', C  G_d3 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)rNrprrbs r3rz Agent._init^s( D'40 /r:c8|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. )rr)rNr[s r3 _getEndpointzAgent._getEndpointus$$33C88r:c bt|j}tj|} |j |}|j|j|jf}|j|||||||jS#t $r t jtcYSwxYw)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]rrrfailrrErHrIrvrc)rNrr[rnrrkr3r4s r3r!z Agent.requestsciik*MM#&  )((3H@((          " )::gi( ( )sB&B.-B.rdNN) r=r>r?r@rrOrerrrr!rAr:r3rrsA 12  /3b20. 9 r:rc eZdZdZddZddZy) ProxyAgentz An HTTP agent able to cross HTTP proxies. @ivar _proxyEndpoint: The endpoint used to connect to the proxy. @since: 11.1 NcP|ddlm}tj|||||_y)Nrro)rrrpr^rO_proxyEndpoint)rNr3rprbs r3rOzProxyAgent.__init__s$ ? 0D'40&r:c t|j}d|jf}|j||j|tj ||||S)z? Issue a new request via the configured proxy. z http-proxy)r"rGrrvrCr])rNrr[rnrr4s r3r!zProxyAgent.requests_ciik*T001 ((      MM#      r:r)r=r>r?r@rOr!rAr:r3rrs'  r:rcneZdZUdZded<ded<ded<ded<ddZd Zd Zd Zdd Z dZ dZ dZ y )_FakeStdlibRequestau A fake L{urllib.request.Request} object for L{cookiejar} to work with. @see: U{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#_twistedHeadersct||_t|_tj |}t|j |_t|j|_|j |jfdvr+|xjdt|jzz c_t|j|_ d|_ y)zK Create a fake request. @param uri: Request URI. rf:FN) rr[r#rrCr]rErrrHrIr origin_req_host unverifiable)rNr[_uris r3rOz_FakeStdlibRequest.__init__s  $&y}}S! -  + KK #+K K IIs499~- -I+DII6!r:cJ|jjt|Srd)rrsr)rNheaders r3 has_headerz_FakeStdlibRequest.has_headers##--mF.CDDr:c`|jjt|t|yrd)rrur)rNnamer#s r3add_unredirected_headerz*_FakeStdlibRequest.add_unredirected_headers" ))-*=}U?STr:c|jSrdrr_s r3 get_full_urlz_FakeStdlibRequest.get_full_urls xxr:Nc|jjt||}||Dcgc] }t|}}|dSycc}w)Nr)r getRawHeadersrr)rNrdefaultrnxs r3 get_headerz_FakeStdlibRequest.get_headersN&&44]45H'R  0781|A8G81: 9sAc|jSrd)rHr_s r3get_hostz_FakeStdlibRequest.get_host yyr:c|jSrd)rrr_s r3get_typez_FakeStdlibRequest.get_typerr:cyr`rAr_s r3is_unverifiablez"_FakeStdlibRequest.is_unverifiablesr:)r[rr Nonerd) r=r>r?r@__annotations__rOrrrrrrrrAr:r3rrsH" H I I"(EUr:rc eZdZUded<ddZy)_FakeUrllibResponseInfor)responsec|jjjt||}|Dcgc] }t |}}|Scc}wrd)rrnrrr)rNrrrnrhs r3get_allz_FakeUrllibResponseInfo.get_allsD--''55mD6I7S&- .\!_ . . /sA N)rr rrr z list[str])r=r>r?rrrAr:r3rr s r:rc,eZdZUdZded<ddZddZy) _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)rc||_yrd)rrNrs r3rOz_FakeStdlibResponse.__init__"s   r:c0t|j}|Srd)rr)rNr9s r3infoz_FakeStdlibResponse.info%s(7 r:N)rr)r r)r  _InfoType)r=r>r?r@rrOrrAr:r3rrs!r:rcbeZdZUdZded<ded<d dZ d d dZ 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)rr)rNrrs r3rOzCookieAgent.__init__?s "r:Ncz||n t}t|}|jdsZ|jj ||j dd}|+|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} NscookieCookie) r#rrsradd_cookie_headerrrtrurrr!r$_extractCookies)rNrr[rnr actualHeaders lastRequest cookieHeaders r3r!zCookieAgent.requestCs&$+#6GI (- &&y1 NN , ,[ 9&11(DAL' - 2 2 4 **9mL6QR{{"" C  +d**K 8 9r:cP|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. )rextract_cookiesr)rNrr!s r3rzCookieAgent._extractCookieses# &&':8'DgNr:)rr%rrr rr) rrr[rrnzOptional[Headers]rzOptional[IBodyProducer]r zDeferred[IResponse])rr)r!rr r))r=r>r?r@rrOr!rrAr:r3rr*st N#&*04 9 9 9# 9 . 9  9D ! ,>   r:rceZdZdZdZdZy) 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$rrs r3rOzGzipDecoder.__init__}s  $ r:cb|jjt||jy)zf Override C{deliverBody} to wrap the given C{protocol} with L{_GzipProtocol}. N)r deliverBody _GzipProtocol)rNrs r3rzGzipDecoder.deliverBodys! !!-$--"HIr:N)r=r>r?r@rOrrAr:r3rrts%Jr:rc"eZdZdZdZdZdZy)ra0 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 cv||_||_tjdtjz|_y)N)r _responsezlib decompressobj MAX_WBITS_zlibDecompress)rNrrs r3rOz_GzipProtocol.__init__s,  !#11"t~~2EFr: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 decompressrrrrrr dataReceived)rNdatarawDatas r3rz_GzipProtocol.dataReceivedsc  >**55d;G  MM & &w / zz > ')dnn= = >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) rflushrrrrrrrconnectionLost)rNrrs r3rz_GzipProtocol.connectionLostst  F**002G  MM & &w / $$V, zz F &')!4dnnE E Fs A4B Nr=r>r?r@rOrrrAr:r3rrs G 0 -r:rc$eZdZdZdZddZdZy)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|Dcgc]}|d c}|_ycc}w)N,r)rdict _decodersjoin _supported)rNrdecodersdecoders r3rOzContentDecoderAgent.__init__s6 h))x$HGWQZ$HI$Hs ANc| t}n|j}|jd|j|jj ||||}|j |jS)zv Send a client request which declares supporting compressed content. @see: L{Agent.request}. saccept-encoding)r#rtrurrr!r$_handleResponserNrr[rnrdeferreds r3r!zContentDecoderAgent.requestsa ?iGllnG/A;;&&vsG\J##D$8$899r:c|jjdg}dj|jd}|rY|j j }|j j|}| ||}n|j|n|rY|r.|jjddj|g|S|jjd|S)zX Check if the response is encoded, and wrap it to handle decompression. scontent-encodingr) rnrrsplitrrGrr5rN setRawHeaders removeHeader)rNrcontentEncodingHeadersrrs r3rz#ContentDecoderAgent._handleResponses"*!1!1!?!?@SUW!X!%+A!B!H!H!N$)--/557Dnn((.G""8,'--d3% "    * *#dii0F&G%H      ) )*= >r:r)r=r>r?r@rOr!rrAr:r3rrs6J :r:r)s AuthorizationsCookiesCookie2sProxy-AuthorizationsWWW-AuthenticateceZdZdZej ej ejejgZ ejgZ d d dZ d dZ dZdZdZy) 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||_||_|Dchc] }t|}}|jt||_ycc}wrd)r_redirectLimit_canonicalHeaderNameupdate_defaultSensitiveHeaders_sensitiveHeaderNames)rNr redirectLimitsensitiveHeaderNameseach sensitives r3rOzRedirectAgent.__init__-sI  + ;;&&vsG\J##D$8$8&#wPQRRr:ct||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 requestURIlocations r3_resolveLocationzRedirectAgent._resolveLocationBs H--r:c||jk\r8tjjd|}t t |gj jdg}|s7tjjd|}t t |g|j||d}|rtj|} tj|} | j| jk(xr4| j| jk(xr| j| jk(} | s;t|j!D cic]\} } | |j"vr| | c} } }|j$j'|||}fd}|j)||j)|j*||||dzScc} } w)z Handle a redirect response, checking the number of redirects already followed, and extracting the location header fields. sInfinite redirection detectedrslocationsNo location header fieldrc*|j|Srd)setPreviousResponse) newResponsers r3_chainResponsez5RedirectAgent._handleRedirect.._chainResponsets  + +H 5 r:rU)rrInfiniteRedirectioncoderrrnrRedirectWithNoLocationrrCr]rErHrIr#getAllRawHeadersr rr!r$r)rNrrr[rn redirectCounterrlocationHeadersrrkparsedLocation sameOriginrawNamerawValuerrs ` r3_handleRedirectzRedirectAgent._handleRedirectQs D// /++ ?#C!'#,: :"**88bI.. :CC!'#,: :((oa.@A  c*I ]]84N!!^%:%::<^^~':'::<^^~':'::  !291I1I1K-GX"$*D*DD );;&&vxA  ^,##  &#w 8I  sG c0|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 PageRedirectrrr%_seeOtherResponses)rNrrr[rnrrs r3rzRedirectAgent._handleResponse}s ==D33 3..((E$gcl^X>>''&#w V V ]]d55 5''&#w V Vr:)rrA)rr%r rXr zIterable[bytes]r)r=r>r?r@r MOVED_PERMANENTLYFOUNDTEMPORARY_REDIRECTPERMANENT_REDIRECTr' SEE_OTHERr)rOr!rr%rrAr:r3rr s6      ..)  02 / / /. /S .* X r:rceZdZdZej gZejejejejgZ y)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:r3r0r0s@ 112     r:r0c"eZdZdZdZdZdZy)_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)rstatusmessage dataBuffer)rNr4r5rs r3rOz_ReadBodyProtocol.__init__s !   r:c:|jj|y)z? Accumulate some more bytes from the response. N)r6rN)rNrs r3rz_ReadBodyProtocol.dataReceiveds t$r:c |jtr5|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) rrrcallbackrr6r}errbackr<r4r5)rNrs r3rz _ReadBodyProtocol.connectionLosts << % MM " "388DOO#< = \\+ , MM ! !$KKsxx/H  MM ! !& )r:NrrAr:r3r2r2s  % *r:r2c dfd }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)rrWgetAborts r3r6zreadBody..cancels    G r:c2tjddS)NabortConnection)getattrrC)rsr3r=zreadBody..getAbortsx))+r=rrrrFactoryrrr(r^rxrrrrrrrrr_canonicalNameCapsr frozensetr rr0Protocolr2rC__all__rAr:r3ris #  !$44FF&223+FI!=7+#F,796LMI$ 5;;ood68D    1 >#H#HL _XXX: Ir1a  2q!$- eDk!  &&$$  _===@ #$%: _$3$3$3N ]lll^=8++=4==@YJYJxBBJ "#GLGL$GLT VT JT T n V$ $ $ NDDN i -( VFFFRJ#I.J*)-%i0)-X VDDDNy33$ V~~~B}.3*))3*l) X k/ CsL00L;:L;