o 5@g@sdZgdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZmZmZmZddlmZmZmZddlmZmZmZmZddlmZdd l m!Z!m"Z"m#Z#dd l$m%Z%dd l&m'Z'dd l(m)Z)dd l*m+Z+ddl,m-Z-m.Z.ddl/m0Z0ddl1m2Z2m3Z3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:ddl;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgddlhmiZimjZjddlkmlZlmmZmmnZnz ddlompZpdZqWn ery,dZqYnwdZsdZtdZue`ZvgdZwgdZxdd ewDZyd!d exDZzd"d#Z{d$d%Zdkd&d'Z|dld(d)Z}dld*d+Z~d,d-Zd.d/Zd0d1Zd2ed3efd4d5Zd2ed3efd6d7Zd8ed3eeeffd9d:Zd;d<ZGd=d>d>eZGd?d@d@ZGdAdBdBe-jZdCZeZdDdEZedFZee"jeGdGdHdHZGdIdJdJeZGdKdLdLeZGdMdNdNeZGdOdPdPZdQZdRZ GdSdTdTZee"jGdUdVdVZee"je"je"jGdWdXdXe-je.jZdYdZZeeld[d\Zee"jGd]d^d^ZGd_d`d`e6endaZeeldbdcZGdddedee6e)dfZdgdhZGdidjdje#jZdS)ma HyperText Transfer Protocol implementation. This is the basic server-side protocol implementation used by the Twisted Web server. It can parse HTTP 1.0 requests and supports many HTTP 1.1 features as well. Additionally, some functionality implemented here is also useful for HTTP clients (such as the chunked encoding parser). @var CACHED: A marker value to be returned from cache-related request methods to indicate to the caller that a cached response will be usable and no response body should be generated. @var FOUND: An HTTP response code indicating a temporary redirect. @var NOT_MODIFIED: An HTTP response code indicating that a requested pre-condition (for example, the condition represented by an I{If-Modified-Since} header is present in the request) has succeeded. This indicates a response body cached by the client can be used. @var PRECONDITION_FAILED: An HTTP response code indicating that a requested pre-condition (for example, the condition represented by an I{If-None-Match} header is present in the request) has failed. This should typically indicate that the server has not taken the requested action. @var maxChunkSizeLineLength: Maximum allowable length of the CRLF-terminated line that indicates the size of a chunk and the extensions associated with it, as in the HTTP 1.1 chunked I{Transfer-Encoding} (RFC 7230 section 4.1). This limits how much data may be buffered when decoding the line. )= SWITCHINGOKCREATEDACCEPTEDNON_AUTHORITATIVE_INFORMATION NO_CONTENT RESET_CONTENTPARTIAL_CONTENT MULTI_STATUSMULTIPLE_CHOICEMOVED_PERMANENTLYFOUND SEE_OTHER NOT_MODIFIED USE_PROXYTEMPORARY_REDIRECTPERMANENT_REDIRECT BAD_REQUEST UNAUTHORIZEDPAYMENT_REQUIRED FORBIDDEN NOT_FOUND NOT_ALLOWEDNOT_ACCEPTABLEPROXY_AUTH_REQUIREDREQUEST_TIMEOUTCONFLICTGONELENGTH_REQUIREDPRECONDITION_FAILEDREQUEST_ENTITY_TOO_LARGEREQUEST_URI_TOO_LONGUNSUPPORTED_MEDIA_TYPEREQUESTED_RANGE_NOT_SATISFIABLEEXPECTATION_FAILEDINTERNAL_SERVER_ERRORNOT_IMPLEMENTED BAD_GATEWAYSERVICE_UNAVAILABLEGATEWAY_TIMEOUTHTTP_VERSION_NOT_SUPPORTEDINSUFFICIENT_STORAGE_SPACE NOT_EXTENDED RESPONSESCACHEDurlparseparse_qsdatetimeToStringdatetimeToLogStringtimegmstringToDatetimetoChunk fromChunkparseContentRangeStringTransport HTTPClient NO_BODY_CODESRequestPotentialDataLoss HTTPChannel HTTPFactoryN)BytesIO)AnyStrCallableOptionalTuple)ParseResultBytesunquote_to_bytesr.) Attribute Interface implementerprovider)Version)address interfacesprotocol) _PullToPush)Deferred) IProtocol)Logger)basicpolicies)log) _PY37PLUS nativeString networkString)proxyForInterface) deprecated)Failure),rr&rrrr#rr r(rr)r*r$rr r r rrrrr+rr%rrrrrrrrrr r"rr,r r'rrrr!r)Headers_sanitizeLinearWhitespace)IAccessLogFormatterINonQueuedRequestFactoryIRequest) H2ConnectionTF<zHTTP/1.1zMagic constant returned by http.Request methods to set cache validation headers when the request is conditional and the value fails the condition.)MonTueWedThuFriSatSun) NJanFebMarAprMayJunJulAugSepOctNovDeccCg|]}|qSlower.0namervrv2/usr/lib/python3/dist-packages/twisted/web/http.py r}cCsg|]}|o |qSrvrwryrvrvr|r}scCs8t|d\}}|d}dd|D}||fS)NcharmapcSsi|] \}}||dqS)rencoderzxyrvrvr| z _parseHeader..)cgi parse_headerdecoderitems)linekeypdictrvrvr| _parseHeaders rcCstt|tr tdt|\}}}}}}t|tr1|d}|d}|d}|d}|d}t||||||S)a Parse an URL into six components. This is similar to C{urlparse.urlparse}, but rejects C{str} input and always produces C{bytes} output. @type url: C{bytes} @raise TypeError: The given url was a C{str} string instead of a C{bytes}. @return: The scheme, net location, path, params, query string, and fragment of the URL - all as C{bytes}. @rtype: C{ParseResultBytes} zurl must be bytes, not unicodeascii) isinstancestr TypeError _urlparserrD)urlschemenetlocpathparamsqueryfragmentrvrvr|r.s       r.c Csi}dd|dD}|D]>}z |dd\}}Wn ty&|r$Yqw|s+|rLt|dd}t|dd}||vrG|||q|g||<q|S)zn Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3. @type qs: C{bytes} cSs g|] }|dD]}|q qS);)split)rzs1s2rvrvr|r}s zparse_qs..&=+ )r ValueErrorunquotereplaceappend)qskeep_blank_valuesstrict_parsingdritemkvrvrvr|r/ s$  r/c CsR|dkrt}t|\ }}}}}}}}} tdt||t|||||f} | S)zT Convert seconds since epoch to HTTP datetime string. @rtype: C{bytes} Nz#%s, %02d %3s %4d %02d:%02d:%02d GMT)timegmtimerW weekdayname monthname msSinceEpochyearmonthdayhhmmsswdrzsrvrvr|r0#sr0c CsH|dkrt}t|\ }}}}}}}}} d|t|||||f} | S)zQ Convert seconds since epoch to log datetime string. @rtype: C{str} Nz#[%02d/%3s/%4d:%02d:%02d:%02d +0000])rrrrrvrvr|r13sr1c Csd}||kr td|fd|krdksJJd||t||}td|D] }|tj|}q,|dkrCt|rC|d}||d}|d|} | d|} | d|} | S) z? Convert time tuple in GMT to seconds since epoch, GMT izYears prior to %d not supportedr imra)rcalendarleapdaysrangemdaysisleap) rrrhourminutesecondEPOCHdaysihoursminutessecondsrvrvr|r2Gs    r2c Cs~t|}|dddtvr#ztd|WSty"Ynwt|}|dks/|dkrF|drF|d}|d}|d}|d}nR|dksN|dkr{|dd d kr{|dd \}}}|d}t |}|d krr|d }n&|d krz|d}nt|dkr|d}|d}|d}|d}ntd|t |}t t |}t |}t t |d\}}} t t |||||| S)zt Convert an HTTP date string (one of three formats) to seconds since epoch. @type dateString: C{bytes} r>sSun, rr-EidilzUnknown datetime format %r:)rVrrxweekdayname_lowerr3rlenisdigitfindintmonthname_lowerindexmapr2) dateStringpartspartlenrrrrrminsecrvrvr|r3[sB   "    r3cCstt|dd|dfS)z Convert string to a chunk. @type data: C{bytes} @returns: a tuple of C{bytes} representing the chunked encoding of data r )rWrdatarvrvr|r4sr4breturncCs |D] }|dvr dSq|dkS)z Is the string case-insensitively hexidecimal? It must be composed of one or more characters in the ranges a-f, A-F and 0-9. s0123456789abcdefABCDEFFrv)rcrvrvr| _ishexdigitss rcCst|st|t|dS)z Decode a hexadecimal integer. Unlike L{int(b, 16)}, this raises L{ValueError} when the integer has a prefix like C{b'0x'}, C{b'+'}, or C{b'-'}, which is desirable when parsing network protocols. )rrr)rrvrvr|_hexints rrcCsf|dd\}}t|}|dkrtd|f|||ddkr%td|d|||ddfS)aA Convert chunk to string. Note that this function is not specification compliant: it doesn't handle chunk extensions. @type data: C{bytes} @return: tuple of (result, remaining) - both C{bytes}. @raise ValueError: If the given data is not a correctly formatted chunked byte string. rrr>z!Chunk length must be >= 0, not %drzchunk must end with CRLFN)rrr)rprefixrestlengthrvrvr|r5sr5cCsf|\}}|dkrtd|d\}}tt|d\}}|dkr*d}nt|}|||fS)z Parse a content-range header into (start, end, realLength). realLength might be None if real length is not known ('*'). bytesz#a range of type %r is not supported/r*N)striprrxrrr)headerkindotherstartend realLengthstartendrvrvr|r6s  r6c@steZdZdZedZedZddZddZdd Z d d Z d d Z de de fddZde de fddZddZdS))_IDeprecatedHTTPChannelToRequestInterfacez= The interface L{HTTPChannel} expects of L{Request}. zLA L{http_headers.Headers} instance giving all received HTTP request headers.zPA L{http_headers.Headers} instance holding all HTTP response headers to be sent.cCdS)z The underlying connection has been lost. @param reason: A failure instance indicating the reason why the connection was lost. @type reason: L{twisted.python.failure.Failure} Nrv)reasonrvrvr|connectionLostz8_IDeprecatedHTTPChannelToRequestInterface.connectionLostcCr)a  Called when L{HTTPChannel} has determined the length, if any, of the incoming request's body. @param length: The length of the request's body. @type length: L{int} if the request declares its body's length and L{None} if it does not. Nrvrrvrvr| gotLengthrz3_IDeprecatedHTTPChannelToRequestInterface.gotLengthcCr)z Deliver a received chunk of body data to the request. Note this does not imply chunked transfer encoding. @param data: The received chunk. @type data: L{bytes} Nrvrrvrvr|handleContentChunkrz<_IDeprecatedHTTPChannelToRequestInterface.handleContentChunkcCr)zF Parse the request's cookies out of received headers. Nrvrvrvrvr| parseCookies rz6_IDeprecatedHTTPChannelToRequestInterface.parseCookiescCr)a Called when the entire request, including its body, has been received. @param command: The request's HTTP command. @type command: L{bytes} @param path: The request's path. Note: this is actually what RFC7320 calls the URI. @type path: L{bytes} @param version: The request's HTTP version. @type version: L{bytes} Nrv)commandrversionrvrvr|requestReceivedrz9_IDeprecatedHTTPChannelToRequestInterface.requestReceivedrrcCr)a Determines if two requests are the same object. @param other: Another object whose identity will be compared to this instance's. @return: L{True} when the two are the same object and L{False} when not. Nrvrrvrvr|__eq__ rz0_IDeprecatedHTTPChannelToRequestInterface.__eq__cCr)a Determines if two requests are not the same object. @param other: Another object whose identity will be compared to this instance's. @return: L{True} when the two are not the same object and L{False} when they are. Nrvr rvrvr|__ne__+rz0_IDeprecatedHTTPChannelToRequestInterface.__ne__cCr)z{ Generate a hash value for the request. @return: The request's hash value. @rtype: L{int} Nrvrvrvrvr|__hash__6rz2_IDeprecatedHTTPChannelToRequestInterface.__hash__N)__name__ __module__ __qualname____doc__rFrequestHeadersresponseHeadersrrrrrobjectboolr r r rvrvrvr|rs     rc@(eZdZdZddZddZddZdS) r7zo I am a BytesIO wrapper that conforms for the transport API. I support the `writeSequence' method. cCs t|_dSN)r?rselfrvrvr|__init__E zStringTransport.__init__cCs|jd|dS)Nr)rwritejoin)rseqrvrvr| writeSequenceHszStringTransport.writeSequencecCst|jd|S)Nr)getattr__dict__)rattrrvrvr| __getattr__KzStringTransport.__getattr__N)r rrrrrr"rvrvrvr|r7?s  r7c@seZdZdZdZdZdZdZddZddZ d d Z d d Z d dZ ddZ ddZddZddZddZddZddZddZdS)r8a@ A client for HTTP 1.0. Notes: You probably want to send a 'Host' header with the name of the site you're connecting to, in order to not break name based virtual hosting. @ivar length: The length of the request body in bytes. @type length: C{int} @ivar firstLine: Are we waiting for the first header line? @type firstLine: C{bool} @ivar __buffer: The buffer that stores the response to the HTTP request. @type __buffer: A C{BytesIO} object. @ivar _header: Part or all of an HTTP request header. @type _header: C{bytes} NTrcCs|j|d|dgdS)Nrs HTTP/1.0  transportr)rrrrvrvr| sendCommandiszHTTPClient.sendCommandcCs>t|ts tt|}t|}t|}|j|d|dgdS)N: r)rrrWrr\r%r)rr{value santizedName santizedValuervrvr| sendHeaderls  zHTTPClient.sendHeadercCs|jddS)Nrr%rrrvrvr| endHeaderstr#zHTTPClient.endHeaderscCsB|dd\}}|}||||dkrt||_dSdS)z Given a complete HTTP header, extract the field name and value and process the header. @param header: a complete HTTP request header of the form 'field-name: value'. @type header: C{bytes} :rcontent-lengthN)rlstrip handleHeaderrxrr)rrrvalrvrvr| extractHeaderws    zHTTPClient.extractHeadercCs|jr/d|_|dd}|d}|d}z|d}Wn ty%d}Ynw||||dS|sJ|jdkr<||jt|_|| dS| dsT| dr\|j||_dS|jrj||j||_dS||_dS) z Parse the status line and headers for an HTTP request. @param line: Part of an HTTP request header. Request bodies are parsed in L{HTTPClient.rawDataReceived}. @type line: C{bytes} FNrr>rr r) firstLiner IndexError handleStatus_headerr3r?_HTTPClient__bufferhandleEndHeaders setRawMode startswith)rrlrstatusmessagervrvr| lineReceiveds2        zHTTPClient.lineReceivedcCs |dSr)handleResponseEnd)rrrvrvr|rrzHTTPClient.connectionLostcCs,|jdur|j}d|_||dSdS)z~ The response has been completely received. This callback may be invoked more than once per request. N)r9getvaluehandleResponse)rrrvrvr|rAs  zHTTPClient.handleResponseEndcCs|j|dSr)r9rrrrvrvr|handleResponsePartr#zHTTPClient.handleResponsePartcCdSrrvrrvrvr|connectionMadeszHTTPClient.connectionMadecCr)z Called when the status-line is received. @param version: e.g. 'HTTP/1.0' @param status: e.g. '200' @type status: C{bytes} @param message: e.g. 'OK' Nrv)rrr>r?rvrvr|r7rzHTTPClient.handleStatuscCr)z9 Called every time a header is received. Nrv)rrr2rvrvr|r1rzHTTPClient.handleHeadercCr)z= Called when all headers have been received. Nrvrrvrvr|r:rzHTTPClient.handleEndHeaderscCsn|jdur|d|j||jd}}|jt|8_nd}|||jdkr5|||dSdS)Nrr>)rrrErA setLineMode)rrrrvrvr|rawDataReceiveds   zHTTPClient.rawDataReceived)r rrrrr5r9r8r&r+r-r3r@rrArErGr7r1r:rIrvrvrvr|r8Os&)   r8)i0cCs|dur |dkr tStS)zS Get a writeable file-like object to which request content can be written. Ni)r?tempfile TemporaryFilerrvrvr|_getContentFilesrMs^\[?(?P.*?)\]?(:\d+)?$c@seZdZdZdZdZeZeeZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdZeZefdd Zd d Zeed d ddddZddZddZ ddZ!ddZ"de#fddZ$ddZ%ddZ&d d!Z'd"d#Z(d$d%Z)d&d'Z*d(d)Z+d*d+Z,        dYd,d-Z-dZd.d/Z.d0d1Z/d2d3Z0d4d5Z1d6d7Z2d8d9Z3d:d;Z4dd?Z6eed d@dAddBdCdDdEZ7dFdGZ8dHdIZ9dJdKZ:dLdMZ;dNdOZdTe?de@fdUdVZAdWdXZBdS)\r:a A HTTP request. Subclasses should override the process() method to determine how the request will be processed. @ivar method: The HTTP method that was used, e.g. C{b'GET'}. @type method: L{bytes} @ivar uri: The full encoded URI which was requested (including query arguments), e.g. C{b'/a/b%20/c?q=v'}. @type uri: L{bytes} @ivar path: The encoded path of the request URI (not including query arguments), e.g. C{b'/a/b%20/c'}. @type path: L{bytes} @ivar args: A mapping of decoded query argument names as L{bytes} to corresponding query argument values as L{list}s of L{bytes}. For example, for a URI with C{foo=bar&foo=baz&quux=spam} as its query part C{args} will be C{{b'foo': [b'bar', b'baz'], b'quux': [b'spam']}}. @type args: L{dict} of L{bytes} to L{list} of L{bytes} @ivar content: A file-like object giving the request body. This may be a file on disk, an L{io.BytesIO}, or some other type. The implementation is free to decide on a per-request basis. @type content: L{typing.BinaryIO} @ivar cookies: The cookies that will be sent in the response. @type cookies: L{list} of L{bytes} @type requestHeaders: L{http_headers.Headers} @ivar requestHeaders: All received HTTP request headers. @type responseHeaders: L{http_headers.Headers} @ivar responseHeaders: All HTTP response headers to be sent. @ivar notifications: A L{list} of L{Deferred}s which are waiting for notification that the response to this request has been finished (successfully or with an error). Don't use this attribute directly, instead use the L{Request.notifyFinish} method. @ivar _disconnected: A flag which is C{False} until the connection over which this request was received is closed and which is C{True} after that. @type _disconnected: L{bool} @ivar _log: A logger instance for request related messages. @type _log: L{twisted.logger.Logger} Nr>s(no method yet)s(no clientproto yet)s (no uri yet)FcCs`g|_||_|j|_|j|_t|_i|_t|_ g|_ |jj |_ |t ur+d}||_ dS)z @param channel: the channel we're connected to. @param queued: (deprecated) are we in the request queue, or can we start writing to the transport? FN) notificationschannelgetPeerclientgetHosthostr[rreceived_cookiesrcookiesr%_QUEUED_SENTINELqueued)rrOrWrvrvr|r@s    zRequest.__init__cCs|jr|jdttd|j||j||`|j dur6z|j Wn t y3Ynw|` |j D]}| dq9g|_ dS)zP Called when have finished responding and are no longer queued. z"Producer was not unregistered for N)producer_logfailurerZ RuntimeErroruriunregisterProducerrO requestDonecontentcloseOSErrorrNcallback)rrrvrvr|_cleanupZs$      zRequest._cleanupTwistedrrcCr)a' Notify the object that it is no longer queued. We start writing whatever data we have to the transport, etc. This method is not intended for users. In 16.3 this method was changed to become a no-op, as L{Request} objects are now never queued. Nrvrrvrvr|noLongerQueuedss zRequest.noLongerQueuedcCst||_dS)a0 Called when HTTP channel got length of content in this request. This method is not intended for users. @param length: The length of the request body, as indicated by the request headers. L{None} if the request headers do not indicate a length. N)rMr`)rrrvrvr|rs zRequest.gotLengthc Csr|jd}|dur dS|D](}|r6|dD]}|}z|dd\}}||j|<Wqty5YqwqdS)zW Parse cookie headers. This method is not intended for users. scookieNrrr)r getRawHeadersrr0rTr)r cookieheaders cookietxtcookrrrvrvr|rs  zRequest.parseCookiescC|j|dS)zX Write a chunk of data. This method is not intended for users. N)r`rrDrvrvr|rszRequest.handleContentChunkc Cs|j}|jddi|_|||_|_||_|jdd}t|dkr+|j|_ n |\|_ }t |d|_|j}|j d}|durG|d}|jdkr|r|rd} t |\} } || d<| d krl|t |jdnY| | krz3tr~tj|j| d d d } nt|j| } tr|jd d| Dn |jdd| DWn!ty} z|jt| tttfrWYd} ~ dSd} ~ ww|jdd|dS)a Called by channel when all data has been received. This method is not intended for users. @type command: C{bytes} @param command: The HTTP verb of this request. This has the case supplied by the client (eg, it maybe "get" rather than "GET"). @type path: C{bytes} @param path: The URI of this request. @type version: C{bytes} @param version: The HTTP version of this request. r>?rs content-typeNsPOSTsmultipart/form-datazCONTENT-LENGTHs!application/x-www-form-urlencodedutf8surrogateescape)encodingerrorscSs0i|]\}}t|tr|ddd|DqS) iso-8859-1cSs&g|]}t|tr|ddn|qS)rmrnrrr)rzrrvrvr|r}s z6Request.requestReceived...rrrrvrvr|rsz+Request.requestReceived..cSsi|] \}}|d|qS)rqrrrvrvr|rr)r`tellseekargsmethodr] clientprotorrrr/rrgrupdatereadrUrparse_multipartr ExceptionrO!_respondToBadRequestAndDisconnectrrrKeyErrorprocess)rrrrclengthr argstringructypemfdrrcgiArgservrvr|rsb         zRequest.requestReceivedrcCs,d|jjt|t|jt|jt|jS)z Return a string description of the request including such information as the request method and request URI. @return: A string loosely describing this L{Request} object. @rtype: L{str} z.<{} at 0x{:x} method={} uri={} clientproto={}>)format __class__r idrVrvr]rwrrvrvr|__repr__ szRequest.__repr__cCr)zY Override in subclasses. This method is not intended for users. Nrvrrvrvr|r~szRequest.processcCs6|jr td||jf||_||_|j||dS)z& Register a producer. zAregistering producer %s before previous one (%s) was unregisteredN)rYrstreamingProducerrOregisterProducerrrY streamingrvrvr|r$szRequest.registerProducercCs|jd|_dS)z* Unregister the producer. N)rOr^rYrrvrvr|r^2s  zRequest.unregisterProducercCs |j|}|dur|dSdS)a Get an HTTP request header. @type key: C{bytes} or C{str} @param key: The name of the header to get the value of. @rtype: C{bytes} or C{str} or L{None} @return: The value of the specified header, or L{None} if that header was not present in the request. The string type of the result matches the type of C{key}. Nr)rrg)rrr(rvrvr| getHeader;s zRequest.getHeadercCs |j|S)a. Get a cookie that was sent from the network. @type key: C{bytes} @param key: The name of the cookie to get. @rtype: C{bytes} or C{None} @returns: The value of the specified cookie, or L{None} if that cookie was not present in the request. )rTget)rrrvrvr| getCookieKs zRequest.getCookiecCs|jt|jdS)a Notify when the response to this request has finished. @note: There are some caveats around the reliability of the delivery of this notification. 1. If this L{Request}'s channel is paused, the notification will not be delivered. This can happen in one of two ways; either you can call C{request.transport.pauseProducing} yourself, or, 2. In order to deliver this notification promptly when a client disconnects, the reactor must continue reading from the transport, so that it can tell when the underlying network connection has gone away. Twisted Web will only keep reading up until a finite (small) maximum buffer size before it gives up and pauses the transport itself. If this occurs, you will not discover that the connection has gone away until a timeout fires or until the application attempts to send some data via L{Request.write}. 3. It is theoretically impossible to distinguish between successfully I{sending} a response and the peer successfully I{receiving} it. There are several networking edge cases where the L{Deferred}s returned by C{notifyFinish} will indicate success, but the data will never be received. There are also edge cases where the connection will appear to fail, but in reality the response was delivered. As a result, the information provided by the result of the L{Deferred}s returned by this method should be treated as a guess; do not make critical decisions in your applications based upon it. @rtype: L{Deferred} @return: A L{Deferred} which will be triggered when the request is finished -- with a L{None} value if the request finishes successfully or with an error if the request is interrupted by an error (for example, the client closing the connection prematurely). r)rNrrOrrvrvr| notifyFinishXs( zRequest.notifyFinishcCs|jrtd|jrtjddddS|js|d|jr$|jdt |jdr7|jj dur7|jj |d |_|j sC| dSdS) zV Indicate that all response data has been written to this L{Request}. zqRequest.finish called on a request after its connection was lost; use Request.notifyFinish to keep track of this.z%Warning! request.finish called twice.r) stacklevelNrs0 factoryr) _disconnectedr\finishedwarningswarnstartedWritingrchunkedrOhasattrrrTrWrdrrvrvr|finishs"   zRequest.finishc Cs|jrtd|jr dS|jsd|_|j}d|jf}|j}g}|dkr>|jddur>|j dkr>|jt vr>| dd|_ |j dur[|jd rP|jd n |jd t|j g|jduri|jd |jg|jD]\}}|D] }| ||fqtqn|jD] } | d | fq|j|||||j dkrd d|_dS|jt vrdd|_dS|jt||_|r|j r|jt|dS|j|dSdS)z Write some data as a result of an HTTP request. The first time this is called, it writes out response data. @type data: C{bytes} @param data: Some bytes to be sent as part of the response body. zBRequest.write called on a request after Request.finish was called.Nrs%dHTTP/1.1r/HEAD)sTransfer-Encodingchunkeds last-modifiedzPWarning: last-modified specified both in header list and lastModified attribute.sETags Set-CookiecSrFrrvrrvrvr|rzRequest.write..cSrFrrvrrvrvr|rr)rr\rrrwcode code_messagerrgrvr9rr lastModified hasHeaderrZinfo setRawHeadersr0etaggetAllRawHeadersrUrO writeHeadersr sentLengthrrr4) rrrrrheadersr{valuesr(cookiervrvr|rs^             z Request.writec Csdd} dd} | | |d| | |} |dur$| d| | |} |dur2| d| | |} |dur@| d | | |} |durN| d | | |} |dur\| d | | |} |rb| d } | rh| d } | r| | } | dvr|tdt| | d| 7} |j| dS)a  Set an outgoing HTTP cookie. In general, you should consider using sessions instead of cookies, see L{twisted.web.server.Request.getSession} and the L{twisted.web.server.Session} class for details. @param k: cookie name @type k: L{bytes} or L{str} @param v: cookie value @type v: L{bytes} or L{str} @param expires: cookie expire attribute value in "Wdy, DD Mon YYYY HH:MM:SS GMT" format @type expires: L{bytes} or L{str} @param domain: cookie domain @type domain: L{bytes} or L{str} @param path: cookie path @type path: L{bytes} or L{str} @param max_age: cookie expiration in seconds from reception @type max_age: L{bytes} or L{str} @param comment: cookie comment @type comment: L{bytes} or L{str} @param secure: direct browser to send the cookie on encrypted connections only @type secure: L{bool} @param httpOnly: direct browser not to expose cookies through channels other than HTTP (and HTTPS) requests @type httpOnly: L{bool} @param sameSite: One of L{None} (default), C{'lax'} or C{'strict'}. Direct browsers not to send this cookie on cross-origin requests. Please see: U{https://tools.ietf.org/html/draft-west-first-party-cookies-07} @type sameSite: L{None}, L{bytes} or L{str} @raise ValueError: If the value for C{sameSite} is not supported. cSs$|dur|St|tr |S|dS)z Ensure that C{val} is bytes, encoding using UTF-8 if needed. @param val: L{bytes} or L{str} @return: L{bytes} Nrm)rrrr2rvrvr| _ensureBytes)s    z'Request.addCookie.._ensureBytescSst|ddS)z Replace linear whitespace (C{\r}, C{\n}, C{\r\n}) and semicolons C{;} in C{val} with a single space. @param val: L{bytes} @return: L{bytes} rr)r\rrrvrvr| _sanitize;sz$Request.addCookie.._sanitizerNs ; Expires=s ; Domain=s; Path=s ; Max-Age=s ; Comment=s; Secures ; HttpOnly)slaxsstrictzInvalid value for sameSite: s ; SameSite=)rxrreprrUr)rrrexpiresdomainrmax_agecommentsecurehttpOnlysameSiterrrrvrvr| addCookies.;   zRequest.addCookiecCsJt|ts td||_|rt|tstd||_dSt|d|_dS)zi Set the HTTP response code. @type code: L{int} @type message: L{bytes} z&HTTP response code must be int or longz*HTTP response status message must be bytessUnknown StatusN)rrrrrrr,r)rrr?rvrvr|setResponseCode[s   zRequest.setResponseCodecCs|j||gdS)a Set an HTTP response header. Overrides any previously set values for this header. @type name: L{bytes} or L{str} @param name: The name of the header for which to set the value. @type value: L{bytes} or L{str} @param value: The value to set for the named header. A L{str} will be UTF-8 encoded, which may not interoperable with other implementations. Avoid passing non-ASCII characters if possible. N)rr)rr{r(rvrvr| setHeaderls zRequest.setHeadercCs|t|d|dS)a- Utility function that does a redirect. Set the response code to L{FOUND} and the I{Location} header to the given URL. The request should have C{finish()} called after this. @param url: I{Location} header value. @type url: L{bytes} or L{str} slocationN)rr r)rrrvrvr|redirect{s zRequest.redirectcCstt|}|jr|j|kr||_|d}|r>|ddd}zt|}Wn ty1YdSw||jkr>|t t SdS)a Set the C{Last-Modified} time for the response to this request. If I am called more than once, I ignore attempts to set Last-Modified earlier, only replacing the Last-Modified time if it is to a later value. If I am a conditional request, I may modify my response code to L{NOT_MODIFIED} if appropriate for the time given. @param when: The last time the resource being returned was modified, in seconds since the epoch. @type when: number @return: If I am a I{If-Modified-Since} conditional request and the time given is not newer than the condition, I return L{http.CACHED} to indicate that you should write no body. Otherwise, I return a false value. sif-modified-sincerrr>N) rmathceilrrrr3rrrr-)rwhen modifiedSince firstPartrvrvr|setLastModifieds     zRequest.setLastModifiedcCsP|r||_|d}|r&|}||vsd|vr&||jdvr!tp"ttSdS)a Set an C{entity tag} for the outgoing response. That's "entity tag" as in the HTTP/1.1 C{ETag} header, "used for comparing two or more entities from the same requested resource." If I am a conditional request, I may modify my response code to L{NOT_MODIFIED} or L{PRECONDITION_FAILED}, if appropriate for the tag given. @param etag: The entity tag for the resource being returned. @type etag: string @return: If I am a C{If-None-Match} conditional request and the tag matches one in the request, I return L{http.CACHED} to indicate that you should write no body. Otherwise, I return a false value. s if-none-match*)rsGETN)rrrrrvrrr-)rrtagsrvrvr|setETags zRequest.setETagcCs,i}|jD] \}}|d||<q|S)a Return dictionary mapping the names of all received headers to the last value received for each. Since this method does not return all header information, C{self.requestHeaders.getAllRawHeaders()} may be preferred. r)rrrx)rrrrrvrvr| getAllHeadersszRequest.getAllHeaderscCs<|d}|durt|}|dur|dSt|jS)z Get the hostname that the HTTP client passed in to the request. @see: L{IRequest.getRequestHostname} @returns: the requested hostname @rtype: C{bytes} hostNrS)r_hostHeaderExpressionmatchgrouprWrRrS)rrSrrvrvr|getRequestHostnames   zRequest.getRequestHostnamecC|jS)a Get my originally requesting transport's host. Don't rely on the 'transport' attribute, since Request objects may be copied remotely. For information on this method's return value, see L{twisted.internet.tcp.Port}. rSrrvrvr|rRszRequest.getHostcCsV||_|r d}nd}||kr|}nd||f}|jd|gtd|||_dS)a Change the host and port the request thinks it's using. This method is useful for working with reverse HTTP proxies (e.g. both Squid and Apache's mod_proxy can do this), when the address the HTTP client is using is different than the one we're listening on. For example, Apache may be listening on https://www.example.com/, and then forwarding requests to http://localhost:8080/, but we don't want HTML produced by Twisted to say b'http://localhost:8080/', they should say b'https://www.example.com/', so we do:: request.setHost(b'www.example.com', 443, ssl=1) @type host: C{bytes} @param host: The value to which to change the host header. @type ssl: C{bool} @param ssl: A flag which, if C{True}, indicates that the request is considered secure (if C{True}, L{isSecure} will return C{True}). iPs%b:%drTCPN) _forceSSLisSecurerrrK IPv4AddressrS)rrSportssldefault hostHeaderrvrvr|setHosts zRequest.setHostrgetClientAddress) replacementcCs t|jtjtjfr|jjSdS)z Return the IP address of the client who submitted this request. This method is B{deprecated}. Use L{getClientAddress} instead. @returns: the client IP address @rtype: C{str} N)rrQrKr IPv6AddressrSrrvrvr| getClientIPs zRequest.getClientIPcCr)a~ Return the address of the client who submitted this request. This may not be a network address (e.g., a server listening on a UNIX domain socket will cause this to return L{UNIXAddress}). Callers must check the type of the returned address. @since: 18.4 @return: the client's address. @rtype: L{IAddress} )rQrrvrvr|r)szRequest.getClientAddresscCs*|jrdSt|dd}|durdS|S)a Return L{True} if this request is using a secure transport. Normally this method returns L{True} if this request's L{HTTPChannel} instance is using a transport that implements L{interfaces.ISSLTransport}. This will also return L{True} if L{Request.setHost} has been called with C{ssl=True}. @returns: L{True} if this request is secure @rtype: C{bool} TrONF)rrr)rrOrvrvr|r9s  zRequest.isSecurec Csz1|d}|sd|_|_WdS|\}}|dkr tt|}|dd\|_|_WdStj tfyDd|_|_YdSt yY|j dd|_|_YdSw)Ns Authorizationrsbasicr.rrX) ruserpasswordrrxrbase64 b64decodebinasciiError BaseExceptionrZr[)rauthhbasupwrvrvr| _authorizeNs        zRequest._authorizecC*z|jWSty Ynw||jS)z Return the HTTP user sent with this request, if any. If no user was supplied, return the empty string. @returns: the HTTP user, if any @rtype: C{bytes} )rrrrrvrvr|getUser`  zRequest.getUsercCr)z Return the HTTP password sent with this request, if any. If no password was supplied, return the empty string. @returns: the HTTP password, if any @rtype: C{bytes} )rrrrrvrvr| getPasswordprzRequest.getPasswordcCs@d|_d|_|jdur|j|jD]}||qg|_dS)z There is no longer a connection for this request to respond over. Clean up anything which can't be useful anymore. TN)rrOr`rarNerrback)rrrrvrvr|rs     zRequest.connectionLostcC|jdur |jdSdS)zL Pass the loseConnection through to the underlying channel. N)rOloseConnectionrrvrvr|rs zRequest.loseConnectionrcCst|tr ||uStS)a Determines if two requests are the same object. @param other: Another object whose identity will be compared to this instance's. @return: L{True} when the two are the same object and L{False} when not. @rtype: L{bool} )rr:NotImplemented)rrrvrvr|r s zRequest.__eq__cCst|S)z A C{Request} is hashable so that it can be used as a mapping key. @return: A C{int} based on the instance's identity. )rrrvrvr|r zRequest.__hash__)NNNNNNFNr)r>)Cr rrrrYrrrr,rrvrwr]rrrrrrurr`rrrQrZrVrrdrYrJrfrrrrrrr~rr^rrrrrrrrrrrrrrRrrrrrrrrrrrr r rvrvrvr|r:s4    `   +R m%!  "   r:c@eZdZdZdS) _DataLossa; L{_DataLoss} indicates that not all of a message body was received. This is only one of several possible exceptions which may indicate that data was lost. Because of this, it should not be checked for by specifically; any unexpected exception should be treated as having caused data loss. Nr rrrrvrvrvr|rrc@r)r;a L{PotentialDataLoss} may be raised by a transfer encoding decoder's C{noMoreData} method to indicate that it cannot be determined if the entire response body has been delivered. This only occurs when making requests to HTTP servers which do not set I{Content-Length} or a I{Transfer-Encoding} in the response because in this case the end of the response is indicated by the connection being closed, an event which may also be due to a transient network problem or other error. Nrrvrvrvr|r;rr;c@r)_MalformedChunkedDataErrora C{_ChunkedTransferDecoder} raises L{_MalformedChunkedDataError} from its C{dataReceived} method when it encounters malformed data. This exception indicates a client-side error. If this exception is raised, the connection should be dropped with a 400 error. Nrrvrvrvr|rrrc@r) _IdentityTransferDecoderaZ Protocol for accumulating bytes up to a specified length. This handles the case where no I{Transfer-Encoding} is specified. @ivar contentLength: Counter keeping track of how many more bytes there are to receive. @ivar dataCallback: A one-argument callable which will be invoked each time application data is received. @ivar finishCallback: A one-argument callable which will be invoked when the terminal chunk is received. It will be invoked with all bytes which were delivered to this protocol which came after the terminal chunk. cCs||_||_||_dSr) contentLength dataCallbackfinishCallback)rrrrrvrvr|rs z!_IdentityTransferDecoder.__init__cCs|jdur td|jdur||dSt||jkr,|jt|8_||dS|j}|j}|j}d|_|_d|_||d||||ddS)a; Interpret the next chunk of bytes received. Either deliver them to the data callback or invoke the finish callback if enough bytes have been received. @raise RuntimeError: If the finish callback has already been invoked during a previous call to this methood. Nz;_IdentityTransferDecoder cannot decode data after finishingr>)rr\rrr)rrrrrrvrvr| dataReceiveds   z%_IdentityTransferDecoder.dataReceivedcCs>|j}d|_|_|jdur|dt|jdkrtdS)ap All data which will be delivered to this decoder has been. Check to make sure as much data as was expected has been received. @raise PotentialDataLoss: If the content length is unknown. @raise _DataLoss: If the content length is known and fewer than that many bytes have been delivered. @return: L{None} Nrr>)rrrr;r)rrrvrvr| noMoreDatas   z#_IdentityTransferDecoder.noMoreDataN)r rrrrrrrvrvrvr|rs  ris !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~c@seZdZdZdZdeegdfdeegdfddfddZdefd d Z defd d Z defd dZ defddZ defddZ deddfddZdddZdS)_ChunkedTransferDecodera Protocol for decoding I{chunked} Transfer-Encoding, as defined by RFC 7230, section 4.1. This protocol can interpret the contents of a request or response body which uses the I{chunked} Transfer-Encoding. It cannot interpret any of the rest of the HTTP protocol. It may make sense for _ChunkedTransferDecoder to be an actual IProtocol implementation. Currently, the only user of this class will only ever call dataReceived on it. However, it might be an improvement if the user could connect this to a transport and deliver connection lost notification. This way, `dataCallback` becomes `self.transport.write` and perhaps `finishCallback` becomes `self.transport.loseConnection()` (although I'm not sure where the extra data goes in that case). This could also allow this object to indicate to the receiver of data that the stream was not completely received, an error case which should be noticed. -exarkun @ivar dataCallback: A one-argument callable which will be invoked each time application data is received. This callback is not reentrant. @ivar finishCallback: A one-argument callable which will be invoked when the terminal chunk is received. It will be invoked with all bytes which were delivered to this protocol which came after the terminal chunk. @ivar length: Counter keeping track of how many more bytes in a chunk there are to receive. @ivar state: One of C{'CHUNK_LENGTH'}, C{'CRLF'}, C{'TRAILER'}, C{'BODY'}, or C{'FINISHED'}. For C{'CHUNK_LENGTH'}, data for the chunk length line is currently being read. For C{'CRLF'}, the CR LF pair which follows each chunk is being read. For C{'TRAILER'}, the CR LF pair which follows the terminal 0-length chunk is currently being read. For C{'BODY'}, the contents of a chunk are being read. For C{'FINISHED'}, the last chunk has been completely read and no more input is valid. @ivar _buffer: Accumulated received data for the current state. At each state transition this is truncated at the front so that index 0 is where the next state shall begin. @ivar _start: While in the C{'CHUNK_LENGTH'} state, tracks the index into the buffer at which search for CRLF should resume. Resuming the search at this position avoids doing quadratic work if the chunk length line arrives over many calls to C{dataReceived}. Not used in any other state. CHUNK_LENGTHrNrrcCs||_||_t|_d|_dS)Nr>)rr bytearray_buffer_start)rrrrvrvr|rzs z _ChunkedTransferDecoder.__init__cCs|jd|j}|tks|dkrt|jtkrtdt|dkr,t|jd|_dS|jdd|}|dkr:|}|jd|}zt|}Wn tyRtdw|j|d|}|rn| d t d krntd |d |dkrvd |_ nd|_ ||_ |jd|d=d|_dS)ak Read the chunk size line, ignoring any extensions. @returns: C{True} once the line has been read and removed from C{self._buffer}. C{False} when more data is required. @raises _MalformedChunkedDataError: when the chunk size cannot be decoded or the length of the line exceeds L{maxChunkSizeLineLength}. rrz,Chunk size line exceeds maximum of {} bytes.rFrr>zChunk-size must be an integer.Nrz(Invalid characters in chunk extensions: .TRAILERBODYrT) rrrmaxChunkSizeLineLengthrrrrr translate_chunkExtCharsstater)reolIndexendOfLengthIndex rawLengthrextrvrvr|_dataReceived_CHUNK_LENGTHs@    z2_ChunkedTransferDecoder._dataReceived_CHUNK_LENGTHcCs<t|jdkr dS|jdstdd|_|jdd=dS)a; Await the carriage return and line feed characters that are the end of chunk marker that follow the chunk data. @returns: C{True} when the CRLF have been read, otherwise C{False}. @raises _MalformedChunkedDataError: when anything other than CRLF are received. rFrChunk did not end with CRLFrr>T)rrr<rrrrvrvr|_dataReceived_CRLFs   z*_ChunkedTransferDecoder._dataReceived_CRLFcCs\t|jdkr dS|jdstdt|jdd}|jdd=d|_||dS)a Await the carriage return and line feed characters that follow the terminal zero-length chunk. Then invoke C{finishCallback} and switch to state C{'FINISHED'}. @returns: C{False}, as there is either insufficient data to continue, or no data remains. @raises _MalformedChunkedDataError: when anything other than CRLF is received. rFrr NFINISHED)rrr<r memoryviewtobytesrrrDrvrvr|_dataReceived_TRAILERs    z-_ChunkedTransferDecoder._dataReceived_TRAILERcCst|j|jkr%t|jd|j}|jd|j=d|_||dSt|j}|jt|8_|jdd=||dS)z Deliver any available chunk data to the C{dataCallback}. When all the remaining data for the chunk arrives, switch to state C{'CRLF'}. @returns: C{True} to continue processing of any buffered data. NCRLFT)rrrrrrrr)rchunkrvrvr|_dataReceived_BODYs    z*_ChunkedTransferDecoder._dataReceived_BODYcCstd)z Once C{finishCallback} has been invoked receipt of additional data raises L{RuntimeError} because it represents a programming error in the caller. zJ_ChunkedTransferDecoder.dataReceived called after last chunk was processed)r\rrvrvr|_dataReceived_FINISHEDsz._ChunkedTransferDecoder._dataReceived_FINISHEDrcCsH|j|7_d}|r|jr"t|d|j}|r |jsdSdSdSdS)zu Interpret data from a request or response body which uses the I{chunked} Transfer-Encoding. T_dataReceived_N)rrr)rrgoOnrvrvr|rs  z$_ChunkedTransferDecoder.dataReceivedcCs|jdkr td|jfdS)zj Verify that all data has been received. If it has not been, raise L{_DataLoss}. r zRChunked decoder in %r state, still expecting more data to get to 'FINISHED' state.N)rrrrvrvr|r s z"_ChunkedTransferDecoder.noMoreData)rN)r rrrrrArrrr r rrrrrrvrvrvr|rFs"1    5  rc@s8eZdZdZddZddZddZdd Zd d Zd S) _NoPushProducerz A no-op version of L{interfaces.IPushProducer}, used to abstract over the possibility that a L{HTTPChannel} transport does not provide L{IPushProducer}. cCr)z Pause producing data. Tells a producer that it has produced too much data to process for the time being, and to stop until resumeProducing() is called. Nrvrrvrvr|pauseProducing!rz_NoPushProducer.pauseProducingcCr)z Resume producing data. This tells a producer to re-add itself to the main loop and produce more data for its consumer. Nrvrrvrvr|resumeProducing)rz_NoPushProducer.resumeProducingcCr)z Register to receive data from a producer. @param producer: The producer to register. @param streaming: Whether this is a streaming producer or not. Nrvrrvrvr|r1rz _NoPushProducer.registerProducercCr)zM Stop consuming data from a producer, without disconnecting. Nrvrrvrvr|r^9rz"_NoPushProducer.unregisterProducercCr)z) IProducer.stopProducing Nrvrrvrvr| stopProducing>rz_NoPushProducer.stopProducingN) r rrrrrrr^rrvrvrvr|rs rc@sDeZdZdZdZdZdZdZdZdZ dZ dZ e Z dZdZdZdZdZd ZdZdZeZd d Zd d ZddZddZddZddZddZdeddfddZ ddZ!ddZ"d d!Z#d"d#Z$d$d%Z%d&d'Z&d(d)Z'd*d+Z(d,d-Z)d.d/Z*d0d1Z+d2d3Z,d4d5Z-d6d7Z.d8d9Z/d:d;Z0dd?Z2d@dAZ3dBdCZ4dS)Dr<a A receiver for HTTP requests. The L{HTTPChannel} provides L{interfaces.ITransport} and L{interfaces.IConsumer} to the L{Request} objects it creates. It also implements L{interfaces.IPushProducer} to C{self.transport}, allowing the transport to pause it. @ivar MAX_LENGTH: Maximum length for initial request line and each line from the header. @ivar _transferDecoder: L{None} or a decoder instance if the request body uses the I{chunked} Transfer-Encoding. @type _transferDecoder: L{_ChunkedTransferDecoder} @ivar maxHeaders: Maximum number of headers allowed per request. @type maxHeaders: C{int} @ivar totalHeadersSize: Maximum bytes for request line plus all headers from the request. @type totalHeadersSize: C{int} @ivar _receivedHeaderSize: Bytes received so far for the header. @type _receivedHeaderSize: C{int} @ivar _handlingRequest: Whether a request is currently being processed. @type _handlingRequest: L{bool} @ivar _dataBuffer: Any data that has been received from the connection while processing an outstanding request. @type _dataBuffer: L{list} of L{bytes} @ivar _networkProducer: Either the transport, if it provides L{interfaces.IPushProducer}, or a null implementation of L{interfaces.IPushProducer}. Used to attempt to prevent the transport from producing excess data when we're responding to a request. @type _networkProducer: L{interfaces.IPushProducer} @ivar _requestProducer: If the L{Request} object or anything it calls registers itself as an L{interfaces.IProducer}, it will be stored here. This is used to create a producing pipeline: pause/resume producing methods will be propagated from the C{transport}, through the L{HTTPChannel} instance, to the c{_requestProducer}. The reason we proxy through the producing methods rather than the old behaviour (where we literally just set the L{Request} object as the producer on the transport) is because we want to be able to exert backpressure on the client to prevent it from sending in arbitrarily many requests without ever reading responses. Essentially, if the client never reads our responses we will eventually stop reading its requests. @type _requestProducer: L{interfaces.IPushProducer} @ivar _requestProducerStreaming: A boolean that tracks whether the producer on the L{Request} side of this channel has registered itself as a L{interfaces.IPushProducer} or an L{interfaces.IPullProducer}. @type _requestProducerStreaming: L{bool} or L{None} @ivar _waitingForTransport: A boolean that tracks whether the transport has asked us to stop producing. This is used to keep track of what we're waiting for: if the transport has asked us to stop producing then we don't want to unpause the transport until it asks us to produce again. @type _waitingForTransport: L{bool} @ivar abortTimeout: The number of seconds to wait after we attempt to shut the transport down cleanly to give up and forcibly terminate it. This is only used when we time a connection out, to prevent errors causing the FD to get leaked. If this is L{None}, we will wait forever. @type abortTimeout: L{int} @ivar _abortingCall: The L{twisted.internet.base.DelayedCall} that will be used to forcibly close the transport if it doesn't close cleanly. @type _abortingCall: L{twisted.internet.base.DelayedCall} @ivar _optimisticEagerReadSize: When a resource takes a long time to answer a request (via L{twisted.web.server.NOT_DONE_YET}, hopefully one day by a L{Deferred}), we would like to be able to let that resource know about the underlying transport disappearing as promptly as possible, via L{Request.notifyFinish}, and therefore via C{self.requests[...].connectionLost()} on this L{HTTPChannel}. However, in order to simplify application logic, we implement head-of-line blocking, and do not relay pipelined requests to the application until the previous request has been answered. This means that said application cannot dispose of any entity-body that comes in from those subsequent requests, which may be arbitrarily large, and it may need to be buffered in memory. To implement this tradeoff between prompt notification when possible (in the most frequent case of non-pipelined requests) and correct behavior when not (say, if a client sends a very long-running GET request followed by a PUT request with a very large body) we will continue reading pipelined requests into C{self._dataBuffer} up to a given limit. C{_optimisticEagerReadSize} is the number of bytes we will accept from the client and buffer before pausing the transport. This behavior has been in place since Twisted 17.9.0 . @type _optimisticEagerReadSize: L{int} ii@r>rrNFcCsg|_d|_g|_d|_dSNF)requests_handlingRequest _dataBuffer_transferDecoderrrvrvr|rs zHTTPChannel.__init__cCs0||jt|jt|_|j|ddS)NT) setTimeouttimeOutrL IPushProducerr%r_networkProducerrrrvrvr|rGs zHTTPChannel.connectionMadecCs||jt|7_|j|jkr|dS|jr|js)dd|_|_dS|s5|jdkr5d|_dSt |j rA| |}n | |t|j }|j |d|_|}t|dkrc|dS|\}}}z|dWnty}|YdSw||_||_||_dS|d kr|jr||j}|sdSd |_||jdkr|dS|dS|dd vr|jd |d 7_dS|jr||j||_dS) zp Called for each line from request until the end of headers when it enters binary mode. NcWrFrrv)rurvrvr|rrz*HTTPChannel.lineReceived..rrr>rrr r) resetTimeout_receivedHeaderSizertotalHeadersSizer|_HTTPChannel__first_line persistentrr@r^ providedByrequestFactoryrrrrUnicodeDecodeError_command_path_version_HTTPChannel__headerheaderReceivedallHeadersReceivedrallContentReceivedr;r0)rrrequestrrrokrvrvr|r@s\               zHTTPChannel.lineReceivedcCs|j||dSr)rrr4rDrvrvr|_finishRequestBody s  zHTTPChannel._finishRequestBodycsfdd}|dkr0|s|Szt|}Wn ty#|YSwt|jdjj}n$|dkrR|dkrGd}tjdjj}n |dkrOd S|Sd Sj dur\|S|_ |_ d S) z If the provided header is C{content-length} or C{transfer-encoding}, choose the appropriate decoder if any. Returns L{True} if the request can proceed and L{False} if not. csd_dSr)r|rrvrrvr|fail( sz5HTTPChannel._maybeChooseTransferDecoder..failr/rstransfer-encodingrNsidentityT) rrrrrrr7rxrr r)rrrr8rnewTransferDecoderrvrr|_maybeChooseTransferDecoder s6       z'HTTPChannel._maybeChooseTransferDecodercCsz |dd\}}Wnty|YdSw|r#|ddr)|dS|}|d}|||s:dS|jdj}| |}|durO| |n| ||g|j d7_ |j |j kri|dSdS)af Do pre-processing (for content-length) and store this header away. Enforce the per-request header limit. @type line: C{bytes} @param line: A line from the header section of a request, excluding the line delimiter. @return: A flag indicating whether the header was valid. @rtype: L{bool} r.rFrNr%T)rrr|isspacerxrr:rrrgrr_receivedHeaderCount maxHeaders)rrrr reqHeadersrrvrvr|r2O s.        zHTTPChannel.headerReceivedcCsx|j}|j}|j}d|_d|_d|_d|_d|_|`|`|`|jr'| d|_ d|_ | |j d}||||dS)Nr>rTr)r.r/r0rr<r'r)r r"r! _savedTimeOutrr;rr)rrrrreqrvrvr|r4y s   zHTTPChannel.allContentReceivedrrcCst|jr|j|ttt|j|jkr|js|j dS| z |j |WdSt y9|YdSw)a This is called when this HTTP/1.1 parser is in raw mode rather than line mode. It may be in raw mode for one of two reasons: 1. All the headers of a request have been received and this L{HTTPChannel} is currently receiving its body. 2. The full content of a request has been received and is currently being processed asynchronously, and this L{HTTPChannel} is buffering the data of all subsequent requests to be parsed later. In the second state, the data will be played back later. @note: This isn't really a public API, and should be invoked only by L{LineReceiver}'s line parsing logic. If you wish to drive an L{HTTPChannel} from a custom data source, call C{dataReceived} on it directly. @see: L{LineReceive.rawDataReceived} N)rrrsumrr_optimisticEagerReadSize_waitingForTransportr$rr&r rrr|rDrvrvr|rI s   zHTTPChannel.rawDataReceivedcCsp|jd}||||j|_||j|jd}|r2|d dkr4|jdkr6| dSdSdSdS)Nrsexpectr>s 100-continuer) rrcheckPersistencer0r*rrrrgrx_send100Continue)rr@expectContinuervrvr|r3 s     zHTTPChannel.allHeadersReceivedcCsZ|jd}|rdd|ddD}ng}|dkr+d|vr)|jddgdSd SdS) a Check if the channel should close or not. @param request: The request most recently received over this channel against which checks will be made to determine if this connection can remain open after a matching response is returned. @type version: C{bytes} @param version: The version of the request. @rtype: C{bool} @return: A flag which, if C{True}, indicates that this connection may remain open to receive another request; if C{False}, the connection must be closed in order to indicate the completion of the response to C{request}. s connectioncSrurvrw)rztrvrvr|r} r~z0HTTPChannel.checkPersistence..r>rrscloseFT)rrgrrr)rr5r connectiontokensrvrvr|rD s  zHTTPChannel.checkPersistencecCst||jdkr t|jd=|js|j|jr4d|_|jr$||jd |j }g|_ | |dS| dS)zC Called by first request in queue when it is done. r>FrN) rrrCr$rr*rr?r!rrrHr)rr5rrvrvr|r_ s    zHTTPChannel.requestDonecCsB|jjdt|jd|jdur||j|j|_| dS)NzTiming out client: {peer}peer) rZrrr%rP abortTimeout callLaterforceAbortClient _abortingCallrrrvrvr|timeoutConnection s   zHTTPChannel.timeoutConnectioncCs.|jjdt|jdd|_|jdS)a Called if C{abortTimeout} seconds have passed since the timeout fired, and the connection still hasn't gone away. This can really only happen on extremely bad connections or when clients are maliciously attempting to keep connections open. z"Forcibly timing out client: {peer}rJN)rZrrr%rPrOabortConnectionrrvrvr|rN s zHTTPChannel.forceAbortClientcCsB|d|jD]}||q|jdur|jd|_dSdSr)r!rrrOcancel)rrr5rvrvr|r, s      zHTTPChannel.connectionLostcCst|jddur dSdS)a# Return L{True} if this channel is using a secure transport. Normally this method returns L{True} if this instance is using a transport that implements L{interfaces.ISSLTransport}. @returns: L{True} if this request is secure @rtype: C{bool} NTF)rL ISSLTransportr%rrvrvr|r6 s zHTTPChannel.isSecurec Cspt}|D] \}}|||q|d|d|d}|g} | dd|D| d|j| dS)a Called by L{Request} objects to write a complete set of HTTP headers to a transport. @param version: The HTTP version in use. @type version: L{bytes} @param code: The HTTP status code to write. @type code: L{bytes} @param reason: The HTTP reason phrase to write. @type reason: L{bytes} @param headers: The headers to write to the transport. @type headers: L{twisted.web.http_headers.Headers} rrcss.|]\}}|D] }|d|dVqqdS)r'rNrv)rzr{rr(rvrvr| [ s z+HTTPChannel.writeHeaders..N)r[ addRawHeaderextendrrr%r) rrrrrsanitizedHeadersr{r( responseLineheaderSequencervrvr|rD s   zHTTPChannel.writeHeaderscCrk)z Called by L{Request} objects to write response data. @param data: The data chunk to write to the stream. @type data: L{bytes} @return: L{None} Nr,rDrvrvr|rc  zHTTPChannel.writecCrk)z Write a list of strings to the HTTP response. @param iovec: A list of byte strings to write to the stream. @type iovec: L{list} of L{bytes} @return: L{None} Nr$)riovecrvrvr|rn rZzHTTPChannel.writeSequencecC |jS)zg Get the remote address of this connection. @return: An L{IAddress} provider. )r%rPrrvrvr|rPy  zHTTPChannel.getPeercCr\)zf Get the local address of this connection. @return: An L{IAddress} provider. )r%rRrrvrvr|rR r]zHTTPChannel.getHostcCs|j|jS)z Closes the connection. Will write any data that is pending to be sent on the network, but if this response has not yet been written to the network will not write anything. @return: L{None} )r$r^r%rrrvrvr|r s  zHTTPChannel.loseConnectioncCsJ|jdurtd||jf|st||}||_||_|s#|dSdS)a Register to receive data from a producer. This sets self to be a consumer for a producer. When this object runs out of data (as when a send(2) call on a socket succeeds in moving the last data from a userspace buffer into a kernelspace buffer), it will ask the producer to resumeProducing(). For L{IPullProducer} providers, C{resumeProducing} will be called once each time data is required. For L{IPushProducer} providers, C{pauseProducing} will be called whenever the write buffer fills up and C{resumeProducing} will only be called when it empties. @type producer: L{IProducer} provider @param producer: The L{IProducer} that will be producing data. @type streaming: L{bool} @param streaming: C{True} if C{producer} provides L{IPushProducer}, C{False} if C{producer} provides L{IPullProducer}. @raise RuntimeError: If a producer is already registered. @return: L{None} NzHCannot register producer %s, because producer %s was never unregistered.)_requestProducerr\rN_requestProducerStreamingstartStreamingrrvrvr|r s   zHTTPChannel.registerProducercCs.|jdurdS|js|jd|_d|_dS)zg Stop consuming data from a producer, without disconnecting. @return: L{None} N)r^r_ stopStreamingrrvrvr|r^ s   zHTTPChannel.unregisterProducercCr)a& Stop producing data. The HTTPChannel doesn't *actually* implement this, beacuse the assumption is that it will only be called just before C{loseConnection} is called. There's nothing sensible we can do other than call C{loseConnection} anyway. N)r^rrrvrvr|r s zHTTPChannel.stopProducingcC2d|_|jdur |j|js|jdSdS)a" Pause producing data. This will be called by the transport when the send buffers have been filled up. We want to simultaneously pause the producing L{Request} object and also pause our transport. The logic behind pausing the transport is specifically to avoid issues like https://twistedmatrix.com/trac/ticket/8868. In this case, our inability to send does not prevent us handling more requests, which means we increasingly queue up more responses in our send buffer without end. The easiest way to handle this is to ensure that if we are unable to send our responses, we will not read further data from the connection until the client pulls some data out. This is a bit of a blunt instrument, but it's ok. Note that this potentially interacts with timeout handling in a positive way. Once the transport is paused the client may run into a timeout which will cause us to tear the connection down. That's a good thing! TN)rCr^rrr$rrvrvr|r s   zHTTPChannel.pauseProducingcCrb)a! Resume producing data. This will be called by the transport when the send buffer has dropped enough to actually send more data. When this happens we can unpause any outstanding L{Request} producers we have, and also unpause our transport. FN)rCr^rrr$rrvrvr|r s   zHTTPChannel.resumeProducingcCs|jddS)z} Sends a 100 Continue response, used to signal to clients that further processing will be performed. sHTTP/1.1 100 Continue Nr,rrvrvr|rE szHTTPChannel._send100ContinuecCs|jd|dS)a& This is a quick and dirty way of responding to bad requests. As described by HTTP standard we should be patient and accept the whole request from the client before sending a polite bad request response, even in the case when clients send tons of data. sHTTP/1.1 400 Bad Request N)r%rrrrvrvr|r| s  z-HTTPChannel._respondToBadRequestAndDisconnect)5r rrrr=r(rLrr*r1r)_HTTPChannel__contentr:r,r?r<r'r^r_rCrOrBrQrZrrGr@r7r:r2r4rrIr3rDr_rPrNrrrrrrPrRrrr^rrrrEr|rvrvrvr|r<Ds`hI/*++     * # r<cCsxt|ts |d}t|}t|ts|d}|dr#|dd}|dr6|ddddd dS|ddS) z Return a string like python repr, but always escaped as if surrounding quotes were double quotes. @param s: The string to escape. @type s: L{bytes} or L{str} @return: An escaped string. @rtype: L{str} rrrN'r"z\"z\')rrrrrrr<r)rrrvrvr|_escape" s       rgc Cs|}t|tjtjtfr|j}nd}t|dpd}t|dp$d}dt t||t|j t|j t|j |j |jp>d||d }|S)zm @return: A combined log formatted log line for the given request. @see: L{IAccessLogFormatter} -sreferers user-agentzk"%(ip)s" - - %(timestamp)s "%(method)s %(uri)s %(protocol)s" %(code)d %(length)s "%(referrer)s" "%(agent)s"r) ip timestamprvr]rMrrreferreragent)rrrKrr_XForwardedForAddressrSrgrdictrvr]rwrr)rjr5 clientAddrrirkrlrrvrvr|combinedLogFormatter: s.rpc@seZdZdZddZdS)rmz L{IAddress} which represents the client IP to log for a request, as gleaned from an X-Forwarded-For header. @ivar host: An IP address or C{b"-"}. @type host: L{bytes} @see: L{proxiedLogFormatter} cCs ||_dSrrrrSrvrvr|rh s z_XForwardedForAddress.__init__N)r rrrrrvrvrvr|rm\ s rmc@s<eZdZdZddZeddZeddZedd Zd S) _XForwardedForRequestz Add a layer on top of another request that only uses the value of an X-Forwarded-For header as the result of C{getClientAddress}. cCs,|jjddgddd}t|S)a8 The client address (the first address) in the value of the I{X-Forwarded-For header}. If the header is not present, the IP is considered to be C{b"-"}. @return: L{_XForwardedForAddress} which wraps the client address as expected by L{combinedLogFormatter}. sx-forwarded-forrhr>,)_requestrrgrrrmrqrvrvr|rr s  z&_XForwardedForRequest.getClientAddresscC|jjS)zX @return: The protocol version in the request. @rtype: L{bytes} )rtrwrrvrvr|rw rz!_XForwardedForRequest.clientprotocCru)zT @return: The response code for the request. @rtype: L{int} )rtrrrvrvr|r rz_XForwardedForRequest.codecCru)z` @return: The number of bytes sent in the response body. @rtype: L{int} )rtrrrvrvr|r rz _XForwardedForRequest.sentLengthN) r rrrrpropertyrwrrrvrvrvr|rrl s  rrrtcCst|t|S)z @return: A combined log formatted log line for the given request but use the value of the I{X-Forwarded-For} header as the value for the client IP address. @see: L{IAccessLogFormatter} )rprr)rjr5rvrvr|proxiedLogFormatter s rwc@seZdZdZdZeZdZdZdZ dZ e ddZ e j ddZ e ddZej ddZe d d Zej d d Ze d d Zej dd Ze ddZej ddZddZdS)_GenericHTTPChannelProtocola A proxy object that wraps one of the HTTP protocol objects, and switches between them depending on TLS negotiated protocol. @ivar _negotiatedProtocol: The protocol negotiated with ALPN or NPN, if any. @type _negotiatedProtocol: Either a bytestring containing the ALPN token for the negotiated protocol, or L{None} if no protocol has yet been negotiated. @ivar _channel: The object capable of behaving like a L{HTTPChannel} that is backing this object. By default this is a L{HTTPChannel}, but if a HTTP protocol upgrade takes place this may be a different channel object. Must implement L{IProtocol}. @type _channel: L{HTTPChannel} @ivar _requestFactory: A callable to use to build L{IRequest} objects. @type _requestFactory: L{IRequest} @ivar _site: A reference to the creating L{twisted.web.server.Site} object. @type _site: L{twisted.web.server.Site} @ivar _factory: A reference to the creating L{HTTPFactory} object. @type _factory: L{HTTPFactory} @ivar _timeOut: A timeout value to pass to the backing channel. @type _timeOut: L{int} or L{None} @ivar _callLater: A value for the C{callLater} callback. @type _callLater: L{callable} NcCru)z= @see: L{_genericHTTPChannelProtocolFactory} )_channelrrrvrvr|r z#_GenericHTTPChannelProtocol.factorycCs||_||j_dSr)_factoryryrrr(rvrvr|r s cCru)z A callable to use to build L{IRequest} objects. Retries the object from the current backing channel. )ryr,rrvrvr|r, z*_GenericHTTPChannelProtocol.requestFactorycC||_||j_dS)a  A callable to use to build L{IRequest} objects. Sets the object on the backing channel and also stores the value for propagation to any new channel. @param value: The new callable to use. @type value: A L{callable} returning L{IRequest} N)_requestFactoryryr,r|rvrvr|r,  cCru)z A reference to the creating L{twisted.web.server.Site} object. Returns the site object from the backing channel. )rysiterrvrvr|r r}z _GenericHTTPChannelProtocol.sitecCr~)a; A reference to the creating L{twisted.web.server.Site} object. Sets the object on the backing channel and also stores the value for propagation to any new channel. @param value: The L{twisted.web.server.Site} object to set. @type value: L{twisted.web.server.Site} N)_siteryrr|rvrvr|r rcCru)z; The idle timeout for the backing channel. )ryr"rrvrvr|r" rzz#_GenericHTTPChannelProtocol.timeOutcCr~)a  The idle timeout for the backing channel. Sets the idle timeout on both the backing channel and stores it for propagation to any new backing channel. @param value: The timeout to set. @type value: L{int} or L{float} N)_timeOutryr"r|rvrvr|r" rcCru)z A value for the C{callLater} callback. This callback is used by the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts. )ryrMrrvrvr|rM rz%_GenericHTTPChannelProtocol.callLatercCr~)z Sets the value for the C{callLater} callback. This callback is used by the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts. @param value: The new callback to use. @type value: L{callable} N) _callLaterryrMr|rvrvr|rM' s cCs|jdurpz|jjj}Wn tyd}Ynw|durd}|dkrets(td|jj}||j d|jj}t |_|j |j_ |j |j_|j|j_|j|j_|j|j_|j|||jdn|dksmJd||_|j|S)zi An override of L{IProtocol.dataReceived} that checks what protocol we're using. Nshttp/1.1sh2z"Negotiated HTTP/2 without support.TzUnsupported protocol negotiated)_negotiatedProtocolryr%negotiatedProtocolAttributeError H2_ENABLEDrr$r^r!r`rr,rrr{rrr"rrMmakeConnectionrr)rrrnetworkProducerr%rvrvr|r3 s8           z(_GenericHTTPChannelProtocol.dataReceived)r rrrrr:rr{rrrrvrsetterr,rr"rMrrvrvrvr|rx s:            rxrycCs ttS)zK Returns an appropriately initialized _GenericHTTPChannelProtocol. )rxr<rrvrvr|"_genericHTTPChannelProtocolFactoryg s rc@s^eZdZdZeZdZeZdeddfddZ ddZ ddZ d d Z d d Z d dZddZdS)r=a Factory for HTTP server. @ivar _logDateTime: A cached datetime string for log messages, updated by C{_logDateTimeCall}. @type _logDateTime: C{str} @ivar _logDateTimeCall: A delayed call for the next update to the cached log datetime string. @type _logDateTimeCall: L{IDelayedCall} provided @ivar _logFormatter: See the C{logFormatter} parameter to L{__init__} @ivar _nativeize: A flag that indicates whether the log file being written to wants native strings (C{True}) or bytes (C{False}). This is only to support writing to L{twisted.python.log} which, unfortunately, works with native strings. @ivar reactor: An L{IReactorTime} provider used to manage connection timeouts and compute logging timestamps. NcCsX|sddlm}||_|durtj|}||_||_|dur!t}||_d|_ d|_ dS)a @param logPath: File path to which access log messages will be written or C{None} to disable logging. @type logPath: L{str} or L{bytes} @param timeout: The initial value of L{timeOut}, which defines the idle connection timeout in seconds, or C{None} to disable the idle timeout. @type timeout: L{float} @param logFormatter: An object to format requests into log lines for the access log. L{combinedLogFormatter} when C{None} is passed. @type logFormatter: L{IAccessLogFormatter} provider @param reactor: An L{IReactorTime} provider used to manage connection timeouts and compute logging timestamps. Defaults to the global reactor. r>)reactorN) twisted.internetrosrabspathlogPathr"rp _logFormatter _logDateTime_logDateTimeCall)rrtimeout logFormatterrrvrvr|r s   zHTTPFactory.__init__cCs&t|j|_|jd|j|_dS)zY Update log datetime periodically, so we aren't always recalculating it. rN)r1rrrrM_updateLogDateTimerrrvrvr|r szHTTPFactory._updateLogDateTimecCs$tj||}|jj|_|j|_|Sr)rM ServerFactory buildProtocolrrMr")raddrprvrvr|r s zHTTPFactory.buildProtocolcCs6|jdur ||jr||j|_dStj|_dS)z6 Set up request logging if necessary. N)rrr _openLogFilelogFilerTlogfilerrvrvr| startFactory s  zHTTPFactory.startFactorycCsTt|dr|jtjkr|j|`|jdur&|jr(|jd|_dSdSdS)Nr)rrrTrraractiverRrrvrvr| stopFactory s     zHTTPFactory.stopFactorycCst|dd}|S)zP Override in subclasses, e.g. to use L{twisted.python.logfile}. abr)open)rrfrvrvr|r s zHTTPFactory._openLogFilecCsFz|j}Wn tyYdSw||j|d}||ddS)z Write a line representing C{request} to the access log file. @param request: The request object about which to log. @type request: L{Request}  rmN)rrrrrr)rr5rrrvrvr|rT s  zHTTPFactory.log)r rrrrrMr_REQUEST_TIMEOUTr"rrrrrrrTrvrvrvr|r=n s %  r=)r>r>r)r__all__rrrrrrrerKrrior?typingr@rArBrC urllib.parserDrErr.rzope.interfacerFrGrHrI incrementalrJrrKrLrM"twisted.internet._producer_helpersrNtwisted.internet.deferrOtwisted.internet.interfacesrPtwisted.loggerrQtwisted.protocolsrRrStwisted.pythonrTtwisted.python.compatrUrVrWtwisted.python.componentsrXtwisted.python.deprecaterYtwisted.python.failurerZtwisted.web._responsesrr&rrrr#rr r(rr)r*r$rr r r rrrrr+rr%rrrrrrrrrr r"rr,r r'rrrr!rtwisted.web.http_headersr[r\twisted.web.iwebr]r^r_twisted.web._http2r`r ImportErrorrprotocol_versionr- responsesrrrrrr/r0r1r2r3r4rrrrrr5r6rr7 LineReceiverr8r9rrVrMcompiler IConsumerr:r{rr;rrrrrr#r ITransport TimeoutMixinr<rgrpIAddressrmrrrwrxrrr=rvrvrvr|sA          .    7   _ @   J T*b !0  @