ϪfNdZddlZddlmZddlmZmZmZmZm Z ddl m Z ddl m Z mZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZmZm Z m!Z!m"Z"m#Z#ddl$m%Z%ddl&m'Z'm(Z(m)Z)dZ*dZ+dZ,dZ-eZ.Gdde/Z0Gdde/Z1Gdde/Z2Gdde2Z3Gdde/Z4Gdd e4Z5Gd!d"e4Z6Gd#d$e/Z7Gd%d&e/Z8Gd'd(e/Z9Gd)d*e4Z:Gd+d,e:Z;Gd-d.e/ZGd2d3e>Z?ejd4eAjd5fzZCd6ZDejd7ZEd8ZFee(Gd9d:ZGGd;d<ZHd=ZIee(ZJee)Gd>d?ZKee Gd@dAZLeeGdBdCZMGdDdEeZNy)Fa An U{HTTP 1.1} client. The way to use the functionality provided by this module is to: - Connect a L{HTTP11ClientProtocol} to an HTTP server - Create a L{Request} with the appropriate data - Pass the request to L{HTTP11ClientProtocol.request} - The returned Deferred will fire with a L{Response} object - Create a L{IProtocol} provider which can handle the response body - Connect it to the response with L{Response.deliverBody} - When the protocol's C{connectionLost} method is called, the response is complete. See L{Response.deliverBody} for details. Various other classes in this module support this usage: - HTTPParser is the basic HTTP parser. It can handle the parts of HTTP which are symmetric between requests and responses. - HTTPClientParser extends HTTPParser to handle response-specific parts of HTTP. One instance is created for each request to parse the corresponding response. N) implementer)CancelledErrorDeferredfail maybeDeferredsucceed)ConnectionDone) IConsumer IPushProducer)Protocol)Logger) LineReceiver) networkString)proxyForInterface)Failure)fullyQualifiedName) NO_CONTENT NOT_MODIFIEDPotentialDataLoss_ChunkedTransferDecoder _DataLoss_IdentityTransferDecoder)Headers)UNKNOWN_LENGTHIClientRequest IResponseSTATUSHEADERBODYDONEceZdZdZy) BadHeadersz@ Headers passed to L{Request} were in some way invalid. N__name__ __module__ __qualname____doc__8/usr/lib/python3/dist-packages/twisted/web/_newclient.pyr"r"Dr)r"ceZdZdZy) ExcessWritezx The body L{IBodyProducer} for a request tried to write data after indicating it had finished writing data. Nr#r(r)r*r-r-Jsr)r-ceZdZdZdZy) ParseErrorzh Some received data could not be parsed. @ivar data: The string which could not be parsed. c@tj|||||_yN) Exception__init__data)selfreasonr4s r*r3zParseError.__init__Xs4. r)Nr$r%r&r'r3r(r)r*r/r/Qs  r)r/ceZdZdZy)BadResponseVersionz= The version string in a status line was unparsable. Nr#r(r)r*r9r9]r+r)r9ceZdZdZdZy)_WrapperExceptiona, L{_WrapperException} is the base exception type for exceptions which include one or more other exceptions as the low-level causes. @ivar reasons: A L{list} of one or more L{Failure} instances encountered during an HTTP request. See subclass documentation for more details. c>tj||||_yr1)r2r3reasons)r5r=s r*r3z_WrapperException.__init__ls4) r)Nr7r(r)r*r;r;cs r)r;ceZdZdZy)RequestGenerationFailedz There was an error while creating the bytes which make up a request. @ivar reasons: A C{list} of one or more L{Failure} instances giving the reasons the request generation was considered to have failed. Nr#r(r)r*r?r?qr)r?ceZdZdZy)RequestTransmissionFailedz There was an error while sending the bytes which make up a request. @ivar reasons: A C{list} of one or more L{Failure} instances giving the reasons the request transmission was considered to have failed. Nr#r(r)r*rBrBzr@r)rBceZdZdZy)ConnectionAbortedzD The connection was explicitly aborted by application code. Nr#r(r)r*rDrDr+r)rDceZdZdZy)WrongBodyLengthz An L{IBodyProducer} declared the number of bytes it was going to produce (via its C{length} attribute) and then produced a different number of bytes. Nr#r(r)r*rFrFr)rFceZdZdZy) ResponseDonez L{ResponseDone} may be passed to L{IProtocol.connectionLost} on the protocol passed to L{Response.deliverBody} and indicates that the entire response has been delivered. Nr#r(r)r*rIrIrGr)rIceZdZdZddZy)ResponseFaileda L{ResponseFailed} indicates that all of the response to a request was not received for some reason. @ivar reasons: A C{list} of one or more L{Failure} instances giving the reasons the response was considered to have failed. @ivar response: If specified, the L{Response} received from the server (and in particular the status code and the headers). Nc>tj||||_yr1)r;r3response)r5r=rMs r*r3zResponseFailed.__init__s""41  r)r1r7r(r)r*rKrKs  !r)rKceZdZdZy)ResponseNeverReceivedzU A L{ResponseFailed} that knows no response bytes at all have been received. Nr#r(r)r*rOrOr+r)rOceZdZdZy)RequestNotSentaF L{RequestNotSent} indicates that an attempt was made to issue a request but for reasons unrelated to the details of the request itself, the request could not be sent. For example, this may indicate that an attempt was made to send a request using a protocol which is no longer connected to a server. Nr#r(r)r*rQrQsr)rQcr |y#t$r#tjdt|YywxYw)z Call C{function}. If it raises an exception, log it with a minimal description of the source. @return: L{None} z Unexpected exception from {name})nameN) BaseException _moduleLogfailurer)functions r*_callAppFunctionrXs9    .5G5Q   s  )66cLeZdZdZdZhdZdZdZdZdZ dZ d Z d Z d Z y ) HTTPParsera L{HTTPParser} handles the parsing side of HTTP processing. With a suitable subclass, it can parse either the client side or the server side of the connection. @ivar headers: All of the non-connection control message headers yet received. @ivar state: State indicator for the response parsing state machine. One of C{STATUS}, C{HEADER}, C{BODY}, C{DONE}. @ivar _partialHeader: L{None} or a C{list} of the lines of a multiline header while that header is being received.  >teupgradetrailers keep-aliveproxy-connection connectioncontent-lengthtransfer-encodingcdt|_t|_t|_d|_yr1)rheaders connHeadersrstate_partialHeaderr5s r*connectionMadezHTTPParser.connectionMades$y "9 "r)c|jtk(r td||_t|_|j y)z Switch to body parsing mode - interpret any more bytes delivered as part of the message body and deliver them to the given decoder. zalready in body modeN)rgr RuntimeError bodyDecoder setRawMode)r5decoders r*switchToBodyModezHTTPParser.switchToBodyModes5 :: 56 6"  r)c|dddk(r|dd}|jtk(r|j|t|_y|jtk(r|r|ddvrz|jRdj |j}|j dd\}}|j}|j|||s|jy|g|_y|jj|yy) z2 Handle one line from a response. N rs r):) rgrstatusReceivedrrhjoinsplitstripheaderReceivedallHeadersReceivedappend)r5lineheaderrSvalues r* lineReceivedzHTTPParser.lineReceived s 9 9D ::     %DJ ZZ6 !47&0&&2 XXd&9&9:F"(,,tQ"7KD%!KKME''e4++-,0&D'##**40!"r)c:|jj|y)zM Pass data from the message body to the body decoder object. N)rm dataReceivedr5r4s r*rawDataReceivedzHTTPParser.rawDataReceived*s %%d+r)c||jvS)a Return C{True} if the given lower-cased name is the name of a connection control header (rather than an entity header). According to RFC 2616, section 14.10, the tokens in the Connection header are probably relevant here. However, I am not sure what the practical consequences of either implementing or ignoring that are. So I leave it unimplemented for the time being. )CONNECTION_CONTROL_HEADERSr5rSs r*isConnectionControlHeaderz$HTTPParser.isConnectionControlHeader0st6666r)cy)a Callback invoked whenever the first line of a new message is received. Override this. @param status: The first line of an HTTP request or response message without trailing I{CR LF}. @type status: C{bytes} Nr()r5statuss r*rvzHTTPParser.statusReceived<r)c|j}|j|r |j}n |j}|j ||y)z< Store the given header in C{self.headers}. N)lowerrrfre addRawHeader)r5rSrres r*rzzHTTPParser.headerReceivedFsAzz|  ) )$ /&&GllGT5)r)c&|jdy)z Callback invoked after the last header is passed to C{headerReceived}. Override this to change to the C{BODY} or C{DONE} state. N)rpris r*r{zHTTPParser.allHeadersReceivedQs d#r)N)r$r%r&r' delimiterrrjrprrrrvrzr{r(r)r*rZrZs? HI "# 1:, 7  *$r)rZcbeZdZdZeehZdeiZdZ e Z dZ dZ dZdZdZd Zd Zd Zy) HTTPClientParseraL An HTTP parser which only handles HTTP responses. @ivar request: The request with which the expected response is associated. @type request: L{Request} @ivar NO_BODY_CODES: A C{set} of response codes which B{MUST NOT} have a body. @ivar finisher: A callable to invoke when this response is fully parsed. @ivar _responseDeferred: A L{Deferred} which will be called back with the response when all headers in the response have been received. Thereafter, L{None}. @ivar _everReceivedData: C{True} if any bytes have been received. schunkedNcL||_||_t|_d|_y)NF)requestfinisherr_responseDeferred_everReceivedData)r5rrs r*r3zHTTPClientParser.__init__us"   !)!&r)c>d|_tj||y)zM Override so that we know if any response has been received. TN)rrZrrs r*rzHTTPClientParser.dataReceived{s"&d+r)c |jd\}}|jd\}}t|t|}}|dks|dkr td||||fS#t$r}tt ||d}~wwxYw)z Parse version strings of the form Protocol '/' Major '.' Minor. E.g. b'HTTP/1.1'. Returns (protocol, major, minor). Will raise ValueError on bad syntax. /.Nrzversion may not be negative)rxint ValueErrorr9str)r5 strversionproto strnumbermajorminores r* parseVersionzHTTPClientParser.parseVersions  9)//5 E9$??40LE5u:s5z5E 19 $%BJO Oue$$  9$SVZ8 8 9s>A A>$A99A>cx|jdd}t|dk(r|\}}d}n!t|dk(r|\}}}n td| t|}t j |j||||j|j|j|_ y#t$r td|wxYw)z Parse the status line into its components and create a response object to keep track of this response's state.  r)zwrong number of partsznon-integer status codeN) rxlenr/rrResponse _constructrre transportrrM)r5rpartsversion codeBytesphrase statusCodes r*rvzHTTPClientParser.statusReceiveds  T1% u:? "' GYF Z1_). &GY4f= = @YJ!++   g &   LL NN LL    @6? ? @s B##B9c<t|_|j|y)a Called to indicate that an entire response has been received. No more bytes will be interpreted by this L{HTTPClientParser}. Extra bytes are passed up and the state of this L{HTTPClientParser} is set to I{DONE}. @param rest: A C{bytes} giving any extra bytes delivered to this L{HTTPClientParser} which are not part of the response being parsed. N)r rgrr5rests r* _finishedzHTTPClientParser._finisheds  dr)cl|jjdk(r|dk(rytj||S)z Content-Length in the response to a HEAD request is an entity header, not a connection control header. HEADrbF)rmethodrZrrs r*rz*HTTPClientParser.isConnectionControlHeaders4 <<  ' )d6G.G33D$??r)cd|jjcxkrdkrGnnD|jjd|jj|j |`y|jj|j vs|j jdk(rLd|j_|j|j|jjn0|jjd}|r!|j|dj}n|jjd }|dn9t!|d k(r t#|d|j_n t%d dk(r"|j|jd}nfd }||jjnP|j&j)|j+||jj,|j|j.j1|j|`y) zn Figure out how long the response body is going to be by examining headers and stuff. dz#Ignoring unexpected {code} response)codeNrrrcrbruz4Too many Content-Length headers; response is invalidct||Sr1)r)xy contentLengths r*z5HTTPClientParser.allHeadersReceived..s3K%q!4r))rMr_loginforj NO_BODY_CODESrrlengthrclearLineBuffer_bodyDataFinishedrf getRawHeaders_transferDecodersrrrrrpauseProducingrp_bodyDataReceivedrcallback)r5transferEncodingHeaderstransferDecodercontentLengthHeadersrs @r*r{z#HTTPClientParser.allHeadersReceiveds $--$$ *s * IINN5DMM6(3K+L M&  )?MM33GI> MM33 /BDMM RS ! &  !!"%  &s;B!D!,D DA DDDD$EE)r$r%r&r'rrrrrrmr rr3rrrvrrr{rr(r)r*rrYs]$ .M +K 8D' ,%  @ @T#l'r)rs \A[%s]+\Z)!#$%&'*+-r^_`|~s0-9sA-Zsa-zcLtj|r|Std|)a  An HTTP method is an HTTP token, which consists of any visible ASCII character that is not a delimiter (i.e. one of C{"(),/:;<=>?@[\]{}}.) @param method: the method to check @type method: L{bytes} @return: the method if it is valid @rtype: L{bytes} @raise ValueError: if the method is not valid @see: U{https://tools.ietf.org/html/rfc7230#section-3.1.1}, U{https://tools.ietf.org/html/rfc7230#section-3.2.6}, U{https://tools.ietf.org/html/rfc5234#appendix-B.1} zInvalid method ) _VALID_METHODmatchr)rs r*_ensureValidMethodrWs)$6" vj1 22r)s\A[\x21-\x7e]+\ZcLtj|r|Std|)a A valid URI cannot contain control characters (i.e., characters between 0-32, inclusive and 127) or non-ASCII characters (i.e., characters with values between 128-255, inclusive). @param uri: the URI to check @type uri: L{bytes} @return: the URI if it is valid @rtype: L{bytes} @raise ValueError: if the URI is not valid @see: U{https://tools.ietf.org/html/rfc3986#section-3.3}, U{https://tools.ietf.org/html/rfc3986#appendix-A}, U{https://tools.ietf.org/html/rfc5234#appendix-B.1} z Invalid URI ) _VALID_URIrr)uris r*_ensureValidURIrqs)$ |C7+ ,,r)cneZdZdZeZd dZe d dZe dZ dZ dZ dZ d Zd Zd Zy)Requesta A L{Request} instance describes an HTTP request to be sent to an HTTP server. @ivar method: See L{__init__}. @ivar uri: See L{__init__}. @ivar headers: See L{__init__}. @ivar bodyProducer: See L{__init__}. @ivar persistent: See L{__init__}. @ivar _parsedURI: Parsed I{URI} for the request, or L{None}. @type _parsedURI: L{twisted.web.client.URI} or L{None} c|t||_t||_||_||_||_d|_y)at @param method: The HTTP method for this request, ex: b'GET', b'HEAD', b'POST', etc. @type method: L{bytes} @param uri: The relative URI of the resource to request. For example, C{b'/foo/bar?baz=quux'}. @type uri: L{bytes} @param headers: Headers to be sent to the server. It is important to note that this object does not create any implicit headers. So it is up to the HTTP Client to add required headers such as 'Host'. @type headers: L{twisted.web.http_headers.Headers} @param bodyProducer: L{None} or an L{IBodyProducer} provider which produces the content body to send to the remote HTTP server. @param persistent: Set to C{True} when you use HTTP persistent connection, defaults to C{False}. @type persistent: L{bool} N)rrrrre bodyProducer persistent _parsedURI)r5rrrerrs r*r3zRequest.__init__s9,)0 "3' ($r)Nc,||||||}||_|S)aS Private constructor. @param method: See L{__init__}. @param uri: See L{__init__}. @param headers: See L{__init__}. @param bodyProducer: See L{__init__}. @param persistent: See L{__init__}. @param parsedURI: See L{Request._parsedURI}. @return: L{Request} instance. )r)clsrrrerr parsedURIrs r*rzRequest._constructs# fc7L*E&r)c<t|jddS)z{ The absolute URI of the request as C{bytes}, or L{None} if the absolute URI cannot be determined. toBytescyr1r(r(r)r*rz%Request.absoluteURI..rr))getattrrris r* absoluteURIzRequest.absoluteURIs Awt <@BBr)cF|jjdd}t|dk7r tdg}|j dj t |jt|jdg|js|j d||j ||jjD]-\}}|j|Dcgc] }|dz|zd zc}/|j d |j|ycc}w) Nshostr(ruz Exactly one Host header requiredrs HTTP/1.1 sConnection: close s:  )rerrr"r|rwrrrrrgetAllRawHeadersextend writeSequence)r5rTEorCLhosts requestLinesrSvaluesvs r* _writeHeaderszRequest._writeHeaderss **7B7 u:??@ @   II&t{{3#DHH-#      8 9      ' LL99; NLD&   V L!1G!; L M NG$ -!Ms D c|jdtj|jd|jj }fd}fd}|j |||S)z Write this request to the given transport using chunked transfer-encoding to frame the body. @param transport: See L{writeTo}. @return: See L{writeTo}. sTransfer-Encoding: chunked Tc&jyr1unregisterProducer)ignoredencoders r* cbProducedz7Request._writeToBodyProducerChunked..cbProduceds  & & (r)cHjj|Sr1)_allowNoMoreWritesr )errr rs r* ebProducedz7Request._writeToBodyProducerChunked..ebProduceds"  & & (  ( ( *Jr))rChunkedEncoderregisterProducerrstartProducing addCallbacks)r5rdr rr s ` @r*_writeToBodyProducerChunkedz#Request._writeToBodyProducerChunkedsk 9&GH +  !2!2D9    , ,W 5 )  z:.r)cpjtdjjfzt }t j|j jdjjfd}||}fd}|j||S)z Write this request to the given transport using content-length to frame the body. @param transport: See L{writeTo}. @return: See L{writeTo}. zContent-Length: %d Tc fd}t|dg fd}fd} fd}|j||j||S)Nc&jyr1)cancel)ignfinishedProducings r*cancelConsumingzSRequest._writeToBodyProducerContentLength..combine..cancelConsuming+s!((*r)cdgk(rdd<j|yjjd|tdy)Nrurz>Buggy state machine in {request}/[{state}]: ebConsuming called)rVrrg)rrrVrepr)rr5rgultimates r* ebConsumingzORequest._writeToBodyProducerContentLength..combine..ebConsuming6sTTF? !E!H$$S) II%%- # $T #Ah &r)cdgk(r(dd< jjdyy#t$rjYywxYw)Nrr)_noMoreWritesExpectedrrTr)resultr rgr s r* cbProducingzORequest._writeToBodyProducerContentLength..combine..cbProducingMs\TF? !E!H0557!))$/#)+!((*+s1A  A cdgk(r'dd<jj|yjjd|y)NrrzProducer is buggy)rV)rrrrV)rr r5rgr s r* ebProducingzORequest._writeToBodyProducerContentLength..combine..ebProducingbsKTF? !E!H..0$$S) II%%&93%Gr))r addErrbackr) consuming producingrr!r%r'rgr r rr5s @@r*combinez:Request._writeToBodyProducerContentLength..combine'sR + 0H FE . 0* H"   -  " "; <Or)c(j|Sr1r) passthroughrs r*fz4Request._writeToBodyProducerContentLength..fzs  ( ( * r)) rrrrrLengthEnforcingConsumerrraddBoth)r5rfinishedConsumingr+rr.r rs`` @@r*!_writeToBodyProducerContentLengthz)Request._writeToBodyProducerContentLength s   2d6G6G6N6N5PP Q %J*   y*;  ""4#4#4d; --<?t}r)c|j3|jdvr|j|y|j|dy|jjt ur|j |S|j|S)a  Format this L{Request} as an HTTP/1.1 request and write it to the given transport. If bodyProducer is not None, it will be associated with an L{IConsumer}. @param transport: The transport to which to write. @type transport: L{twisted.internet.interfaces.ITransport} provider @return: A L{Deferred} which fires with L{None} when the request has been completely written to the transport or with a L{Failure} if there is any problem generating the request bytes. N)sPUTsPOST)rrr5rrrrr2r4s r*writeTozRequest.writeToss    ${{//33I>""9d3    % % 733I> >99)D Dr)cBt|jjy)aR Stop writing this request to the transport. This can only be called after C{writeTo} and before the L{Deferred} returned by C{writeTo} fires. It should cancel any asynchronous task started by C{writeTo}. The L{Deferred} returned by C{writeTo} need not be fired if this method is called. N)rXr stopProducingris r* stopWritingzRequest.stopWritings **889r))F)FN)r$r%r&r'r rr3 classmethodrpropertyrrrr2r5r7r:r(r)r*rrsc  8D:MQ&CC.68xt E4 :r)rc(eZdZdZdZdZdZdZy)r/a An L{IConsumer} proxy which enforces an exact length requirement on the total data written to it. @ivar _length: The number of bytes remaining to be written. @ivar _producer: The L{IBodyProducer} which is writing to this consumer. @ivar _consumer: The consumer to which at most C{_length} bytes will be forwarded. @ivar _finished: A L{Deferred} which will be fired with a L{Failure} if too many bytes are written to this consumer. cP|j|_||_||_||_yr1)r_length _producer _consumerr)r5producerconsumerfinisheds r*r3z LengthEnforcingConsumer.__init__s" !!!r)cd|_yz Indicate that no additional writes are allowed. Attempts to write after calling this method will be met with an exception. N)rris r*rz*LengthEnforcingConsumer._allowNoMoreWrites r)c|j$|jjtt ||j kr:|xj t |zc_|j j|yt|jj|jjtd|jy)z Write C{bytes} to the underlying consumer unless C{_noMoreWritesExpected} has been called or there are/have been too many bytes. Nztoo many bytes written) rr@r9r-rr?rAwriterXrrFrr5bytess r*rIzLengthEnforcingConsumer.writes >> ! NN ( ( *-  u: % LLCJ &L NN  ' T^^99 : NN " "?3K#L M  # # %r)cl|j(|j|jr tdyy)z Called to indicate no more bytes will be written to this consumer. Check to see that the correct number have been written. @raise WrongBodyLength: If not enough bytes have been written. Nztoo few bytes written)rrr?rFris r*r#z-LengthEnforcingConsumer._noMoreWritesExpecteds7 >> %  # # %||%&=>> &r)N)r$r%r&r'r3rrIr#r(r)r*r/r/s " &8 ?r)r/c4fd}|j|_|S)a} Given a I{dispatch} name and a function, return a function which can be used as a method and which, when called, will call another method defined on the instance and return the result. The other method which is called is determined by the value of the C{_state} attribute of the instance. @param name: A string which is used to construct the name of the subsidiary method to invoke. The subsidiary method is named like C{'_%s_%s' % (name, _state)}. @param template: A function object which is used to give the returned function a docstring. @return: The dispatcher function. ct|dzdz|jzd}|t|dd|j||i|S)N_z has no z method in state )r_staterl)r5argskwargsfuncrSs r* dispatcherz*makeStatefulDispatcher..dispatchersYtS4Z#- ;TB <$$7H VW WT$V$$r))r')rStemplaterTs` r*makeStatefulDispatcherrVs"% "))J r)ceZdZdZeZdZdZdZe dZ dZ dZ e de Z d Zd Zd Zd Zd Ze deZdZdZdZdZddZe deZddZddZdZdZy)ra A L{Response} instance describes an HTTP response received from an HTTP server. L{Response} should not be subclassed or instantiated. @ivar _transport: See L{__init__}. @ivar _bodyProtocol: The L{IProtocol} provider to which the body is delivered. L{None} before one has been registered with C{deliverBody}. @ivar _bodyBuffer: A C{list} of the strings passed to C{bodyDataReceived} before C{deliverBody} is called. L{None} afterwards. @ivar _state: Indicates what state this L{Response} instance is in, particularly with respect to delivering bytes from the response body to an application-supplied protocol object. This may be one of C{'INITIAL'}, C{'CONNECTED'}, C{'DEFERRED_CLOSE'}, or C{'FINISHED'}, with the following meanings: - INITIAL: This is the state L{Response} objects start in. No protocol has yet been provided and the underlying transport may still have bytes to deliver to it. - DEFERRED_CLOSE: If the underlying transport indicates all bytes have been delivered but no application-provided protocol is yet available, the L{Response} moves to this state. Data is buffered and waiting for a protocol to be delivered to. - CONNECTED: If a protocol is provided when the state is INITIAL, the L{Response} moves to this state. Any buffered data is delivered and any data which arrives from the transport subsequently is given directly to the protocol. - FINISHED: If a protocol is provided in the DEFERRED_CLOSE state, the L{Response} moves to this state after delivering all buffered data to the protocol. Otherwise, if the L{Response} is in the CONNECTED state, if the transport indicates there is no more data, the L{Response} moves to this state. Nothing else can happen once the L{Response} is in this state. @type _state: C{str} NFc||_||_||_||_||_g|_d|_d|_d|_y)a @param version: HTTP version components protocol, major, minor. E.g. C{(b'HTTP', 1, 1)} to mean C{b'HTTP/1.1'}. @param code: HTTP status code. @type code: L{int} @param phrase: HTTP reason phrase, intended to give a short description of the HTTP status code. @param headers: HTTP response headers. @type headers: L{twisted.web.http_headers.Headers} @param _transport: The transport which is delivering this response. INITIALN) rrrre _transport _bodyBufferrPrpreviousResponse)r5rrrrerZs r*r3zResponse.__init__RsE     $  $r)cDt|||||}t||_|S)aM Private constructor. @param version: See L{__init__}. @param code: See L{__init__}. @param phrase: See L{__init__}. @param headers: See L{__init__}. @param _transport: See L{__init__}. @param request: See L{IResponse.request}. @return: L{Response} instance. )r_ClientRequestProxyr)rrrrrerZrrMs r*rzResponse._constructls(GT67JG.w7r)c||_yr1)r\)r5r\s r*setPreviousResponsezResponse.setPreviousResponse~s 0r)cy)zi Dispatch the given L{IProtocol} depending of the current state of the response. Nr(r5protocols r* deliverBodyzResponse.deliverBodyrr)rdc|j|j||_|jD]}|jj |d|_d|_|jj y)z Deliver any buffered data to C{protocol} and prepare to deliver any future data to it. Move to the C{'CONNECTED'} state. N CONNECTED)makeConnectionrZ _bodyProtocolr[rrPresumeProducingr5rcr4s r*_deliverBody_INITIALzResponse._deliverBody_INITIALsh 0%$$ 2D    + +D 1 2!  '')r)c4td|jd)z It is invalid to attempt to deliver data to a protocol when it is already being delivered to another protocol. zResponse already has protocol z, cannot deliverBody again)rlrhrbs r*_deliverBody_CONNECTEDzResponse._deliverBody_CONNECTEDs )) ,  r)c|j|j|jD]}|j|d|_|j |j d|_y)z Deliver any buffered data to C{protocol} and then disconnect the protocol. Move to the C{'FINISHED'} state. NFINISHED)rgrZr[rr_reasonrPrjs r*_deliverBody_DEFERRED_CLOSEz$Response._deliverBody_DEFERRED_CLOSEsZ 0$$ (D  ! !$ ' ( -  r)ctd)z It is invalid to attempt to deliver data to a protocol after the response body has been delivered to another protocol. z2Response already finished, cannot deliverBody now.rlrbs r*_deliverBody_FINISHEDzResponse._deliverBody_FINISHEDs OPPr)cy)z Called by HTTPClientParser with chunks of data from the response body. They will be buffered or delivered to the protocol passed to deliverBody. Nr(rs r*rzResponse._bodyDataReceivedrr)bodyDataReceivedc:|jj|y)a Buffer any data received for later delivery to a protocol passed to C{deliverBody}. Little or no data should be buffered by this method, since the transport has been paused and will not be resumed until a protocol is supplied. N)r[r|rs r*_bodyDataReceived_INITIALz"Response._bodyDataReceived_INITIALs %r)c:|jj|y)zk Deliver any data received to the protocol to which this L{Response} is connected. N)rhrrs r*_bodyDataReceived_CONNECTEDz$Response._bodyDataReceived_CONNECTEDs ''-r)ctd)z It is invalid for data to be delivered after it has been indicated that the response body has been completely delivered. z0Cannot receive body data after _bodyDataFinishedrsrs r* _bodyDataReceived_DEFERRED_CLOSEz)Response._bodyDataReceived_DEFERRED_CLOSEs MNNr)ctd)zz It is invalid for data to be delivered after the response body has been delivered to a protocol. z4Cannot receive body data after protocol disconnectedrsrs r*_bodyDataReceived_FINISHEDz#Response._bodyDataReceived_FINISHEDs TUUr)cy)z Called by HTTPClientParser when no more body data is available. If the optional reason is supplied, this indicates a problem or potential problem receiving all of the response body. Nr(r5r6s r*rzResponse._bodyDataFinishedrr)bodyDataFinishedcLd|_|ttd}||_y)z} Move to the C{'DEFERRED_CLOSE'} state to wait for a protocol to which to deliver the response body. DEFERRED_CLOSENResponse body fully received)rPrrIrprs r*_bodyDataFinished_INITIALz"Response._bodyDataFinished_INITIALs' ' >\*HIJF r)c|ttd}|jj|d|_d|_y)zN Disconnect the protocol and move to the C{'FINISHED'} state. Nrro)rrIrhrrPrs r*_bodyDataFinished_CONNECTEDz$Response._bodyDataFinished_CONNECTEDs< >\*HIJF ))&1!  r)ctd) It is invalid to attempt to notify the L{Response} of the end of the response body data more than once. z&Cannot finish body data more than oncersris r* _bodyDataFinished_DEFERRED_CLOSEz)Response._bodyDataFinished_DEFERRED_CLOSEs CDDr)ctd)rz3Cannot finish body data after protocol disconnectedrsris r*_bodyDataFinished_FINISHEDz#Response._bodyDataFinished_FINISHED s STTr)r1)r$r%r&r'rrrh _bodyFinishedr3r;rr`rdrVrkrmrqrtrrxrzr|r~rrrrrr(r)r*rrs*XFMM%4"1 ) DK*( !$Q //ACTU &.OV //ACTU!EUr)rc.eZdZdZdZdZdZdZdZy)rz Helper object which exposes L{IConsumer} on top of L{HTTP11ClientProtocol} for streaming request bodies to the server. c||_yr1rr4s r*r3zChunkedEncoder.__init__s "r)cd|_yrFrris r*rz!ChunkedEncoder._allowNoMoreWritesrGr)c<|jj||y)zE Register the given producer with C{self.transport}. N)rr)r5rB streamings r*rzChunkedEncoder.registerProducer&s '')> !-  $$ 8c$i/ 0$ @ r)cz|jd|jj|jy)zT Indicate that the request body is complete and finish the request. r)N)rIrr rris r*r z!ChunkedEncoder.unregisterProducer9s+ 3 ))+ !r)N) r$r%r&r'r3rrrIr r(r)r*rrs  #=  "r)rc8eZdZdZdZdZdZdZdZdZ dZ y ) TransportProxyProducera' An L{twisted.internet.interfaces.IPushProducer} implementation which wraps another such thing and proxies calls to it until it is told to stop. @ivar _producer: The wrapped L{twisted.internet.interfaces.IPushProducer} provider or L{None} after this proxy has been stopped. Fc||_yr1r@)r5rBs r*r3zTransportProxyProducer.__init__Ts !r)cd|_y)z Stop forwarding calls of L{twisted.internet.interfaces.IPushProducer} methods to the underlying L{twisted.internet.interfaces.IPushProducer} provider. Nrris r* stopProxyingz#TransportProxyProducer.stopProxyingWs r)cR|j|jjyy)zl Proxy the stoppage to the underlying producer, unless this proxy has been stopped. N)r@r9ris r*r9z$TransportProxyProducer.stopProducing_s# >> % NN ( ( * &r)cR|j|jjyy)zn Proxy the resumption to the underlying producer, unless this proxy has been stopped. N)r@riris r*riz&TransportProxyProducer.resumeProducinggs# >> % NN * * , &r)cR|j|jjyy)zi Proxy the pause to the underlying producer, unless this proxy has been stopped. N)r@rris r*rz%TransportProxyProducer.pauseProducingo# >> % NN ) ) + &r)cR|j|jjyy)z Proxy the request to lose the connection to the underlying producer, unless this proxy has been stopped. N)r@loseConnectionris r*rz%TransportProxyProducer.loseConnectionwrr)N) r$r%r&r' disconnectingr3rr9rirrr(r)r*rrBs,M"+-,,r)rceZdZdZdZdZdZdZdZdZ e Z dfdZ e dZdZdZed eZd ZeZd Zd Zd ZdZedeZdZdZdZdZdZdZdZy)HTTP11ClientProtocola( L{HTTP11ClientProtocol} is an implementation of the HTTP 1.1 client protocol. It supports as few features as possible. @ivar _parser: After a request is issued, the L{HTTPClientParser} to which received data making up the response to that request is delivered. @ivar _finishedRequest: After a request is issued, the L{Deferred} which will fire when a L{Response} object corresponding to that request is available. This allows L{HTTP11ClientProtocol} to fail the request if there is a connection or parsing problem. @ivar _currentRequest: After a request is issued, the L{Request} instance used to make that request. This allows L{HTTP11ClientProtocol} to stop request generation if necessary (for example, if the connection is lost). @ivar _transportProxy: After a request is issued, the L{TransportProxyProducer} to which C{_parser} is connected. This allows C{_parser} to pause and resume the transport in a way which L{HTTP11ClientProtocol} can exert some control over. @ivar _responseDeferred: After a request is issued, the L{Deferred} from C{_parser} which will fire with a L{Response} when one has been received. This is eventually chained with C{_finishedRequest}, but only in certain cases to avoid double firing that Deferred. @ivar _state: Indicates what state this L{HTTP11ClientProtocol} instance is in with respect to transmission of a request and reception of a response. This may be one of the following strings: - QUIESCENT: This is the state L{HTTP11ClientProtocol} instances start in. Nothing is happening: no request is being sent and no response is being received or expected. - TRANSMITTING: When a request is made (via L{request}), the instance moves to this state. L{Request.writeTo} has been used to start to send a request but it has not yet finished. - TRANSMITTING_AFTER_RECEIVING_RESPONSE: The server has returned a complete response but the request has not yet been fully sent yet. The instance will remain in this state until the request is fully sent. - GENERATION_FAILED: There was an error while the request. The request was not fully sent to the network. - WAITING: The request was fully sent to the network. The instance is now waiting for the response to be fully received. - ABORTING: Application code has requested that the HTTP connection be aborted. - CONNECTION_LOST: The connection has been lost. @type _state: C{str} @ivar _abortDeferreds: A list of C{Deferred} instances that will fire when the connection is lost. QUIESCENTNcyr1r()cs r*rzHTTP11ClientProtocol.rr)c ||_g|_yr1)_quiescentCallback_abortDeferreds)r5quiescentCallbacks r*r3zHTTP11ClientProtocol.__init__s"3!r)c|jSr1rPris r*rgzHTTP11ClientProtocol.states {{r)c jdk7rttSd_t|jj fd}t |_|_tj _ t|j_ jjjjj_fd}fd}j!||jS)a Issue C{request} over C{self.transport} and return a L{Deferred} which will fire with a L{Response} instance or an error. @param request: The object defining the parameters of the request to issue. @type request: L{Request} @rtype: L{Deferred} @return: The deferred may errback with L{RequestGenerationFailed} if the request was not fully written to the transport due to a local error. It may errback with L{RequestTransmissionFailed} if it was not fully written to the transport due to a network error. It may errback with L{ResponseFailed} if the request was sent (not necessarily received) but some or all of the response was lost. It may errback with L{RequestNotSent} if it is not possible to send any more requests using this L{HTTP11ClientProtocol}. r TRANSMITTINGcjdvrjyjjj t t y)N)r%TRANSMITTING_AFTER_RECEIVING_RESPONSE)rPrrabortConnection_disconnectParserrr)r_requestDeferredr5s r* cancelRequestz3HTTP11ClientProtocol.request..cancelRequestsD{{WW '')..0&&w~/?'@Ar)c~jdk(r-d_jjjyy)NrWAITING)rPr chainDeferred_finishedRequest)r r5s r*cbRequestWrittenz6HTTP11ClientProtocol.request..cbRequestWrittens5{{n,' &&44T5J5JK-r)cjdk(rPd_jjjj t t |gyjjd|jy)NrGENERATION_FAILEDzJError writing request, but not in valid state to finalize request: {state})rVrg) rPrrrrrr?rrV)rr5s r*ebRequestWritingz6HTTP11ClientProtocol.request..ebRequestWritingsm{{n,1 ..0%%--g6Mse6T.UV !!3++ "r))rPrrQrr7rrr_currentRequestr_transportProxyr_finishResponse_parserrgrr)r5rrrrrs` @r*rzHTTP11ClientProtocol.requests& ;;+ %() )$ ($..I B!) 7 '5dnnE'1E1EF  ##D$8$89!%!?!? L  %%&68HI$$$r)cy)a! Called by an L{HTTPClientParser} to indicate that it has parsed a complete response. @param rest: A C{bytes} giving any trailing bytes which were given to the L{HTTPClientParser} which were not part of the response it was parsing. Nr(rs r*rz$HTTP11ClientProtocol._finishResponserr)finishResponsec|jdk(rd|_n,d|_|jj|j|jyt d}|jj jdd}d|vs%|jdk7s|jjs|jt|y|jj |j||j'|y#t$r8|j j#d|jj%YRwxYw) Nrrrz synthetic!rar(scloser)rPrrrrr rfrrr_giveUprrrirrTrrVrr)r5rr6rfs r*_finishResponse_WAITINGz,HTTP11ClientProtocol._finishResponse_WAITINGs  ;;) #%DKBDK  " " 0 01F1F G <<   -ll..<<]BO  ${{k)''22 LL ) NN * * , 0''-  " "6 * ! 0 !!"%--/  0s!D>EEc|j[|j}d|_d|_d|_d|_|jj d|_|j |yy)z If there is still a parser, call its C{connectionLost} method with the given reason. If there is not, do nothing. @type reason: L{Failure} N)rrrrrrr)r5r6parsers r*rz&HTTP11ClientProtocol._disconnectParserLse << #\\FDL#'D $(D !%)D "  - - /#'D  ! !& ) $r)cZ|jj|j|y)z Lose the underlying connection and disconnect the parser with the given L{Failure}. Use this method instead of calling the transport's loseConnection method directly otherwise random things will break. N)rrrrs r*rzHTTP11ClientProtocol._giveUpbs" %%' v&r)c |jj|y#t$r|jt YywxYw)z4 Handle some stuff from some place. N)rrrTrrrJs r*rz!HTTP11ClientProtocol.dataReceivedms6 $ LL % %e , $ LL # $s"AAcy)zh The underlying transport went away. If appropriate, notify the parser object. Nr(rs r*rz#HTTP11ClientProtocol.connectionLostvrr)rcd|_y)z{ Nothing is currently happening. Move to the C{'CONNECTION_LOST'} state but otherwise do nothing. CONNECTION_LOSTNrrs r*_connectionLost_QUIESCENTz.HTTP11ClientProtocol._connectionLost_QUIESCENT~ ( r)cd|_y)z The connection was in an inconsistent state. Move to the C{'CONNECTION_LOST'} state but otherwise do nothing. rNrrs r*!_connectionLost_GENERATION_FAILEDz6HTTP11ClientProtocol._connectionLost_GENERATION_FAILEDrr)cd|_|jjtt |g|`|j j y)z Fail the L{Deferred} for the current request, notify the request object that it does not need to continue transmitting itself, and move to the C{'CONNECTION_LOST'} state. rN)rPrrrrBrr:rs r*_connectionLost_TRANSMITTINGz1HTTP11ClientProtocol._connectionLost_TRANSMITTINGsF (  %%g.G.Q&RS  ! ((*r)cd|_y)z9 Move to the C{'CONNECTION_LOST'} state. rNrrs r*5_connectionLost_TRANSMITTING_AFTER_RECEIVING_RESPONSEzJHTTP11ClientProtocol._connectionLost_TRANSMITTING_AFTER_RECEIVING_RESPONSEs ( r)c4|j|d|_y)a Disconnect the response parser so that it can propagate the event as necessary (for example, to call an application protocol's C{connectionLost} method, or to fail a request L{Deferred}) and move to the C{'CONNECTION_LOST'} state. rN)rrPrs r*_connectionLost_WAITINGz,HTTP11ClientProtocol._connectionLost_WAITINGs v&' r)c|jttd|_|jD]}|j dg|_y)z Disconnect the response parser with a L{ConnectionAborted} failure, and move to the C{'CONNECTION_LOST'} state. rN)rrrDrPrr)r5r6rs r*_connectionLost_ABORTINGz-HTTP11ClientProtocol._connectionLost_ABORTINGsK w'8':;<' %% A JJt  !r)c|jdk(r tdS|jjd|_t }|j j ||S)zw Close the connection and cause all outstanding L{request} L{Deferred}s to fire with an error. rNABORTING)rPrrrrrr|)r5rs r*abortzHTTP11ClientProtocol.abortsR ;;+ +4=  %%'  J ##A&r))r$r%r&r'rPrrrrrr rr3r<rgrrrVr_finishResponse_TRANSMITTINGrrrrrrrrrrrr(r)r*rrs;zFGOO 8D)7"A%F --=OO++Z$; *, '$ ,,rs. 0 &2@.!0/7*5-FF     X  )    / 1  i9!&!"N Y  M$M$`^'z^'B      :3.RZZ, - -. ^j:j:j:Z D?D?N>(7 YrUrUrUj Y)")")"X ]:,:,:,z8r)