o bs @sdZddlZddlZddlZddlZddlmZddlmZddl m Z m Z m Z ddlmZddlmZddlmZmZmZdd lmZdd lmZmZdd lmZmZdd lmZdd l m!Z!m"Z"ddl#m$Z$ddl%m&Z&m'Z'ddl(m)Z)ddl*m+Z+m,Z,ddl-m.Z.m/Z/ddl0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8ddZ Gddde+j9Z:GdddZ;ddZZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHdd lImJZJzdd!lKmLZLWn eMydZLYn wdd"lNmOZOmPZPmQZQd#d$ZRGd%d&d&ZSee7Gd'd(d(ZTe&ed)d*dde'eSed)d*ddeTd+Ud,d-eSjVeSjWee7Gd.d/d/ZXeeGd0d1d1ZYee7Gd2d3d3ZZee6Gd4d5d5Z[Gd6d7d7ej\Z]Gd8d9d9Z^Gd:d;d;Z_Gdd?d?Zaee4Gd@dAdAe`Zbee4GdBdCdCe`ZcGdDdEdEZdGdFdGdGZeee4GdHdIdIZfGdJdKdKe$e8ZgGdLdMdMe$eZhee4GdNdOdOZie1jjZkelgdPZmee4GdQdRdRZnGdSdTdTenZoGdUdVdVejpZqdWe8dXejresfdYdZZtgd[ZudS)]z HTTP client. N)wraps)Iterable) urldefragurljoin urlunparse) implementer)Version)deferprotocoltask) isIPv6Address)HostnameEndpoint wrapClientTLS)IOpenSSLContextFactory IProtocol)Logger) nativeString networkString)proxyForInterface)deprecatedModuleAttributegetDeprecationWarningString)Failure)errorhttp)_ensureValidMethod_ensureValidURI)Headers)UNKNOWN_LENGTHIAgentIAgentEndpointFactory IBodyProducerIPolicyForHTTPS IResponsecCs ttdd|D}|dS)Ncss|]}|dVqdS)charmapN)decode).0pr'4/usr/lib/python3/dist-packages/twisted/web/client.py 0szurlunparse..r#) _urlunparsetupleencode)partsresultr'r'r(r/s rc@seZdZdZdS)PartialDownloadErrorz Page was only partially downloaded, we got disconnected in middle. @ivar response: All of the response body which was downloaded. N)__name__ __module__ __qualname____doc__r'r'r'r(r/4sr/c@s:eZdZdZddZed ddZddZed d Z dS) URIzd A URI object. @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21} c Cs:||_||_|d|_||_||_||_||_||_dS)a @type scheme: L{bytes} @param scheme: URI scheme specifier. @type netloc: L{bytes} @param netloc: Network location component. @type host: L{bytes} @param host: Host name. For IPv6 address literals the brackets are stripped. @type port: L{int} @param port: Port number. @type path: L{bytes} @param path: Hierarchical path. @type params: L{bytes} @param params: Parameters for last path segment. @type query: L{bytes} @param query: Query string. @type fragment: L{bytes} @param fragment: Fragment identifier. s[]N) schemenetlocstriphostportpathparamsqueryfragment) selfr5r6r8r9r:r;r<r=r'r'r(__init__Cs  z URI.__init__Nc Cs|}t|\}}}}}}|dur|dkrd}nd}d|vr=|dd\} } zt| } Wnty<||} } Ynw||} } |||| | ||||S)aN Parse the given URI into a L{URI}. @type uri: C{bytes} @param uri: URI to parse. @type defaultPort: C{int} or L{None} @param defaultPort: An alternate value to use as the port if the URI does not include one. @rtype: L{URI} @return: Parsed URI instance. NhttpsP:)r7rurlparsersplitint ValueError) clsuri defaultPortr5r6r:r;r<r=r8r9r'r'r( fromBytesgs   z URI.fromBytescCs t|j|j|j|j|j|jfS)z Assemble the individual parts of the I{URI} into a fully formed I{URI}. @rtype: C{bytes} @return: A fully formed I{URI}. )rr5r6r:r;r<r=r>r'r'r(toBytessz URI.toBytescCs*tdd|j|j|jdf}|dkrd}|S)a! The absolute I{URI} path including I{URI} parameters, query string and fragment identifier. @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21#section-5.3} @return: The absolute path in original form. @rtype: L{bytes} /)rr:r;r<)r>r:r'r'r( originForms zURI.originFormN) r0r1r2r3r? classmethodrLrNpropertyrQr'r'r'r(r4<s$ !r4cCs0t|\}}tt||\}}t|d|p|S)a Construct a full ("absolute") URL by combining a "base URL" with another URL. Informally, this uses components of the base URL, in particular the addressing scheme, the network location and (part of) the path, to provide missing components in the relative URL. Additionally, the fragment identifier is preserved according to the HTTP 1.1 bis draft. @type base: C{bytes} @param base: Base URL. @type url: C{bytes} @param url: URL to combine with C{base}. @return: An absolute URL resulting from the combination of C{base} and C{url}. @see: L{urllib.parse.urljoin()} @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2} #)rr)baseurlbaseFragurlFragr'r'r(_urljoins rZc Ostt|}||g|Ri|}ddlm}|jdkr;ddlm}|dur-|}| t |j |j |||S| t |j |j ||S)a Create and connect an HTTP page getting factory. Any additional positional or keyword arguments are used when calling C{factoryFactory}. @param factoryFactory: Factory factory that is called with C{url}, C{args} and C{kwargs} to produce the getter @param contextFactory: Context factory to use when creating a secure connection, defaulting to L{None} @return: The factory created by C{factoryFactory} rreactorr@)sslN)r4rLrr7twisted.internetr\r5r]ClientContextFactory connectSSLrr8r9 connectTCP) rWfactoryFactorycontextFactoryargskwargsrJfactoryr\r]r'r'r(_makeGetterFactorys   rg) HTTP11ClientProtocolPotentialDataLossRequestRequestGenerationFailedRequestNotSentRequestTransmissionFailedResponse ResponseDoneResponseFailedResponseNeverReceived_WrapperException)SchemeNotSupported)SSL)CertificateOptionsoptionsForClientTLS platformTrustcCs tdurt|dd}|S|S)a} The decorated method requires pyOpenSSL to be present, or it raises L{NotImplementedError}. @param decoratee: A function which requires pyOpenSSL. @type decoratee: L{callable} @return: A function which raises L{NotImplementedError} if pyOpenSSL is not installed; otherwise, if it is installed, simply return C{decoratee}. @rtype: L{callable} Nc_std)z pyOpenSSL is not available. @param a: The positional arguments for C{decoratee}. @param kw: The keyword arguments for C{decoratee}. @raise NotImplementedError: Always. zSSL support unavailable)NotImplementedError)akwr'r'r(raiseNotImplementeds z(_requireSSL..raiseNotImplemented)rtr) decorateer{r'r'r( _requireSSLs    r}c@s$eZdZdZddZeddZdS)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. cCsttjtdS)z Return a L{CertificateOptions}. @param hostname: ignored @param port: ignored @return: A new CertificateOptions instance. @rtype: L{CertificateOptions} )method trustRoot)rurt SSLv23_METHODrwr>hostnamer9r'r'r(_getCertificateOptions1 z.WebClientContextFactory._getCertificateOptionscCs|||S)z Return an L{OpenSSL.SSL.Context}. @param hostname: ignored @param port: ignored @return: A new SSL context. @rtype: L{OpenSSL.SSL.Context} )r getContextrr'r'r(r>rz"WebClientContextFactory.getContextN)r0r1r2r3rr}rr'r'r'r(r~&s   r~c@s&eZdZdZdddZeddZdS)BrowserLikePolicyForHTTPSz1 SSL connection creator for web clients. NcC ||_dSrR) _trustRoot)r>rr'r'r(r?R z"BrowserLikePolicyForHTTPS.__init__cCst|d|jdS)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)rvr$rrr'r'r(creatorForNetlocUsz*BrowserLikePolicyForHTTPS.creatorForNetlocrR)r0r1r2r3r?r}rr'r'r'r(rLs  rTwisted) replacementz; rDc@s"eZdZdZdddZddZdS) 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 cCs||_t|_||_dS)z @param policyforHTTPS: The IPolicyForHTTPS to wrap. @type policyforHTTPS: L{IPolicyForHTTPS} @param cacheSize: The maximum size of the hostname cache. @type cacheSize: L{int} N)_policyForHTTPS collections OrderedDict_cache _cacheSize)r>policyforHTTPS cacheSizer'r'r(r?s  z#HostnameCachingHTTPSPolicy.__init__cCsh|d}z|j|}Wnty|j||}Ynw||j|<t|j|jkr2|jjdd|S)a< Create a L{client connection creator } 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) r$rpopKeyErrorrrlenrpopitem)r>rr9r8creatorr'r'r(rs   z+HostnameCachingHTTPSPolicy.creatorForNetlocN)rr0r1r2r3r?rr'r'r'r(rvs  rc@ eZdZdZddZddZdS)_ContextFactoryWithContextz A L{_ContextFactoryWithContext} is like a L{twisted.internet.ssl.ContextFactory} with a pre-created context. @ivar _context: A Context. @type _context: L{OpenSSL.SSL.Context} cC ||_dS)z Initialize a L{_ContextFactoryWithContext} with a context. @param context: An SSL context. @type context: L{OpenSSL.SSL.Context} N_context)r>contextr'r'r(r?s z#_ContextFactoryWithContext.__init__cC|jS)z Return the context created by L{_DeprecatedToCurrentPolicyForHTTPS._webContextFactory}. @return: A context. @rtype: L{OpenSSL.SSL.Context} rrMr'r'r(rsz%_ContextFactoryWithContext.getContextN)r0r1r2r3r?rr'r'r'r(rs rc@r)"_DeprecatedToCurrentPolicyForHTTPSa+ Adapt a web context factory to a normal context factory. @ivar _webContextFactory: An object providing a getContext method with C{hostname} and C{port} arguments. @type _webContextFactory: L{WebClientContextFactory} (or object with a similar C{getContext} method). cCr)a> Wrap a web context factory in an L{IPolicyForHTTPS}. @param webContextFactory: An object providing a getContext method with C{hostname} and C{port} arguments. @type webContextFactory: L{WebClientContextFactory} (or object with a similar C{getContext} method). N)_webContextFactory)r>webContextFactoryr'r'r(r?s z+_DeprecatedToCurrentPolicyForHTTPS.__init__cCs|j||}t|S)a Called the wrapped web context factory's C{getContext} method with a hostname and port number and return the resulting context object. @param hostname: The hostname part of the URI. @type hostname: L{bytes} @param port: The port part of the URI. @type port: L{int} @return: A context factory. @rtype: L{IOpenSSLContextFactory} )rrr)r>rr9rr'r'r(rsz3_DeprecatedToCurrentPolicyForHTTPS.creatorForNetlocNrr'r'r'r(rs rc@sNeZdZdZedfddZddZddZd d Zd d Z d dZ ddZ dS)FileBodyProducera L{FileBodyProducer} produces bytes from an input file object incrementally and writes them to a consumer. Since file-like objects cannot be read from in an event-driven manner, L{FileBodyProducer} uses a L{Cooperator} instance to schedule reads from the file. This process is also paused and resumed based on notifications from the L{IConsumer} provider being written to. The file is closed after it has been read, or if the producer is stopped early. @ivar _inputFile: Any file-like object, bytes read from which will be written to a consumer. @ivar _cooperate: A method like L{Cooperator.cooperate} which is used to schedule all reads. @ivar _readSize: The number of bytes to read from C{_inputFile} at a time. icCs$||_|j|_||_|||_dSrR) _inputFile cooperate _cooperate _readSize_determineLengthlength)r> inputFile cooperatorreadSizer'r'r(r?szFileBodyProducer.__init__cCsTz|j}|j}Wn tytYSw|}|dtj|}||tj||S)z Determine how many bytes can be read out of C{fObj} (assuming it is not modified from this point on). If the determination cannot be made, return C{UNKNOWN_LENGTH}. r)seektellAttributeErrorrosSEEK_ENDSEEK_SET)r>fObjrroriginalPositionendr'r'r(rs    z!FileBodyProducer._determineLengthcCs2|jz|jWdStjyYdSw)z Permanently stop writing bytes from the file to the consumer by stopping the underlying L{CooperativeTask}. N)rclose_taskstopr TaskFinishedrMr'r'r( stopProducing+s zFileBodyProducer.stopProducingcs<|_j}fdd}|dd||S)aZ Start a cooperative task which will read bytes from the input file and write them to C{consumer}. Return a L{Deferred} which fires after all bytes have been written. If this L{Deferred} is cancelled before it is fired, stop reading and writing bytes. @param consumer: Any L{IConsumer} provider cs6|tjrtS|tjr tS|SrR)checkr CancelledErrorrr TaskStoppedDeferredreasonrMr'r( maybeStoppedBs  z5FileBodyProducer.startProducing..maybeStoppedcSdSrRr')ignoredr'r'r(Mz1FileBodyProducer.startProducing..)r _writelooprwhenDone addCallbacks)r>consumerdrr'rMr(startProducing6s    zFileBodyProducer.startProducingccs6 |j|j}|s|jdS||dVq)z Return an iterator which reads one chunk of bytes from the input file and writes them to the consumer for each time it is iterated. TN)rreadrrwrite)r>rbytesr'r'r(rPs  zFileBodyProducer._writeloopcC|jdS)z Temporarily suspend copying bytes from the input file to the consumer by pausing the L{CooperativeTask} which drives that activity. N)rpauserMr'r'r(pauseProducing]szFileBodyProducer.pauseProducingcCr)z Undo the effects of a previous C{pauseProducing} and resume copying bytes to the consumer by resuming the L{CooperativeTask} which drives the write activity. N)rresumerMr'r'r(resumeProducingdsz FileBodyProducer.resumeProducingN) r0r1r2r3r r?rrrrrrr'r'r'r(rs  rc@s.eZdZdZddZdefddZddZd S) _HTTP11ClientFactoryaa A factory for L{HTTP11ClientProtocol}, used by L{HTTPConnectionPool}. @ivar _quiescentCallback: The quiescent callback to be passed to protocol instances, used to return them to the connection pool. @ivar _metadata: Metadata about the low-level connection details, used to make the repr more useful. @since: 11.1 cC||_||_dSrR)_quiescentCallback _metadata)r>quiescentCallbackmetadatar'r'r(r?z z_HTTP11ClientFactory.__init__returncCsd|j|jS)Nz_HTTP11ClientFactory({}, {}))formatrrrMr'r'r(__repr__~sz_HTTP11ClientFactory.__repr__cCs t|jSrR)rhr)r>addrr'r'r( buildProtocolrz"_HTTP11ClientFactory.buildProtocolN)r0r1r2r3r?strrrr'r'r'r(rms   rc@(eZdZdZddZddZddZdS) _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. cCrrR)_clientProtocol_newConnection)r>clientProtocol newConnectionr'r'r(r?rz&_RetryingHTTP11ClientProtocol.__init__cCsX|dvrdSt|tttfsdSt|tr$|jD] }|tjr#dSq|dur*dSdS)a Indicate whether request should be retried. Only returns C{True} if method is idempotent, no response was received, the reason for the failed request was not due to user-requested cancellation, and no body was sent. The latter requirement may be relaxed in the future, and PUT added to approved method list. @param method: The method of the request. @type method: L{bytes} )GETHEADsOPTIONSsDELETEsTRACEFNT) isinstancerlrmrqrrreasonsrr r)r>r exception bodyProduceraFailurer'r'r( _shouldRetrys    z*_RetryingHTTP11ClientProtocol._shouldRetrycs(j}fdd}|||S)z Do a request, and retry once (with a new connection) if it fails in a retryable manner. @param request: A L{Request} instance that will be requested using the wrapped protocol. cs.j|jjrfddS|S)Ncs |SrRrequest) connectionrr'r(rs zG_RetryingHTTP11ClientProtocol.request..failed..)rrvaluerr addCallbackrrr>r'r(faileds  z5_RetryingHTTP11ClientProtocol.request..failed)rr addErrback)r>rrrr'rr(rs  z%_RetryingHTTP11ClientProtocol.requestN)r0r1r2r3r?rrr'r'r'r(rs   rc@sXeZdZdZeZdZdZdZe Z dddZ ddZ d d Z d d Zd dZddZdS)HTTPConnectionPoolaU A pool of persistent HTTP connections. Features: - Cached connections will eventually time out. - Limits on maximum number of persistent connections. Connections are stored using keys, which should be chosen such that any connections stored under a given key can be used interchangeably. Failed requests done using previously cached connections will be retried once if they use an idempotent method (e.g. GET), in case the HTTP server timed them out. @ivar persistent: Boolean indicating whether connections should be persistent. Connections are persistent by default. @ivar maxPersistentPerHost: The maximum number of cached persistent connections for a C{host:port} destination. @type maxPersistentPerHost: C{int} @ivar cachedConnectionTimeout: Number of seconds a cached persistent connection will stay open before disconnecting. @ivar retryAutomatically: C{boolean} indicating whether idempotent requests should be retried once if no response was received. @ivar _factory: The factory used to connect to the proxy. @ivar _connections: Map (scheme, host, port) to lists of L{HTTP11ClientProtocol} instances. @ivar _timeouts: Map L{HTTP11ClientProtocol} instances to a C{IDelayedCall} instance of their timeout. @since: 12.1 TcCs||_||_i|_i|_dSrR)_reactor persistent _connections _timeouts)r>r\rr'r'r(r?s zHTTPConnectionPool.__init__cstj}|r4|d}j|j|=|jdkr2jr-fdd}t||}t |S|s S)a Supply a connection, newly created or retrieved from the pool, to be used for one HTTP request. The connection will remain out of the pool (not available to be returned from future calls to this method) until one HTTP request has been completed over it. Afterwards, if the connection is still open, it will automatically be added to the pool. @param key: A unique key identifying connections that can be used interchangeably. @param endpoint: An endpoint that can be used to open a new connection if no cached connection is available. @return: A C{Deferred} that will fire with a L{HTTP11ClientProtocol} (or a wrapper) that can be used to send a single HTTP request. r QUIESCENTcs SrR)rr'endpointkeyr>r'r(rs z2HTTPConnectionPool.getConnection..) rgetrrcancelstateretryAutomaticallyrr succeedr)r>rr connectionsrrr'rr( getConnections     z HTTPConnectionPool.getConnectioncs(fdd}|t|}||S)zv Create a new connection. This implements the new connection code path for L{getConnection}. cs|dSrR)_putConnectionr rr>r'r(r'z.quiescentCallback)_factoryreprconnect)r>rrrrfr'rr(r s z!HTTPConnectionPool._newConnectioncCs&|j|j|||j|=dS)zG Remove a connection from the cache and disconnect it. N) transportloseConnectionrremover)r>rrr'r'r(_removeConnection-s  z$HTTPConnectionPool._removeConnectioncCs|jdkrztdty|jdYdSw|j|g}t||jkr=| d}|j |j | |j |=|||j|j|j||}||j |<dS)z Return a persistent connection to the pool. This will be called by L{HTTP11ClientProtocol} when the connection becomes quiescent. rz5BUG: Non-quiescent protocol added to connection pool.Nr)r  RuntimeError BaseException_logfailurer setdefaultrmaxPersistentPerHostrrrrr appendr callLatercachedConnectionTimeoutr)r>rrrdroppedcidr'r'r(r5s,      z!HTTPConnectionPool._putConnectioncCsdg}|jD]}|D] }||q qi|_|jD]}|qi|_t|ddS)z Close all persistent connections and remove them from the pool. @return: L{defer.Deferred} that fires when all connections have been closed. cSrrRr')ignr'r'r(r`rz;HTTPConnectionPool.closeCachedConnections..) rvaluesr!abortrr r gatherResultsr)r>results protocolsr&dcr'r'r(closeCachedConnectionsQs z)HTTPConnectionPool.closeCachedConnectionsN)T)r0r1r2r3rrr r#r rrr?rrrrr-r'r'r'r(rs& &  rc@r) _AgentBasea Base class offering common facilities for L{Agent}-type classes. @ivar _reactor: The C{IReactorTime} implementation which will be used by the pool, and perhaps by subclasses as well. @ivar _pool: The L{HTTPConnectionPool} used to manage HTTP connections. cCs"|dur t|d}||_||_dSNF)rr_pool)r>r\poolr'r'r(r?ms  z_AgentBase.__init__cCs4tt|r d|d}||fdvr|Sd||fS)z Compute the string to use for the value of the I{Host} header, based on the given scheme, host name, and port number. [])httprB)r@rAs%b:%d)r r)r>r5r8r9r'r'r(_computeHostValuess    z_AgentBase._computeHostValuec sttstddtdtdurtds4d j j j j ||}fdd} || |S)zk Issue a new request, given the endpoint and the path sent as part of the request. zmethod=z is z, but must be bytesNshostc s |tjjjdS)N)r parsedURI)rrj _constructr0r)protorheadersrr7 requestPathr>r'r( cbConnectedsz4_AgentBase._requestWithEndpoint..cbConnected)rr TypeErrortyperr hasHeadercopy addRawHeaderr6r5r8r9r0rr) r>rrrr7r;rr<rr=r'r:r(_requestWithEndpoint~s"    z_AgentBase._requestWithEndpointN)r0r1r2r3r?r6rCr'r'r'r(r.cs   r.c@r)_StandardEndpointFactorya Standard HTTP endpoint destinations - TCP for HTTP, TCP+TLS for HTTPS. @ivar _policyForHTTPS: A web context factory which will be used to create SSL context objects for any SSL connections the agent needs to make. @ivar _connectTimeout: If not L{None}, the timeout passed to L{HostnameEndpoint} for specifying the connection timeout. @ivar _bindAddress: If not L{None}, the address passed to L{HostnameEndpoint} for specifying the local address to bind to. cCs||_||_||_||_dS)a @param reactor: A provider to use to create endpoints. @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor types. @param contextFactory: A factory for TLS contexts, to control the verification parameters of OpenSSL. @type contextFactory: L{IPolicyForHTTPS}. @param connectTimeout: The amount of time that this L{Agent} will wait for the peer to accept a connection. @type connectTimeout: L{float} or L{None} @param bindAddress: The local address for client sockets to bind to. @type bindAddress: L{bytes} or L{None} N)rr_connectTimeout _bindAddress)r>r\rcconnectTimeout bindAddressr'r'r(r?s z!_StandardEndpointFactory.__init__cCsi}|jdur |j|d<|j|d<zt|j}Wnty'tdj|dwt|j||j fi|}|j dkr;|S|j dkrN|j |j|j }t ||Std|j ) z Connect directly over TCP for C{b'http'} scheme, and TLS for C{b'https'}. @param uri: L{URI} to connect to. @return: Endpoint to connect to. @rtype: L{IStreamClientEndpoint} NtimeoutrHzdThe host of the provided URI ({uri.host!r}) contains non-ASCII octets, it should be ASCII decodable.rJr5r@zUnsupported scheme: )rErFrr8UnicodeDecodeErrorrHrr rr9r5rrrrs)r>rJrer8rconnectionCreatorr'r'r(endpointForURIs,       z'_StandardEndpointFactory.endpointForURIN)r0r1r2r3r?rMr'r'r'r(rDs rDc@sLeZdZdZedddfddZed ddZddZd d Z dd d Z dS)Agenta+ L{Agent} is a very basic HTTP client. It supports I{HTTP} and I{HTTPS} scheme URIs. @ivar _pool: An L{HTTPConnectionPool} instance. @ivar _endpointFactory: The L{IAgentEndpointFactory} which will be used to create endpoints for outgoing connections. @since: 9.0 NcCsJt|stjt|ddtdt|}t||||}||||dS)a Create an L{Agent}. @param reactor: A reactor for this L{Agent} to place outgoing connections. @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor types. @param contextFactory: A factory for TLS contexts, to control the verification parameters of OpenSSL. The default is to use a L{BrowserLikePolicyForHTTPS}, so unless you have special requirements you can leave this as-is. @type contextFactory: L{IPolicyForHTTPS}. @param connectTimeout: The amount of time that this L{Agent} will wait for the peer to accept a connection. @type connectTimeout: L{float} @param bindAddress: The local address for client sockets to bind to. @type bindAddress: L{bytes} @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which case a non-persistent L{HTTPConnectionPool} instance will be created. @type pool: L{HTTPConnectionPool} z was passed as the HTTPS policy for an Agent, but it does not provide IPolicyForHTTPS. Since Twisted 14.0, you must pass a provider of IPolicyForHTTPS.r) stacklevelcategoryN) r! providedBywarningswarnrDeprecationWarningrrD_init)r>r\rcrGrHr1endpointFactoryr'r'r(r?s "zAgent.__init__cCs||}|||||S)a Create a new L{Agent} that will use the endpoint factory to figure out how to connect to the server. @param reactor: A reactor for this L{Agent} to place outgoing connections. @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor types. @param endpointFactory: Used to construct endpoints which the HTTP client will connect with. @type endpointFactory: an L{IAgentEndpointFactory} provider. @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which case a non-persistent L{HTTPConnectionPool} instance will be created. @type pool: L{HTTPConnectionPool} @return: A new L{Agent}. )__new__rU)rIr\rVr1agentr'r'r(usingEndpointFactory2s zAgent.usingEndpointFactorycCst|||||_dS)a Initialize a new L{Agent}. @param reactor: A reactor for this L{Agent} to place outgoing connections. @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor types. @param endpointFactory: Used to construct endpoints which the HTTP client will connect with. @type endpointFactory: an L{IAgentEndpointFactory} provider. @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which case a non-persistent L{HTTPConnectionPool} instance will be created. @type pool: L{HTTPConnectionPool} @return: A new L{Agent}. N)r.r?_endpointFactory)r>r\rVr1r'r'r(rULs z Agent._initcCs |j|S)z Get an endpoint for the given URI, using C{self._endpointFactory}. @param uri: The URI of the request. @type uri: L{URI} @return: An endpoint which can be used to connect to given address. )rZrM)r>rJr'r'r( _getEndpointcs zAgent._getEndpointc Cslt|}t|}z||}Wnty!ttYSw|j |j |j f}| |||||||j S)a) Issue a request to the server indicated by the given C{uri}. An existing connection from the connection pool may be used or a new one may be created. I{HTTP} and I{HTTPS} schemes are supported in C{uri}. @see: L{twisted.web.iweb.IAgent.request} )rr7r4rLr[rsr failrr5r8r9rCrQ)r>rrJr;rr7rrr'r'r(rns"  z Agent.requestrRNN) r0r1r2r3rr?rSrYrUr[rr'r'r'r(rNs 1  rNc@s$eZdZdZdddZdddZdS) ProxyAgentz An HTTP agent able to cross HTTP proxies. @ivar _proxyEndpoint: The endpoint used to connect to the proxy. @since: 11.1 NcCs,|dur ddlm}t|||||_dS)Nrr[)r^r\r.r?_proxyEndpoint)r>rr\r1r'r'r(r?s  zProxyAgent.__init__c Cs4t|}d|jf}|||j|t||||S)z? Issue a new request via the configured proxy. z http-proxy)rr7r_rCr4rL)r>rrJr;rrr'r'r(rs  zProxyAgent.requestr])r0r1r2r3r?rr'r'r'r(r^s r^c@sReZdZdZddZddZddZdd Zdd d Zd dZ ddZ ddZ d S)_FakeUrllib2Requesta A fake C{urllib2.Request} object for C{cookielib} to work with. @see: U{http://docs.python.org/library/urllib2.html#request-objects} @type uri: native L{str} @ivar uri: Request URI. @type headers: L{twisted.web.http_headers.Headers} @ivar headers: Request headers. @type type: native L{str} @ivar type: The scheme of the URI. @type host: native L{str} @ivar host: The host[:port] of the URI. @since: 11.1 cCsvt||_t|_t|}t|j|_t|j|_|j|j fdvr.|jdt |j 7_t|j|_ dd|_ dS)zn Create a fake Urllib2 request. @param uri: Request URI. @type uri: L{bytes} r4:cSdSr/r')_r'r'r(rrz._FakeUrllib2Request.__init__..N) rrJrr;r4rLr5r?r8r9rorigin_req_host unverifiable)r>rJ_urir'r'r(r?s     z_FakeUrllib2Request.__init__cCs|jt|SrR)r;r@r)r>headerr'r'r( has_headerrz_FakeUrllib2Request.has_headercCs|jt|t|dSrR)r;rBr)r>namerr'r'r(add_unredirected_headersz+_FakeUrllib2Request.add_unredirected_headercCrrRrJrMr'r'r( get_full_urlz _FakeUrllib2Request.get_full_urlNcCs4|jt||}|durdd|D}|dSdS)NcSg|]}t|qSr'rr%xr'r'r( z2_FakeUrllib2Request.get_header..r)r; getRawHeadersr)r>ridefaultr;r'r'r( get_headers z_FakeUrllib2Request.get_headercCrrR)r8rMr'r'r(get_hostrlz_FakeUrllib2Request.get_hostcCrrR)r?rMr'r'r(get_typerlz_FakeUrllib2Request.get_typecCrbr/r'rMr'r'r(is_unverifiablesz#_FakeUrllib2Request.is_unverifiablerR) r0r1r2r3r?rhrjrkrurvrwrxr'r'r'r(r`s  r`c@r)_FakeUrllib2Responsez A fake C{urllib2.Response} object for C{cookielib} to work with. @type response: C{twisted.web.iweb.IResponse} @ivar response: Underlying Twisted Web response. @since: 11.1 cCrrRresponser>r{r'r'r(r?rz_FakeUrllib2Response.__init__csGfddd}|S)Ncs$eZdZfddZfddZdS)z(_FakeUrllib2Response.info.._Metacsjj|g}|SrR)r{r;rs)zelfrir;rMr'r( getheaderssz3_FakeUrllib2Response.info.._Meta.getheaderscs&jjt||}dd|D}|S)NcSrmr'rnror'r'r(rqrrzD_FakeUrllib2Response.info.._Meta.get_all..)r{r;rsr)r}rirtr;hrMr'r(get_all s z0_FakeUrllib2Response.info.._Meta.get_allN)r0r1r2r~rr'rMr'r(_Metas rr')r>rr'rMr(infosz_FakeUrllib2Response.infoN)r0r1r2r3r?rr'r'r'r(rys ryc@*eZdZdZddZd ddZddZdS) CookieAgentaj L{CookieAgent} extends the basic L{Agent} to add RFC-compliant handling of HTTP cookies. Cookies are written to and extracted from a C{cookielib.CookieJar} instance. The same cookie jar instance will be used for any requests through this agent, mutating it whenever a I{Set-Cookie} header appears in a response. @type _agent: L{twisted.web.client.Agent} @ivar _agent: Underlying Twisted Web agent to issue requests through. @type cookieJar: C{cookielib.CookieJar} @ivar cookieJar: Initialized cookie jar to read cookies from and store cookies to. @since: 11.1 cCrrR)_agent cookieJar)r>rXrr'r'r(r?+rzCookieAgent.__init__NcCs||durt}t|}|ds,|j||dd}|dur,|}|dt||j ||||}| |j ||S)a Issue a new request to the wrapped L{Agent}. Send a I{Cookie} header if a cookie for C{uri} is stored in L{CookieAgent.cookieJar}. Cookies are automatically extracted and stored from requests. If a C{'cookie'} header appears in C{headers} it will override the automatic cookie header obtained from the cookie jar. @see: L{Agent.request} NscookieCookie) rr`r@radd_cookie_headerrurArBrrrr_extractCookies)r>rrJr;r lastRequest cookieHeaderrr'r'r(r/s    zCookieAgent.requestcCst|}|j|||S)z Extract response cookies and store them in the cookie jar. @type response: L{twisted.web.iweb.IResponse} @param response: Twisted Web response. @param request: A urllib2 compatible request object. )ryrextract_cookies)r>r{rrespr'r'r(rLs zCookieAgent._extractCookiesr])r0r1r2r3r?rrr'r'r'r(rs   rc@r) GzipDecoderz A wrapper for a L{Response} instance which handles gzip'ed body. @ivar original: The original L{Response} object. @since: 11.1 cCs||_t|_dSrR)originalrrr|r'r'r(r?crzGzipDecoder.__init__cCs|jt||jdS)zf Override C{deliverBody} to wrap the given C{protocol} with L{_GzipProtocol}. N)r deliverBody _GzipProtocol)r>r r'r'r(rgszGzipDecoder.deliverBodyN)r0r1r2r3r?rr'r'r'r(rZs rc@r) 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 cCs"||_||_tdtj|_dS)N)r _responsezlib decompressobj MAX_WBITS_zlibDecompress)r>r r{r'r'r(r?|sz_GzipProtocol.__init__cCsJz|j|}Wntjyttg|jw|r#|j|dSdS)zz Decompress C{data} with the zlib decompressor, forwarding the raw data to the original protocol. N) r decompressrrrprrr dataReceived)r>datarawDatar'r'r(rsz_GzipProtocol.dataReceivedcCsRz|j}Wntjyt|tg|jw|r!|j||j |dS)zr Forward the connection lost event, flushing remaining data from the decompressor if any. N) rflushrrrprrrrconnectionLost)r>rrr'r'r(rs z_GzipProtocol.connectionLostNr0r1r2r3r?rrr'r'r'r(ros   rc@r) ContentDecoderAgenta An L{Agent} wrapper to handle encoded content. It takes care of declaring the support for content in the I{Accept-Encoding} header and automatically decompresses the received data if the I{Content-Encoding} header indicates a supported encoding. For example:: agent = ContentDecoderAgent(Agent(reactor), [(b'gzip', GzipDecoder)]) @param agent: The agent to wrap @type agent: L{IAgent} @param decoders: A sequence of (name, decoder) objects. The name declares which encoding the decoder supports. The decoder must accept an L{IResponse} and return an L{IResponse} when called. The order determines how the decoders are advertised to the server. Names must be unique.not be duplicated. @type decoders: sequence of (L{bytes}, L{callable}) tuples @since: 11.1 @see: L{GzipDecoder} cCs*||_t||_ddd|D|_dS)N,cSsg|]}|dqS)rr')r%decoderr'r'r(rqrrz0ContentDecoderAgent.__init__..)rdict _decodersjoin _supported)r>rXdecodersr'r'r(r?s zContentDecoderAgent.__init__NcCsD|durt}n|}|d|j|j||||}||jS)zv Send a client request which declares supporting compressed content. @see: L{Agent.request}. Nsaccept-encoding)rrArBrrrr_handleResponser>rrJr;rdeferredr'r'r(rs  zContentDecoderAgent.requestcCs|jdg}d|d}|r.|}|j|}|dur&||}n||n|s|r=|j dd|g|S|j d|S)zX Check if the response is encoded, and wrap it to handle decompression. scontent-encodingrN) r;rsrsplitrr7rr r! setRawHeaders removeHeader)r>r{contentEncodingHeadersrirr'r'r(rs"       z#ContentDecoderAgent._handleResponser])r0r1r2r3r?rrr'r'r'r(rs   r)s AuthorizationsCookiesCookie2sProxy-AuthorizationsWWW-Authenticatec@sneZdZdZejejejejgZ ej gZ  dde de deefddZdd d Zd d ZddZddZd S) RedirectAgenta An L{Agent} wrapper which handles HTTP redirects. The implementation is rather strict: 301 and 302 behaves like 307, not redirecting automatically on methods different from I{GET} and I{HEAD}. See L{BrowserLikeRedirectAgent} for a redirecting Agent that behaves more like a web browser. @param redirectLimit: The maximum number of times the agent is allowed to follow redirects before failing with a L{error.InfiniteRedirection}. @param sensitiveHeaderNames: An iterable of C{bytes} enumerating the names of headers that must not be transmitted when redirecting to a different origins. These will be consulted in addition to the protocol-specified set of headers that contain sensitive information. @cvar _redirectResponses: A L{list} of HTTP status codes to be redirected for I{GET} and I{HEAD} methods. @cvar _seeOtherResponses: A L{list} of HTTP status codes to be redirected for any method and the method altered to I{GET}. @since: 11.1 rr'rX redirectLimitsensitiveHeaderNamescCs.||_||_dd|D}|t||_dS)NcSsh|]}t|qSr')_canonicalHeaderName)r%eachr'r'r( rrz)RedirectAgent.__init__..)r_redirectLimitupdate_defaultSensitiveHeaders_sensitiveHeaderNames)r>rXrr sensitiver'r'r(r?s   zRedirectAgent.__init__NcCs&|j||||}||j|||dS)zb Send a client request following HTTP redirects. @see: L{Agent.request}. r)rrrrrr'r'r(rszRedirectAgent.requestcCs t||S)a2 Resolve the redirect location against the request I{URI}. @type requestURI: C{bytes} @param requestURI: The request I{URI}. @type location: C{bytes} @param location: The redirect location. @rtype: C{bytes} @return: Final resolved I{URI}. )rZ)r> requestURIlocationr'r'r(_resolveLocation(s zRedirectAgent._resolveLocationcs|jkrtjjd|d}tt|gjdg}|s/tjd|}tt|g ||d}|rdt |} t |} | j | j koT| j | j koT| j| jk} | sdtfdd|D}j|||} fdd } | | | j||||d S) z Handle a redirect response, checking the number of redirects already followed, and extracting the location header fields. sInfinite redirection detectedrslocationsNo location header fieldrcs i|] \}}|jvr||qSr')r)r%rawNamerawValuerMr'r( Rs  z1RedirectAgent._handleRedirect..cs||SrR)setPreviousResponse) newResponserzr'r(_chainResponseZs z5RedirectAgent._handleRedirect.._chainResponserD)rrInfiniteRedirectioncoderprr;rsRedirectWithNoLocationrr4rLr5r8r9rgetAllRawHeadersrrrr)r>r{rrJr; redirectCounterrlocationHeadersrr7parsedLocation sameOriginrrr')r{r>r(_handleRedirect7s@         zRedirectAgent._handleRedirectcCsh|j|jvr#|dvrtj|j|d}tt|g|||||||S|j|jvr2||d|||S|S)zY Handle the response, making another request if it indicates a redirect. )rrrr)r_redirectResponsesr PageRedirectrprr_seeOtherResponses)r>r{rrJr;rrr'r'r(rcs  zRedirectAgent._handleResponse)rr'r])r0r1r2r3rMOVED_PERMANENTLYFOUNDTEMPORARY_REDIRECTPERMANENT_REDIRECTr SEE_OTHERrrrGrrr?rrrrr'r'r'r(rs*   ,rc@s,eZdZdZejgZejejej ej gZ dS)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) r0r1r2r3rrrrrrrrr'r'r'r(rqs rc@r) _ReadBodyProtocolak Protocol that collects data sent to it. This is a helper for L{IResponse.deliverBody}, which collects the body and fires a deferred with it. @ivar deferred: See L{__init__}. @ivar status: See L{__init__}. @ivar message: See L{__init__}. @ivar dataBuffer: list of byte-strings received @type dataBuffer: L{list} of L{bytes} cCs||_||_||_g|_dS)a# @param status: Status of L{IResponse} @ivar status: L{int} @param message: Message of L{IResponse} @type message: L{bytes} @param deferred: deferred to fire when response is complete @type deferred: L{Deferred} firing with L{bytes} N)rstatusmessage dataBuffer)r>rrrr'r'r(r?s  z_ReadBodyProtocol.__init__cCs|j|dS)z? Accumulate some more bytes from the response. N)rr!)r>rr'r'r(rsz_ReadBodyProtocol.dataReceivedcCs`|tr|jd|jdS|tr(|jt|j |j d|jdS|j|dS)z Deliver the accumulated response bytes to the waiting L{Deferred}, if the response body has been completely received without error. rON) rrorcallbackrrrierrbackr/rr)r>rr'r'r(rs  z _ReadBodyProtocol.connectionLostNrr'r'r'r(rs  rr{rcspdtjddffdd }t|}t|j|j|fdd|jdur6dur6tjdt d d |S) a Get the body of an L{IResponse} and return it as a byte string. This is a helper function for clients that don't want to incrementally receive the body of an HTTP response. @param response: The HTTP response for which the body will be read. @type response: L{IResponse} provider @return: A L{Deferred} which will fire with the body of the response. Cancelling it will close the connection to the server immediately. rrNcs}|dur |dSdS)z Cancel a L{readBody} call, close the connection to the HTTP server immediately, if it is still open. @param deferred: The cancelled L{defer.Deferred}. Nr')rr()getAbortr'r(r s zreadBody..cancelcstjddS)NabortConnection)getattrrr'rr'r(rszreadBody..getAbortzLUsing readBody with a transport that does not have an abortConnection methodr)rPrO) r rrrphraserrrRrSrT)r{r rr')rr r(readBodys   r)rNrrrrrrr/r^rrrkrmrnrorprqr4rR)vr3rrrRr functoolsrtypingr urllib.parserrrr*zope.interfacer incrementalrr^r r r twisted.internet.abstractr twisted.internet.endpointsr rtwisted.internet.interfacesrrtwisted.loggerrtwisted.python.compatrrtwisted.python.componentsrtwisted.python.deprecaterrtwisted.python.failurer twisted.webrrtwisted.web._newclientrrtwisted.web.http_headersrtwisted.web.iwebrrrr r!r"Errorr/r4rZrgrhrirjrkrlrmrnrorprqrrtwisted.web.errorrsOpenSSLrt ImportErrortwisted.internet.sslrurvrwr}r~rrr1r0rrrrFactoryrrrr.rDrNr^r`ryrrrr_canonicalNameCapsr frozensetrrrProtocolrrrr__all__r'r'r'r(s           r 4"  &   @'o@EJ'EB,G 6 ,