http.py 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440
  1. # -*- test-case-name: twisted.web.test.test_http -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. HyperText Transfer Protocol implementation.
  6. This is the basic server-side protocol implementation used by the Twisted
  7. Web server. It can parse HTTP 1.0 requests and supports many HTTP 1.1
  8. features as well. Additionally, some functionality implemented here is
  9. also useful for HTTP clients (such as the chunked encoding parser).
  10. @var CACHED: A marker value to be returned from cache-related request methods
  11. to indicate to the caller that a cached response will be usable and no
  12. response body should be generated.
  13. @var FOUND: An HTTP response code indicating a temporary redirect.
  14. @var NOT_MODIFIED: An HTTP response code indicating that a requested
  15. pre-condition (for example, the condition represented by an
  16. I{If-Modified-Since} header is present in the request) has succeeded. This
  17. indicates a response body cached by the client can be used.
  18. @var PRECONDITION_FAILED: An HTTP response code indicating that a requested
  19. pre-condition (for example, the condition represented by an I{If-None-Match}
  20. header is present in the request) has failed. This should typically
  21. indicate that the server has not taken the requested action.
  22. @var maxChunkSizeLineLength: Maximum allowable length of the CRLF-terminated
  23. line that indicates the size of a chunk and the extensions associated with
  24. it, as in the HTTP 1.1 chunked I{Transfer-Encoding} (RFC 7230 section 4.1).
  25. This limits how much data may be buffered when decoding the line.
  26. """
  27. from __future__ import annotations
  28. __all__ = [
  29. "SWITCHING",
  30. "OK",
  31. "CREATED",
  32. "ACCEPTED",
  33. "NON_AUTHORITATIVE_INFORMATION",
  34. "NO_CONTENT",
  35. "RESET_CONTENT",
  36. "PARTIAL_CONTENT",
  37. "MULTI_STATUS",
  38. "MULTIPLE_CHOICE",
  39. "MOVED_PERMANENTLY",
  40. "FOUND",
  41. "SEE_OTHER",
  42. "NOT_MODIFIED",
  43. "USE_PROXY",
  44. "TEMPORARY_REDIRECT",
  45. "PERMANENT_REDIRECT",
  46. "BAD_REQUEST",
  47. "UNAUTHORIZED",
  48. "PAYMENT_REQUIRED",
  49. "FORBIDDEN",
  50. "NOT_FOUND",
  51. "NOT_ALLOWED",
  52. "NOT_ACCEPTABLE",
  53. "PROXY_AUTH_REQUIRED",
  54. "REQUEST_TIMEOUT",
  55. "CONFLICT",
  56. "GONE",
  57. "LENGTH_REQUIRED",
  58. "PRECONDITION_FAILED",
  59. "REQUEST_ENTITY_TOO_LARGE",
  60. "REQUEST_URI_TOO_LONG",
  61. "UNSUPPORTED_MEDIA_TYPE",
  62. "REQUESTED_RANGE_NOT_SATISFIABLE",
  63. "EXPECTATION_FAILED",
  64. "IM_A_TEAPOT",
  65. "INTERNAL_SERVER_ERROR",
  66. "NOT_IMPLEMENTED",
  67. "BAD_GATEWAY",
  68. "SERVICE_UNAVAILABLE",
  69. "GATEWAY_TIMEOUT",
  70. "HTTP_VERSION_NOT_SUPPORTED",
  71. "INSUFFICIENT_STORAGE_SPACE",
  72. "NOT_EXTENDED",
  73. "RESPONSES",
  74. "CACHED",
  75. "urlparse",
  76. "parse_qs",
  77. "datetimeToString",
  78. "datetimeToLogString",
  79. "timegm",
  80. "stringToDatetime",
  81. "toChunk",
  82. "fromChunk",
  83. "parseContentRange",
  84. "StringTransport",
  85. "HTTPClient",
  86. "NO_BODY_CODES",
  87. "Request",
  88. "PotentialDataLoss",
  89. "HTTPChannel",
  90. "HTTPFactory",
  91. ]
  92. import base64
  93. import binascii
  94. import calendar
  95. import math
  96. import os
  97. import re
  98. import tempfile
  99. import warnings
  100. from email import message_from_bytes
  101. from email.message import EmailMessage, Message
  102. from io import BufferedIOBase, BytesIO, TextIOWrapper
  103. from time import gmtime, time
  104. from typing import (
  105. AnyStr,
  106. Callable,
  107. Dict,
  108. List,
  109. Optional,
  110. Protocol as TypingProtocol,
  111. Tuple,
  112. )
  113. from urllib.parse import (
  114. ParseResultBytes,
  115. unquote_to_bytes as unquote,
  116. urlparse as _urlparse,
  117. )
  118. from zope.interface import Attribute, Interface, implementer, provider
  119. from incremental import Version
  120. from twisted.internet import address, interfaces, protocol
  121. from twisted.internet._producer_helpers import _PullToPush
  122. from twisted.internet.defer import Deferred
  123. from twisted.internet.interfaces import (
  124. IAddress,
  125. IDelayedCall,
  126. IProtocol,
  127. IReactorTime,
  128. ITCPTransport,
  129. )
  130. from twisted.internet.protocol import Protocol
  131. from twisted.logger import Logger
  132. from twisted.protocols import basic, policies
  133. from twisted.python import log
  134. from twisted.python.compat import nativeString, networkString
  135. from twisted.python.components import proxyForInterface
  136. from twisted.python.deprecate import deprecated, deprecatedModuleAttribute
  137. from twisted.python.failure import Failure
  138. from twisted.web._abnf import _hexint, _istoken
  139. from twisted.web._responses import (
  140. ACCEPTED,
  141. BAD_GATEWAY,
  142. BAD_REQUEST,
  143. CONFLICT,
  144. CREATED,
  145. EXPECTATION_FAILED,
  146. FORBIDDEN,
  147. FOUND,
  148. GATEWAY_TIMEOUT,
  149. GONE,
  150. HTTP_VERSION_NOT_SUPPORTED,
  151. IM_A_TEAPOT,
  152. INSUFFICIENT_STORAGE_SPACE,
  153. INTERNAL_SERVER_ERROR,
  154. LENGTH_REQUIRED,
  155. MOVED_PERMANENTLY,
  156. MULTI_STATUS,
  157. MULTIPLE_CHOICE,
  158. NO_CONTENT,
  159. NON_AUTHORITATIVE_INFORMATION,
  160. NOT_ACCEPTABLE,
  161. NOT_ALLOWED,
  162. NOT_EXTENDED,
  163. NOT_FOUND,
  164. NOT_IMPLEMENTED,
  165. NOT_MODIFIED,
  166. OK,
  167. PARTIAL_CONTENT,
  168. PAYMENT_REQUIRED,
  169. PERMANENT_REDIRECT,
  170. PRECONDITION_FAILED,
  171. PROXY_AUTH_REQUIRED,
  172. REQUEST_ENTITY_TOO_LARGE,
  173. REQUEST_TIMEOUT,
  174. REQUEST_URI_TOO_LONG,
  175. REQUESTED_RANGE_NOT_SATISFIABLE,
  176. RESET_CONTENT,
  177. RESPONSES,
  178. SEE_OTHER,
  179. SERVICE_UNAVAILABLE,
  180. SWITCHING,
  181. TEMPORARY_REDIRECT,
  182. UNAUTHORIZED,
  183. UNSUPPORTED_MEDIA_TYPE,
  184. USE_PROXY,
  185. )
  186. from twisted.web.http_headers import (
  187. Headers,
  188. InvalidHeaderName,
  189. _nameEncoder,
  190. _sanitizeLinearWhitespace,
  191. )
  192. from twisted.web.iweb import IAccessLogFormatter, INonQueuedRequestFactory, IRequest
  193. try:
  194. from twisted.web._http2 import H2Connection
  195. H2_ENABLED = True
  196. except ImportError:
  197. H2_ENABLED = False
  198. # A common request timeout -- 1 minute. This is roughly what nginx uses, and
  199. # so it seems to be a good choice for us too.
  200. _REQUEST_TIMEOUT = 1 * 60
  201. protocol_version = "HTTP/1.1"
  202. CACHED = """Magic constant returned by http.Request methods to set cache
  203. validation headers when the request is conditional and the value fails
  204. the condition."""
  205. # backwards compatibility
  206. responses = RESPONSES
  207. # datetime parsing and formatting
  208. weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  209. _months = [
  210. "Jan",
  211. "Feb",
  212. "Mar",
  213. "Apr",
  214. "May",
  215. "Jun",
  216. "Jul",
  217. "Aug",
  218. "Sep",
  219. "Oct",
  220. "Nov",
  221. "Dec",
  222. ]
  223. monthname = [None] + _months
  224. _weekdaynameBytes = [s.encode("ascii") for s in weekdayname]
  225. _monthnameBytes = [None] + [s.encode("ascii") for s in _months]
  226. weekdayname_lower = [name.lower() for name in weekdayname]
  227. monthname_lower = [name and name.lower() for name in monthname]
  228. def _parseRequestLine(line: bytes) -> tuple[bytes, bytes, bytes]:
  229. """
  230. Parse an HTTP request line, which looks like:
  231. GET /foo/bar HTTP/1.1
  232. This function attempts to validate the well-formedness of
  233. the line. RFC 9112 section 3 provides this ABNF:
  234. request-line = method SP request-target SP HTTP-version
  235. We allow any method that is a valid token:
  236. method = token
  237. token = 1*tchar
  238. tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  239. / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  240. / DIGIT / ALPHA
  241. We allow any non-empty request-target that contains only printable
  242. ASCII characters (no whitespace).
  243. The RFC defines HTTP-version like this:
  244. HTTP-version = HTTP-name "/" DIGIT "." DIGIT
  245. HTTP-name = %s"HTTP"
  246. However, this function is more strict than the RFC: we only allow
  247. HTTP versions of 1.0 and 1.1, as later versions of HTTP don't use
  248. a request line.
  249. @returns: C{(method, request, version)} three-tuple
  250. @raises: L{ValueError} when malformed
  251. """
  252. method, request, version = line.split(b" ")
  253. if not _istoken(method):
  254. raise ValueError("Invalid method")
  255. for c in request:
  256. if c <= 32 or c > 176:
  257. raise ValueError("Invalid request-target")
  258. if request == b"":
  259. raise ValueError("Empty request-target")
  260. if version != b"HTTP/1.1" and version != b"HTTP/1.0":
  261. raise ValueError("Invalid version")
  262. return method, request, version
  263. def _parseContentType(line: bytes) -> bytes:
  264. """
  265. Parse the Content-Type header.
  266. """
  267. msg = EmailMessage()
  268. msg["content-type"] = line.decode("charmap")
  269. key = msg.get_content_type()
  270. encodedKey = key.encode("charmap")
  271. return encodedKey
  272. class _MultiPartParseException(Exception):
  273. """
  274. Failed to parse the multipart/form-data payload.
  275. """
  276. def _getMultiPartArgs(content: bytes, ctype: bytes) -> dict[bytes, list[bytes]]:
  277. """
  278. Parse the content of a multipart/form-data request.
  279. """
  280. result = {}
  281. multiPartHeaders = b"MIME-Version: 1.0\r\n" + b"Content-Type: " + ctype + b"\r\n"
  282. msg = message_from_bytes(multiPartHeaders + content)
  283. if not msg.is_multipart():
  284. raise _MultiPartParseException("Not a multipart.")
  285. part: Message
  286. # "per Python docs, a list of Message objects when is_multipart() is True,
  287. # or a string when is_multipart() is False"
  288. for part in msg.get_payload(): # type:ignore[assignment]
  289. name: str | None = part.get_param(
  290. "name", header="content-disposition"
  291. ) # type:ignore[assignment]
  292. if not name:
  293. continue
  294. payload: bytes = part.get_payload(decode=True) # type:ignore[assignment]
  295. result[name.encode("utf8")] = [payload]
  296. return result
  297. def urlparse(url):
  298. """
  299. Parse an URL into six components.
  300. This is similar to C{urlparse.urlparse}, but rejects C{str} input
  301. and always produces C{bytes} output.
  302. @type url: C{bytes}
  303. @raise TypeError: The given url was a C{str} string instead of a
  304. C{bytes}.
  305. @return: The scheme, net location, path, params, query string, and fragment
  306. of the URL - all as C{bytes}.
  307. @rtype: C{ParseResultBytes}
  308. """
  309. if isinstance(url, str):
  310. raise TypeError("url must be bytes, not unicode")
  311. scheme, netloc, path, params, query, fragment = _urlparse(url)
  312. if isinstance(scheme, str):
  313. scheme = scheme.encode("ascii")
  314. netloc = netloc.encode("ascii")
  315. path = path.encode("ascii")
  316. query = query.encode("ascii")
  317. fragment = fragment.encode("ascii")
  318. return ParseResultBytes(scheme, netloc, path, params, query, fragment)
  319. def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
  320. """
  321. Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3.
  322. This was created to help with Python 2 to Python 3 migration.
  323. Consider using L{urllib.parse.parse_qs}.
  324. @type qs: C{bytes}
  325. """
  326. d = {}
  327. items = [s2 for s1 in qs.split(b"&") for s2 in s1.split(b";")]
  328. for item in items:
  329. try:
  330. k, v = item.split(b"=", 1)
  331. except ValueError:
  332. if strict_parsing:
  333. raise
  334. continue
  335. if v or keep_blank_values:
  336. k = unquote(k.replace(b"+", b" "))
  337. v = unquote(v.replace(b"+", b" "))
  338. if k in d:
  339. d[k].append(v)
  340. else:
  341. d[k] = [v]
  342. return d
  343. def datetimeToString(msSinceEpoch=None):
  344. """
  345. Convert seconds since epoch to HTTP datetime string.
  346. @rtype: C{bytes}
  347. """
  348. year, month, day, hh, mm, ss, wd, _, _ = (
  349. gmtime() if msSinceEpoch is None else gmtime(msSinceEpoch)
  350. )
  351. return b"%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
  352. _weekdaynameBytes[wd],
  353. day,
  354. _monthnameBytes[month],
  355. year,
  356. hh,
  357. mm,
  358. ss,
  359. )
  360. def datetimeToLogString(msSinceEpoch=None):
  361. """
  362. Convert seconds since epoch to log datetime string.
  363. @rtype: C{str}
  364. """
  365. if msSinceEpoch == None:
  366. # This code path is apparently never used in practice inside Twisted.
  367. msSinceEpoch = time() # pragma: no cover
  368. year, month, day, hh, mm, ss, wd, y, z = gmtime(msSinceEpoch)
  369. s = "[%02d/%3s/%4d:%02d:%02d:%02d +0000]" % (
  370. day,
  371. monthname[month],
  372. year,
  373. hh,
  374. mm,
  375. ss,
  376. )
  377. return s
  378. def timegm(year, month, day, hour, minute, second):
  379. """
  380. Convert time tuple in GMT to seconds since epoch, GMT
  381. """
  382. EPOCH = 1970
  383. if year < EPOCH:
  384. raise ValueError("Years prior to %d not supported" % (EPOCH,))
  385. assert 1 <= month <= 12
  386. days = 365 * (year - EPOCH) + calendar.leapdays(EPOCH, year)
  387. for i in range(1, month):
  388. days = days + calendar.mdays[i]
  389. if month > 2 and calendar.isleap(year):
  390. days = days + 1
  391. days = days + day - 1
  392. hours = days * 24 + hour
  393. minutes = hours * 60 + minute
  394. seconds = minutes * 60 + second
  395. return seconds
  396. def stringToDatetime(dateString):
  397. """
  398. Convert an HTTP date string (one of three formats) to seconds since epoch.
  399. @type dateString: C{bytes}
  400. """
  401. parts = dateString.decode("ascii").split()
  402. if not parts[0][0:3].lower() in weekdayname_lower:
  403. # Weekday is stupid. Might have been omitted.
  404. try:
  405. return stringToDatetime(b"Sun, " + dateString)
  406. except ValueError:
  407. # Guess not.
  408. pass
  409. partlen = len(parts)
  410. if (partlen == 5 or partlen == 6) and parts[1].isdigit():
  411. # 1st date format: Sun, 06 Nov 1994 08:49:37 GMT
  412. # (Note: "GMT" is literal, not a variable timezone)
  413. # (also handles without "GMT")
  414. # This is the normal format
  415. day = parts[1]
  416. month = parts[2]
  417. year = parts[3]
  418. time = parts[4]
  419. elif (partlen == 3 or partlen == 4) and parts[1].find("-") != -1:
  420. # 2nd date format: Sunday, 06-Nov-94 08:49:37 GMT
  421. # (Note: "GMT" is literal, not a variable timezone)
  422. # (also handles without without "GMT")
  423. # Two digit year, yucko.
  424. day, month, year = parts[1].split("-")
  425. time = parts[2]
  426. year = int(year)
  427. if year < 69:
  428. year = year + 2000
  429. elif year < 100:
  430. year = year + 1900
  431. elif len(parts) == 5:
  432. # 3rd date format: Sun Nov 6 08:49:37 1994
  433. # ANSI C asctime() format.
  434. day = parts[2]
  435. month = parts[1]
  436. year = parts[4]
  437. time = parts[3]
  438. else:
  439. raise ValueError("Unknown datetime format %r" % dateString)
  440. day = int(day)
  441. month = int(monthname_lower.index(month.lower()))
  442. year = int(year)
  443. hour, min, sec = map(int, time.split(":"))
  444. return int(timegm(year, month, day, hour, min, sec))
  445. def toChunk(data):
  446. """
  447. Convert string to a chunk.
  448. @type data: C{bytes}
  449. @returns: a tuple of C{bytes} representing the chunked encoding of data
  450. """
  451. return (networkString(f"{len(data):x}"), b"\r\n", data, b"\r\n")
  452. def fromChunk(data: bytes) -> Tuple[bytes, bytes]:
  453. """
  454. Convert chunk to string.
  455. Note that this function is not specification compliant: it doesn't handle
  456. chunk extensions.
  457. @type data: C{bytes}
  458. @return: tuple of (result, remaining) - both C{bytes}.
  459. @raise ValueError: If the given data is not a correctly formatted chunked
  460. byte string.
  461. """
  462. prefix, rest = data.split(b"\r\n", 1)
  463. length = _hexint(prefix)
  464. if length < 0:
  465. raise ValueError("Chunk length must be >= 0, not %d" % (length,))
  466. if rest[length : length + 2] != b"\r\n":
  467. raise ValueError("chunk must end with CRLF")
  468. return rest[:length], rest[length + 2 :]
  469. def parseContentRange(header):
  470. """
  471. Parse a content-range header into (start, end, realLength).
  472. realLength might be None if real length is not known ('*').
  473. """
  474. kind, other = header.strip().split()
  475. if kind.lower() != "bytes":
  476. raise ValueError("a range of type %r is not supported")
  477. startend, realLength = other.split("/")
  478. start, end = map(int, startend.split("-"))
  479. if realLength == "*":
  480. realLength = None
  481. else:
  482. realLength = int(realLength)
  483. return (start, end, realLength)
  484. class _IDeprecatedHTTPChannelToRequestInterface(Interface):
  485. """
  486. The interface L{HTTPChannel} expects of L{Request}.
  487. """
  488. requestHeaders = Attribute(
  489. "A L{http_headers.Headers} instance giving all received HTTP request "
  490. "headers."
  491. )
  492. responseHeaders = Attribute(
  493. "A L{http_headers.Headers} instance holding all HTTP response "
  494. "headers to be sent."
  495. )
  496. def connectionLost(reason):
  497. """
  498. The underlying connection has been lost.
  499. @param reason: A failure instance indicating the reason why
  500. the connection was lost.
  501. @type reason: L{twisted.python.failure.Failure}
  502. """
  503. def gotLength(length):
  504. """
  505. Called when L{HTTPChannel} has determined the length, if any,
  506. of the incoming request's body.
  507. @param length: The length of the request's body.
  508. @type length: L{int} if the request declares its body's length
  509. and L{None} if it does not.
  510. """
  511. def handleContentChunk(data):
  512. """
  513. Deliver a received chunk of body data to the request. Note
  514. this does not imply chunked transfer encoding.
  515. @param data: The received chunk.
  516. @type data: L{bytes}
  517. """
  518. def parseCookies():
  519. """
  520. Parse the request's cookies out of received headers.
  521. """
  522. def requestReceived(command, path, version):
  523. """
  524. Called when the entire request, including its body, has been
  525. received.
  526. @param command: The request's HTTP command.
  527. @type command: L{bytes}
  528. @param path: The request's path. Note: this is actually what
  529. RFC7320 calls the URI.
  530. @type path: L{bytes}
  531. @param version: The request's HTTP version.
  532. @type version: L{bytes}
  533. """
  534. def __eq__(other: object) -> bool:
  535. """
  536. Determines if two requests are the same object.
  537. @param other: Another object whose identity will be compared
  538. to this instance's.
  539. @return: L{True} when the two are the same object and L{False}
  540. when not.
  541. """
  542. def __ne__(other: object) -> bool:
  543. """
  544. Determines if two requests are not the same object.
  545. @param other: Another object whose identity will be compared
  546. to this instance's.
  547. @return: L{True} when the two are not the same object and
  548. L{False} when they are.
  549. """
  550. def __hash__():
  551. """
  552. Generate a hash value for the request.
  553. @return: The request's hash value.
  554. @rtype: L{int}
  555. """
  556. class StringTransport:
  557. """
  558. I am a BytesIO wrapper that conforms for the transport API. I support
  559. the `writeSequence' method.
  560. """
  561. def __init__(self):
  562. self.s = BytesIO()
  563. def writeSequence(self, seq):
  564. self.s.write(b"".join(seq))
  565. def __getattr__(self, attr):
  566. return getattr(self.__dict__["s"], attr)
  567. class HTTPClient(basic.LineReceiver):
  568. """
  569. A client for HTTP 1.0.
  570. Notes:
  571. You probably want to send a 'Host' header with the name of the site you're
  572. connecting to, in order to not break name based virtual hosting.
  573. @ivar length: The length of the request body in bytes.
  574. @type length: C{int}
  575. @ivar firstLine: Are we waiting for the first header line?
  576. @type firstLine: C{bool}
  577. @ivar __buffer: The buffer that stores the response to the HTTP request.
  578. @type __buffer: A C{BytesIO} object.
  579. @ivar _header: Part or all of an HTTP request header.
  580. @type _header: C{bytes}
  581. """
  582. length = None
  583. firstLine = True
  584. __buffer = None
  585. _header = b""
  586. def sendCommand(self, command, path):
  587. self.transport.writeSequence([command, b" ", path, b" HTTP/1.0\r\n"])
  588. def sendHeader(self, name, value):
  589. if not isinstance(value, bytes):
  590. # XXX Deprecate this case
  591. value = networkString(str(value))
  592. santizedName = _sanitizeLinearWhitespace(name)
  593. santizedValue = _sanitizeLinearWhitespace(value)
  594. self.transport.writeSequence([santizedName, b": ", santizedValue, b"\r\n"])
  595. def endHeaders(self):
  596. self.transport.write(b"\r\n")
  597. def extractHeader(self, header):
  598. """
  599. Given a complete HTTP header, extract the field name and value and
  600. process the header.
  601. @param header: a complete HTTP request header of the form
  602. 'field-name: value'.
  603. @type header: C{bytes}
  604. """
  605. key, val = header.split(b":", 1)
  606. val = val.lstrip()
  607. self.handleHeader(key, val)
  608. if key.lower() == b"content-length":
  609. self.length = int(val)
  610. def lineReceived(self, line):
  611. """
  612. Parse the status line and headers for an HTTP request.
  613. @param line: Part of an HTTP request header. Request bodies are parsed
  614. in L{HTTPClient.rawDataReceived}.
  615. @type line: C{bytes}
  616. """
  617. if self.firstLine:
  618. self.firstLine = False
  619. l = line.split(None, 2)
  620. version = l[0]
  621. status = l[1]
  622. try:
  623. message = l[2]
  624. except IndexError:
  625. # sometimes there is no message
  626. message = b""
  627. self.handleStatus(version, status, message)
  628. return
  629. if not line:
  630. if self._header != b"":
  631. # Only extract headers if there are any
  632. self.extractHeader(self._header)
  633. self.__buffer = BytesIO()
  634. self.handleEndHeaders()
  635. self.setRawMode()
  636. return
  637. if line.startswith(b"\t") or line.startswith(b" "):
  638. # This line is part of a multiline header. According to RFC 822, in
  639. # "unfolding" multiline headers you do not strip the leading
  640. # whitespace on the continuing line.
  641. self._header = self._header + line
  642. elif self._header:
  643. # This line starts a new header, so process the previous one.
  644. self.extractHeader(self._header)
  645. self._header = line
  646. else: # First header
  647. self._header = line
  648. def connectionLost(self, reason):
  649. self.handleResponseEnd()
  650. def handleResponseEnd(self):
  651. """
  652. The response has been completely received.
  653. This callback may be invoked more than once per request.
  654. """
  655. if self.__buffer is not None:
  656. b = self.__buffer.getvalue()
  657. self.__buffer = None
  658. self.handleResponse(b)
  659. def handleResponsePart(self, data):
  660. self.__buffer.write(data)
  661. def connectionMade(self):
  662. pass
  663. def handleStatus(self, version, status, message):
  664. """
  665. Called when the status-line is received.
  666. @param version: e.g. 'HTTP/1.0'
  667. @param status: e.g. '200'
  668. @type status: C{bytes}
  669. @param message: e.g. 'OK'
  670. """
  671. def handleHeader(self, key, val):
  672. """
  673. Called every time a header is received.
  674. """
  675. def handleEndHeaders(self):
  676. """
  677. Called when all headers have been received.
  678. """
  679. def rawDataReceived(self, data):
  680. if self.length is not None:
  681. data, rest = data[: self.length], data[self.length :]
  682. self.length -= len(data)
  683. else:
  684. rest = b""
  685. self.handleResponsePart(data)
  686. if self.length == 0:
  687. self.handleResponseEnd()
  688. self.setLineMode(rest)
  689. deprecatedModuleAttribute(
  690. Version("Twisted", 24, 7, 0),
  691. "Use twisted.web.client.Agent instead.",
  692. __name__,
  693. HTTPClient.__name__,
  694. )
  695. # response codes that must have empty bodies
  696. NO_BODY_CODES = (204, 304)
  697. # Sentinel object that detects people explicitly passing `queued` to Request.
  698. _QUEUED_SENTINEL = object()
  699. def _getContentFile(length):
  700. """
  701. Get a writeable file-like object to which request content can be written.
  702. """
  703. if length is not None and length < 100000:
  704. return BytesIO()
  705. return tempfile.TemporaryFile()
  706. _hostHeaderExpression = re.compile(rb"^\[?(?P<host>.*?)\]?(:\d+)?$")
  707. @implementer(interfaces.IConsumer, _IDeprecatedHTTPChannelToRequestInterface)
  708. class Request:
  709. """
  710. A HTTP request.
  711. Subclasses should override the process() method to determine how
  712. the request will be processed.
  713. @ivar method: The HTTP method that was used, e.g. C{b'GET'}.
  714. @type method: L{bytes}
  715. @ivar uri: The full encoded URI which was requested (including query
  716. arguments), e.g. C{b'/a/b%20/c?q=v'}.
  717. @type uri: L{bytes}
  718. @ivar path: The encoded path of the request URI (not including query
  719. arguments), e.g. C{b'/a/b%20/c'}.
  720. @type path: L{bytes}
  721. @ivar args: A mapping of decoded query argument names as L{bytes} to
  722. corresponding query argument values as L{list}s of L{bytes}.
  723. For example, for a URI with C{foo=bar&foo=baz&quux=spam}
  724. as its query part C{args} will be C{{b'foo': [b'bar', b'baz'],
  725. b'quux': [b'spam']}}.
  726. @type args: L{dict} of L{bytes} to L{list} of L{bytes}
  727. @ivar content: A file-like object giving the request body. This may be
  728. a file on disk, an L{io.BytesIO}, or some other type. The
  729. implementation is free to decide on a per-request basis.
  730. @type content: L{typing.BinaryIO}
  731. @ivar cookies: The cookies that will be sent in the response.
  732. @type cookies: L{list} of L{bytes}
  733. @type requestHeaders: L{http_headers.Headers}
  734. @ivar requestHeaders: All received HTTP request headers.
  735. @type responseHeaders: L{http_headers.Headers}
  736. @ivar responseHeaders: All HTTP response headers to be sent.
  737. @ivar notifications: A L{list} of L{Deferred}s which are waiting for
  738. notification that the response to this request has been finished
  739. (successfully or with an error). Don't use this attribute directly,
  740. instead use the L{Request.notifyFinish} method.
  741. @ivar _disconnected: A flag which is C{False} until the connection over
  742. which this request was received is closed and which is C{True} after
  743. that.
  744. @type _disconnected: L{bool}
  745. @ivar _log: A logger instance for request related messages.
  746. @type _log: L{twisted.logger.Logger}
  747. """
  748. producer = None
  749. finished = 0
  750. code = OK
  751. code_message = RESPONSES[OK]
  752. method = b"(no method yet)"
  753. clientproto = b"(no clientproto yet)"
  754. uri = b"(no uri yet)"
  755. startedWriting = 0
  756. chunked = 0
  757. sentLength = 0 # content-length of response, or total bytes sent via chunking
  758. etag = None
  759. lastModified = None
  760. args = None
  761. path = None
  762. content = None
  763. _forceSSL = 0
  764. _disconnected = False
  765. _log = Logger()
  766. def __init__(self, channel: HTTPChannel, queued: object = _QUEUED_SENTINEL) -> None:
  767. """
  768. @param channel: the channel we're connected to.
  769. @param queued: (deprecated) are we in the request queue, or can we
  770. start writing to the transport?
  771. """
  772. self.notifications: List[Deferred[None]] = []
  773. self.channel = channel
  774. # Cache the client and server information, we'll need this
  775. # later to be serialized and sent with the request so CGIs
  776. # will work remotely
  777. self.client = self.channel.getPeer()
  778. self.host = self.channel.getHost()
  779. self.requestHeaders: Headers = Headers()
  780. self.received_cookies: Dict[bytes, bytes] = {}
  781. self.responseHeaders: Headers = Headers()
  782. self.cookies: List[bytes] = [] # outgoing cookies
  783. self.transport = self.channel.transport
  784. if queued is _QUEUED_SENTINEL:
  785. queued = False
  786. self.queued = queued
  787. def _cleanup(self):
  788. """
  789. Called when have finished responding and are no longer queued.
  790. """
  791. if self.producer:
  792. self._log.failure(
  793. "",
  794. Failure(RuntimeError(f"Producer was not unregistered for {self.uri}")),
  795. )
  796. self.unregisterProducer()
  797. self.channel.requestDone(self)
  798. del self.channel
  799. if self.content is not None:
  800. try:
  801. self.content.close()
  802. except OSError:
  803. # win32 suckiness, no idea why it does this
  804. pass
  805. del self.content
  806. for d in self.notifications:
  807. d.callback(None)
  808. self.notifications = []
  809. # methods for channel - end users should not use these
  810. @deprecated(Version("Twisted", 16, 3, 0))
  811. def noLongerQueued(self):
  812. """
  813. Notify the object that it is no longer queued.
  814. We start writing whatever data we have to the transport, etc.
  815. This method is not intended for users.
  816. In 16.3 this method was changed to become a no-op, as L{Request}
  817. objects are now never queued.
  818. """
  819. pass
  820. def gotLength(self, length):
  821. """
  822. Called when HTTP channel got length of content in this request.
  823. This method is not intended for users.
  824. @param length: The length of the request body, as indicated by the
  825. request headers. L{None} if the request headers do not indicate a
  826. length.
  827. """
  828. self.content = _getContentFile(length)
  829. def parseCookies(self):
  830. """
  831. Parse cookie headers.
  832. This method is not intended for users.
  833. """
  834. cookieheaders = self.requestHeaders.getRawHeaders(b"Cookie")
  835. if cookieheaders is None:
  836. return
  837. for cookietxt in cookieheaders:
  838. if cookietxt:
  839. for cook in cookietxt.split(b";"):
  840. cook = cook.lstrip()
  841. try:
  842. k, v = cook.split(b"=", 1)
  843. self.received_cookies[k] = v
  844. except ValueError:
  845. pass
  846. def handleContentChunk(self, data):
  847. """
  848. Write a chunk of data.
  849. This method is not intended for users.
  850. """
  851. self.content.write(data)
  852. def requestReceived(self, command, path, version):
  853. """
  854. Called by channel when all data has been received.
  855. This method is not intended for users.
  856. @type command: C{bytes}
  857. @param command: The HTTP verb of this request. This has the case
  858. supplied by the client (eg, it maybe "get" rather than "GET").
  859. @type path: C{bytes}
  860. @param path: The URI of this request.
  861. @type version: C{bytes}
  862. @param version: The HTTP version of this request.
  863. """
  864. clength = self.content.tell()
  865. self.content.seek(0, 0)
  866. self.args = {}
  867. self.method, self.uri = command, path
  868. self.clientproto = version
  869. x = self.uri.split(b"?", 1)
  870. if len(x) == 1:
  871. self.path = self.uri
  872. else:
  873. self.path, argstring = x
  874. self.args = parse_qs(argstring, 1)
  875. # Argument processing
  876. args = self.args
  877. ctype = self.requestHeaders.getRawHeaders(b"Content-Type")
  878. if ctype is not None:
  879. ctype = ctype[0]
  880. if self.method == b"POST" and ctype and clength:
  881. mfd = b"multipart/form-data"
  882. key = _parseContentType(ctype)
  883. if key == b"application/x-www-form-urlencoded":
  884. args.update(parse_qs(self.content.read(), 1))
  885. elif key == mfd:
  886. try:
  887. self.content.seek(0)
  888. content = self.content.read()
  889. self.args.update(_getMultiPartArgs(content, ctype))
  890. except _MultiPartParseException:
  891. # It was a bad request.
  892. self.channel._respondToBadRequestAndDisconnect()
  893. return
  894. self.content.seek(0, 0)
  895. self.process()
  896. def __repr__(self) -> str:
  897. """
  898. Return a string description of the request including such information
  899. as the request method and request URI.
  900. @return: A string loosely describing this L{Request} object.
  901. @rtype: L{str}
  902. """
  903. return "<{} at 0x{:x} method={} uri={} clientproto={}>".format(
  904. self.__class__.__name__,
  905. id(self),
  906. nativeString(self.method),
  907. nativeString(self.uri),
  908. nativeString(self.clientproto),
  909. )
  910. def process(self):
  911. """
  912. Override in subclasses.
  913. This method is not intended for users.
  914. """
  915. pass
  916. # consumer interface
  917. def registerProducer(self, producer, streaming):
  918. """
  919. Register a producer.
  920. """
  921. if self.producer:
  922. raise ValueError(
  923. "registering producer %s before previous one (%s) was "
  924. "unregistered" % (producer, self.producer)
  925. )
  926. self.streamingProducer = streaming
  927. self.producer = producer
  928. self.channel.registerProducer(producer, streaming)
  929. def unregisterProducer(self):
  930. """
  931. Unregister the producer.
  932. """
  933. self.channel.unregisterProducer()
  934. self.producer = None
  935. # The following is the public interface that people should be
  936. # writing to.
  937. def getHeader(self, key: AnyStr) -> Optional[AnyStr]:
  938. """
  939. Get an HTTP request header.
  940. @type key: C{bytes} or C{str}
  941. @param key: The name of the header to get the value of.
  942. @rtype: C{bytes} or C{str} or L{None}
  943. @return: The value of the specified header, or L{None} if that header
  944. was not present in the request. The string type of the result
  945. matches the type of C{key}.
  946. """
  947. value = self.requestHeaders.getRawHeaders(key)
  948. if value is not None:
  949. return value[-1]
  950. return None
  951. def getCookie(self, key):
  952. """
  953. Get a cookie that was sent from the network.
  954. @type key: C{bytes}
  955. @param key: The name of the cookie to get.
  956. @rtype: C{bytes} or C{None}
  957. @returns: The value of the specified cookie, or L{None} if that cookie
  958. was not present in the request.
  959. """
  960. return self.received_cookies.get(key)
  961. def notifyFinish(self) -> Deferred[None]:
  962. """
  963. Notify when the response to this request has finished.
  964. @note: There are some caveats around the reliability of the delivery of
  965. this notification.
  966. 1. If this L{Request}'s channel is paused, the notification
  967. will not be delivered. This can happen in one of two ways;
  968. either you can call C{request.transport.pauseProducing}
  969. yourself, or,
  970. 2. In order to deliver this notification promptly when a client
  971. disconnects, the reactor must continue reading from the
  972. transport, so that it can tell when the underlying network
  973. connection has gone away. Twisted Web will only keep
  974. reading up until a finite (small) maximum buffer size before
  975. it gives up and pauses the transport itself. If this
  976. occurs, you will not discover that the connection has gone
  977. away until a timeout fires or until the application attempts
  978. to send some data via L{Request.write}.
  979. 3. It is theoretically impossible to distinguish between
  980. successfully I{sending} a response and the peer successfully
  981. I{receiving} it. There are several networking edge cases
  982. where the L{Deferred}s returned by C{notifyFinish} will
  983. indicate success, but the data will never be received.
  984. There are also edge cases where the connection will appear
  985. to fail, but in reality the response was delivered. As a
  986. result, the information provided by the result of the
  987. L{Deferred}s returned by this method should be treated as a
  988. guess; do not make critical decisions in your applications
  989. based upon it.
  990. @rtype: L{Deferred}
  991. @return: A L{Deferred} which will be triggered when the request is
  992. finished -- with a L{None} value if the request finishes
  993. successfully or with an error if the request is interrupted by an
  994. error (for example, the client closing the connection prematurely).
  995. """
  996. self.notifications.append(Deferred())
  997. return self.notifications[-1]
  998. def finish(self):
  999. """
  1000. Indicate that all response data has been written to this L{Request}.
  1001. """
  1002. if self._disconnected:
  1003. raise RuntimeError(
  1004. "Request.finish called on a request after its connection was lost; "
  1005. "use Request.notifyFinish to keep track of this."
  1006. )
  1007. if self.finished:
  1008. warnings.warn("Warning! request.finish called twice.", stacklevel=2)
  1009. return
  1010. if not self.startedWriting:
  1011. # write headers
  1012. self.write(b"")
  1013. if self.chunked:
  1014. # write last chunk and closing CRLF
  1015. self.channel.write(b"0\r\n\r\n")
  1016. # log request
  1017. if hasattr(self.channel, "factory") and self.channel.factory is not None:
  1018. self.channel.factory.log(self)
  1019. self.finished = 1
  1020. if not self.queued:
  1021. self._cleanup()
  1022. def write(self, data):
  1023. """
  1024. Write some data as a result of an HTTP request. The first
  1025. time this is called, it writes out response data.
  1026. @type data: C{bytes}
  1027. @param data: Some bytes to be sent as part of the response body.
  1028. """
  1029. if self.finished:
  1030. raise RuntimeError(
  1031. "Request.write called on a request after Request.finish was called."
  1032. )
  1033. if self._disconnected:
  1034. # Don't attempt to write any data to a disconnected client.
  1035. # The RuntimeError exception will be thrown as usual when
  1036. # request.finish is called
  1037. return
  1038. if not self.startedWriting:
  1039. self.startedWriting = 1
  1040. version = self.clientproto
  1041. code = b"%d" % (self.code,)
  1042. reason = self.code_message
  1043. # if we don't have a content length, we send data in
  1044. # chunked mode, so that we can support pipelining in
  1045. # persistent connections.
  1046. if (
  1047. (version == b"HTTP/1.1")
  1048. and (self.responseHeaders.getRawHeaders(b"Content-Length") is None)
  1049. and self.method != b"HEAD"
  1050. and self.code not in NO_BODY_CODES
  1051. ):
  1052. self.responseHeaders.setRawHeaders("Transfer-Encoding", [b"chunked"])
  1053. self.chunked = 1
  1054. if self.lastModified is not None:
  1055. if self.responseHeaders.hasHeader(b"Last-Modified"):
  1056. self._log.info(
  1057. "Warning: last-modified specified both in"
  1058. " header list and lastModified attribute."
  1059. )
  1060. else:
  1061. self.responseHeaders.setRawHeaders(
  1062. b"Last-Modified", [datetimeToString(self.lastModified)]
  1063. )
  1064. if self.etag is not None:
  1065. self.responseHeaders.setRawHeaders(b"ETag", [self.etag])
  1066. if self.cookies:
  1067. self.responseHeaders.setRawHeaders(b"Set-Cookie", self.cookies)
  1068. self.channel.writeHeaders(version, code, reason, self.responseHeaders)
  1069. # if this is a "HEAD" request, we shouldn't return any data
  1070. if self.method == b"HEAD":
  1071. self.write = lambda data: None
  1072. return
  1073. # for certain result codes, we should never return any data
  1074. if self.code in NO_BODY_CODES:
  1075. self.write = lambda data: None
  1076. return
  1077. self.sentLength = self.sentLength + len(data)
  1078. if data:
  1079. if self.chunked:
  1080. self.channel.writeSequence(toChunk(data))
  1081. else:
  1082. self.channel.write(data)
  1083. def addCookie(
  1084. self,
  1085. k,
  1086. v,
  1087. expires=None,
  1088. domain=None,
  1089. path=None,
  1090. max_age=None,
  1091. comment=None,
  1092. secure=None,
  1093. httpOnly=False,
  1094. sameSite=None,
  1095. ):
  1096. """
  1097. Set an outgoing HTTP cookie.
  1098. In general, you should consider using sessions instead of cookies, see
  1099. L{twisted.web.server.Request.getSession} and the
  1100. L{twisted.web.server.Session} class for details.
  1101. @param k: cookie name
  1102. @type k: L{bytes} or L{str}
  1103. @param v: cookie value
  1104. @type v: L{bytes} or L{str}
  1105. @param expires: cookie expire attribute value in
  1106. "Wdy, DD Mon YYYY HH:MM:SS GMT" format
  1107. @type expires: L{bytes} or L{str}
  1108. @param domain: cookie domain
  1109. @type domain: L{bytes} or L{str}
  1110. @param path: cookie path
  1111. @type path: L{bytes} or L{str}
  1112. @param max_age: cookie expiration in seconds from reception
  1113. @type max_age: L{bytes} or L{str}
  1114. @param comment: cookie comment
  1115. @type comment: L{bytes} or L{str}
  1116. @param secure: direct browser to send the cookie on encrypted
  1117. connections only
  1118. @type secure: L{bool}
  1119. @param httpOnly: direct browser not to expose cookies through channels
  1120. other than HTTP (and HTTPS) requests
  1121. @type httpOnly: L{bool}
  1122. @param sameSite: One of L{None} (default), C{'lax'} or C{'strict'}.
  1123. Direct browsers not to send this cookie on cross-origin requests.
  1124. Please see:
  1125. U{https://tools.ietf.org/html/draft-west-first-party-cookies-07}
  1126. @type sameSite: L{None}, L{bytes} or L{str}
  1127. @raise ValueError: If the value for C{sameSite} is not supported.
  1128. """
  1129. def _ensureBytes(val):
  1130. """
  1131. Ensure that C{val} is bytes, encoding using UTF-8 if
  1132. needed.
  1133. @param val: L{bytes} or L{str}
  1134. @return: L{bytes}
  1135. """
  1136. if val is None:
  1137. # It's None, so we don't want to touch it
  1138. return val
  1139. if isinstance(val, bytes):
  1140. return val
  1141. else:
  1142. return val.encode("utf8")
  1143. def _sanitize(val):
  1144. r"""
  1145. Replace linear whitespace (C{\r}, C{\n}, C{\r\n}) and
  1146. semicolons C{;} in C{val} with a single space.
  1147. @param val: L{bytes}
  1148. @return: L{bytes}
  1149. """
  1150. return _sanitizeLinearWhitespace(val).replace(b";", b" ")
  1151. cookie = _sanitize(_ensureBytes(k)) + b"=" + _sanitize(_ensureBytes(v))
  1152. if expires is not None:
  1153. cookie = cookie + b"; Expires=" + _sanitize(_ensureBytes(expires))
  1154. if domain is not None:
  1155. cookie = cookie + b"; Domain=" + _sanitize(_ensureBytes(domain))
  1156. if path is not None:
  1157. cookie = cookie + b"; Path=" + _sanitize(_ensureBytes(path))
  1158. if max_age is not None:
  1159. cookie = cookie + b"; Max-Age=" + _sanitize(_ensureBytes(max_age))
  1160. if comment is not None:
  1161. cookie = cookie + b"; Comment=" + _sanitize(_ensureBytes(comment))
  1162. if secure:
  1163. cookie = cookie + b"; Secure"
  1164. if httpOnly:
  1165. cookie = cookie + b"; HttpOnly"
  1166. if sameSite:
  1167. sameSite = _ensureBytes(sameSite).lower()
  1168. if sameSite not in [b"lax", b"strict"]:
  1169. raise ValueError("Invalid value for sameSite: " + repr(sameSite))
  1170. cookie += b"; SameSite=" + sameSite
  1171. self.cookies.append(cookie)
  1172. def setResponseCode(self, code: int, message: Optional[bytes] = None) -> None:
  1173. """
  1174. Set the HTTP response code.
  1175. @type code: L{int}
  1176. @type message: L{bytes}
  1177. """
  1178. self.code = code
  1179. if message is not None:
  1180. self.code_message = message
  1181. else:
  1182. self.code_message = RESPONSES.get(code, b"Unknown Status")
  1183. def setHeader(self, name, value):
  1184. """
  1185. Set an HTTP response header. Overrides any previously set values for
  1186. this header.
  1187. @type name: L{bytes} or L{str}
  1188. @param name: The name of the header for which to set the value.
  1189. @type value: L{bytes} or L{str}
  1190. @param value: The value to set for the named header. A L{str} will be
  1191. UTF-8 encoded, which may not interoperable with other
  1192. implementations. Avoid passing non-ASCII characters if possible.
  1193. """
  1194. self.responseHeaders.setRawHeaders(name, [value])
  1195. def redirect(self, url):
  1196. """
  1197. Utility function that does a redirect.
  1198. Set the response code to L{FOUND} and the I{Location} header to the
  1199. given URL.
  1200. The request should have C{finish()} called after this.
  1201. @param url: I{Location} header value.
  1202. @type url: L{bytes} or L{str}
  1203. """
  1204. self.setResponseCode(FOUND)
  1205. self.setHeader(b"Location", url)
  1206. def setLastModified(self, when):
  1207. """
  1208. Set the C{Last-Modified} time for the response to this request.
  1209. If I am called more than once, I ignore attempts to set
  1210. Last-Modified earlier, only replacing the Last-Modified time
  1211. if it is to a later value.
  1212. If I am a conditional request, I may modify my response code
  1213. to L{NOT_MODIFIED} if appropriate for the time given.
  1214. @param when: The last time the resource being returned was
  1215. modified, in seconds since the epoch.
  1216. @type when: number
  1217. @return: If I am a I{If-Modified-Since} conditional request and
  1218. the time given is not newer than the condition, I return
  1219. L{http.CACHED<CACHED>} to indicate that you should write no
  1220. body. Otherwise, I return a false value.
  1221. """
  1222. # time.time() may be a float, but the HTTP-date strings are
  1223. # only good for whole seconds.
  1224. when = int(math.ceil(when))
  1225. if (not self.lastModified) or (self.lastModified < when):
  1226. self.lastModified = when
  1227. modifiedSince = self.getHeader(b"If-Modified-Since")
  1228. if modifiedSince:
  1229. firstPart = modifiedSince.split(b";", 1)[0]
  1230. try:
  1231. modifiedSince = stringToDatetime(firstPart)
  1232. except ValueError:
  1233. return None
  1234. if modifiedSince >= self.lastModified:
  1235. self.setResponseCode(NOT_MODIFIED)
  1236. return CACHED
  1237. return None
  1238. def setETag(self, etag):
  1239. """
  1240. Set an C{entity tag} for the outgoing response.
  1241. That's \"entity tag\" as in the HTTP/1.1 C{ETag} header, \"used
  1242. for comparing two or more entities from the same requested
  1243. resource.\"
  1244. If I am a conditional request, I may modify my response code
  1245. to L{NOT_MODIFIED} or L{PRECONDITION_FAILED}, if appropriate
  1246. for the tag given.
  1247. @param etag: The entity tag for the resource being returned.
  1248. @type etag: string
  1249. @return: If I am a C{If-None-Match} conditional request and
  1250. the tag matches one in the request, I return
  1251. L{http.CACHED<CACHED>} to indicate that you should write
  1252. no body. Otherwise, I return a false value.
  1253. """
  1254. if etag:
  1255. self.etag = etag
  1256. tags = self.getHeader(b"If-None-Match")
  1257. if tags:
  1258. tags = tags.split()
  1259. if (etag in tags) or (b"*" in tags):
  1260. self.setResponseCode(
  1261. ((self.method in (b"HEAD", b"GET")) and NOT_MODIFIED)
  1262. or PRECONDITION_FAILED
  1263. )
  1264. return CACHED
  1265. return None
  1266. def getAllHeaders(self):
  1267. """
  1268. Return dictionary mapping the names of all received headers to the last
  1269. value received for each.
  1270. Since this method does not return all header information,
  1271. C{self.requestHeaders.getAllRawHeaders()} may be preferred.
  1272. """
  1273. headers = {}
  1274. for k, v in self.requestHeaders.getAllRawHeaders():
  1275. headers[k.lower()] = v[-1]
  1276. return headers
  1277. def getRequestHostname(self):
  1278. """
  1279. Get the hostname that the HTTP client passed in to the request.
  1280. @see: L{IRequest.getRequestHostname}
  1281. @returns: the requested hostname
  1282. @rtype: C{bytes}
  1283. """
  1284. host = self.getHeader(b"Host")
  1285. if host is not None:
  1286. match = _hostHeaderExpression.match(host)
  1287. if match is not None:
  1288. return match.group("host")
  1289. return networkString(self.getHost().host)
  1290. def getHost(self):
  1291. """
  1292. Get my originally requesting transport's host.
  1293. Don't rely on the 'transport' attribute, since Request objects may be
  1294. copied remotely. For information on this method's return value, see
  1295. L{twisted.internet.tcp.Port}.
  1296. """
  1297. return self.host
  1298. def setHost(self, host, port, ssl=0):
  1299. """
  1300. Change the host and port the request thinks it's using.
  1301. This method is useful for working with reverse HTTP proxies (e.g.
  1302. both Squid and Apache's mod_proxy can do this), when the address
  1303. the HTTP client is using is different than the one we're listening on.
  1304. For example, Apache may be listening on https://www.example.com/, and
  1305. then forwarding requests to http://localhost:8080/, but we don't want
  1306. HTML produced by Twisted to say b'http://localhost:8080/', they should
  1307. say b'https://www.example.com/', so we do::
  1308. request.setHost(b'www.example.com', 443, ssl=1)
  1309. @type host: C{bytes}
  1310. @param host: The value to which to change the host header.
  1311. @type ssl: C{bool}
  1312. @param ssl: A flag which, if C{True}, indicates that the request is
  1313. considered secure (if C{True}, L{isSecure} will return C{True}).
  1314. """
  1315. self._forceSSL = ssl # set first so isSecure will work
  1316. if self.isSecure():
  1317. default = 443
  1318. else:
  1319. default = 80
  1320. if port == default:
  1321. hostHeader = host
  1322. else:
  1323. hostHeader = b"%b:%d" % (host, port)
  1324. self.requestHeaders.setRawHeaders(b"Host", [hostHeader])
  1325. self.host = address.IPv4Address("TCP", host, port)
  1326. @deprecated(Version("Twisted", 18, 4, 0), replacement="getClientAddress")
  1327. def getClientIP(self):
  1328. """
  1329. Return the IP address of the client who submitted this request.
  1330. This method is B{deprecated}. Use L{getClientAddress} instead.
  1331. @returns: the client IP address
  1332. @rtype: C{str}
  1333. """
  1334. if isinstance(self.client, (address.IPv4Address, address.IPv6Address)):
  1335. return self.client.host
  1336. else:
  1337. return None
  1338. def getClientAddress(self):
  1339. """
  1340. Return the address of the client who submitted this request.
  1341. This may not be a network address (e.g., a server listening on
  1342. a UNIX domain socket will cause this to return
  1343. L{UNIXAddress}). Callers must check the type of the returned
  1344. address.
  1345. @since: 18.4
  1346. @return: the client's address.
  1347. @rtype: L{IAddress}
  1348. """
  1349. return self.client
  1350. def isSecure(self):
  1351. """
  1352. Return L{True} if this request is using a secure transport.
  1353. Normally this method returns L{True} if this request's L{HTTPChannel}
  1354. instance is using a transport that implements
  1355. L{interfaces.ISSLTransport}.
  1356. This will also return L{True} if L{Request.setHost} has been called
  1357. with C{ssl=True}.
  1358. @returns: L{True} if this request is secure
  1359. @rtype: C{bool}
  1360. """
  1361. if self._forceSSL:
  1362. return True
  1363. channel = getattr(self, "channel", None)
  1364. if channel is None:
  1365. return False
  1366. return channel.isSecure()
  1367. def _authorize(self):
  1368. # Authorization, (mostly) per the RFC
  1369. try:
  1370. authh = self.getHeader(b"Authorization")
  1371. if not authh:
  1372. self.user = self.password = b""
  1373. return
  1374. bas, upw = authh.split()
  1375. if bas.lower() != b"basic":
  1376. raise ValueError()
  1377. upw = base64.b64decode(upw)
  1378. self.user, self.password = upw.split(b":", 1)
  1379. except (binascii.Error, ValueError):
  1380. self.user = self.password = b""
  1381. except BaseException:
  1382. self._log.failure("")
  1383. self.user = self.password = b""
  1384. def getUser(self):
  1385. """
  1386. Return the HTTP user sent with this request, if any.
  1387. If no user was supplied, return the empty string.
  1388. @returns: the HTTP user, if any
  1389. @rtype: C{bytes}
  1390. """
  1391. try:
  1392. return self.user
  1393. except BaseException:
  1394. pass
  1395. self._authorize()
  1396. return self.user
  1397. def getPassword(self):
  1398. """
  1399. Return the HTTP password sent with this request, if any.
  1400. If no password was supplied, return the empty string.
  1401. @returns: the HTTP password, if any
  1402. @rtype: C{bytes}
  1403. """
  1404. try:
  1405. return self.password
  1406. except BaseException:
  1407. pass
  1408. self._authorize()
  1409. return self.password
  1410. def connectionLost(self, reason):
  1411. """
  1412. There is no longer a connection for this request to respond over.
  1413. Clean up anything which can't be useful anymore.
  1414. """
  1415. self._disconnected = True
  1416. self.channel = None
  1417. if self.content is not None:
  1418. self.content.close()
  1419. for d in self.notifications:
  1420. d.errback(reason)
  1421. self.notifications = []
  1422. def loseConnection(self):
  1423. """
  1424. Pass the loseConnection through to the underlying channel.
  1425. """
  1426. if self.channel is not None:
  1427. self.channel.loseConnection()
  1428. def __eq__(self, other: object) -> bool:
  1429. """
  1430. Determines if two requests are the same object.
  1431. @param other: Another object whose identity will be compared
  1432. to this instance's.
  1433. @return: L{True} when the two are the same object and L{False}
  1434. when not.
  1435. @rtype: L{bool}
  1436. """
  1437. # When other is not an instance of request, return
  1438. # NotImplemented so that Python uses other.__eq__ to perform
  1439. # the comparison. This ensures that a Request proxy generated
  1440. # by proxyForInterface compares equal to an actual Request
  1441. # instanceby turning request != proxy into proxy != request.
  1442. if isinstance(other, Request):
  1443. return self is other
  1444. return NotImplemented
  1445. def __hash__(self):
  1446. """
  1447. A C{Request} is hashable so that it can be used as a mapping key.
  1448. @return: A C{int} based on the instance's identity.
  1449. """
  1450. return id(self)
  1451. class _DataLoss(Exception):
  1452. """
  1453. L{_DataLoss} indicates that not all of a message body was received. This
  1454. is only one of several possible exceptions which may indicate that data
  1455. was lost. Because of this, it should not be checked for by
  1456. specifically; any unexpected exception should be treated as having
  1457. caused data loss.
  1458. """
  1459. class PotentialDataLoss(Exception):
  1460. """
  1461. L{PotentialDataLoss} may be raised by a transfer encoding decoder's
  1462. C{noMoreData} method to indicate that it cannot be determined if the
  1463. entire response body has been delivered. This only occurs when making
  1464. requests to HTTP servers which do not set I{Content-Length} or a
  1465. I{Transfer-Encoding} in the response because in this case the end of the
  1466. response is indicated by the connection being closed, an event which may
  1467. also be due to a transient network problem or other error.
  1468. """
  1469. class _MalformedChunkedDataError(Exception):
  1470. """
  1471. C{_ChunkedTransferDecoder} raises L{_MalformedChunkedDataError} from its
  1472. C{dataReceived} method when it encounters malformed data. This exception
  1473. indicates a client-side error. If this exception is raised, the connection
  1474. should be dropped with a 400 error.
  1475. """
  1476. class _IdentityTransferDecoder:
  1477. """
  1478. Protocol for accumulating bytes up to a specified length. This handles the
  1479. case where no I{Transfer-Encoding} is specified.
  1480. @ivar contentLength: Counter keeping track of how many more bytes there are
  1481. to receive.
  1482. @ivar dataCallback: A one-argument callable which will be invoked each
  1483. time application data is received.
  1484. @ivar finishCallback: A one-argument callable which will be invoked when
  1485. the terminal chunk is received. It will be invoked with all bytes
  1486. which were delivered to this protocol which came after the terminal
  1487. chunk.
  1488. """
  1489. __slots__ = ["contentLength", "dataCallback", "finishCallback"]
  1490. def __init__(self, contentLength, dataCallback, finishCallback):
  1491. self.contentLength = contentLength
  1492. self.dataCallback = dataCallback
  1493. self.finishCallback = finishCallback
  1494. def dataReceived(self, data):
  1495. """
  1496. Interpret the next chunk of bytes received. Either deliver them to the
  1497. data callback or invoke the finish callback if enough bytes have been
  1498. received.
  1499. @raise RuntimeError: If the finish callback has already been invoked
  1500. during a previous call to this methood.
  1501. """
  1502. if self.dataCallback is None:
  1503. raise RuntimeError(
  1504. "_IdentityTransferDecoder cannot decode data after finishing"
  1505. )
  1506. if self.contentLength is None:
  1507. self.dataCallback(data)
  1508. elif len(data) < self.contentLength:
  1509. self.contentLength -= len(data)
  1510. self.dataCallback(data)
  1511. else:
  1512. # Make the state consistent before invoking any code belonging to
  1513. # anyone else in case noMoreData ends up being called beneath this
  1514. # stack frame.
  1515. contentLength = self.contentLength
  1516. dataCallback = self.dataCallback
  1517. finishCallback = self.finishCallback
  1518. self.dataCallback = self.finishCallback = None
  1519. self.contentLength = 0
  1520. dataCallback(data[:contentLength])
  1521. finishCallback(data[contentLength:])
  1522. def noMoreData(self):
  1523. """
  1524. All data which will be delivered to this decoder has been. Check to
  1525. make sure as much data as was expected has been received.
  1526. @raise PotentialDataLoss: If the content length is unknown.
  1527. @raise _DataLoss: If the content length is known and fewer than that
  1528. many bytes have been delivered.
  1529. @return: L{None}
  1530. """
  1531. finishCallback = self.finishCallback
  1532. self.dataCallback = self.finishCallback = None
  1533. if self.contentLength is None:
  1534. finishCallback(b"")
  1535. raise PotentialDataLoss()
  1536. elif self.contentLength != 0:
  1537. raise _DataLoss()
  1538. maxChunkSizeLineLength = 1024
  1539. _chunkExtChars = (
  1540. b"\t !\"#$%&'()*+,-./0123456789:;<=>?@"
  1541. b"ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`"
  1542. b"abcdefghijklmnopqrstuvwxyz{|}~"
  1543. b"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f"
  1544. b"\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f"
  1545. b"\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf"
  1546. b"\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf"
  1547. b"\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf"
  1548. b"\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf"
  1549. b"\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
  1550. b"\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
  1551. )
  1552. """
  1553. Characters that are valid in a chunk extension.
  1554. See RFC 7230 section 4.1.1::
  1555. chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
  1556. chunk-ext-name = token
  1557. chunk-ext-val = token / quoted-string
  1558. And section 3.2.6::
  1559. token = 1*tchar
  1560. tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  1561. / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  1562. / DIGIT / ALPHA
  1563. ; any VCHAR, except delimiters
  1564. quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
  1565. qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text
  1566. obs-text = %x80-FF
  1567. We don't check if chunk extensions are well-formed beyond validating that they
  1568. don't contain characters outside this range.
  1569. """
  1570. class _ChunkedTransferDecoder:
  1571. """
  1572. Protocol for decoding I{chunked} Transfer-Encoding, as defined by RFC 7230,
  1573. section 4.1. This protocol can interpret the contents of a request or
  1574. response body which uses the I{chunked} Transfer-Encoding. It cannot
  1575. interpret any of the rest of the HTTP protocol.
  1576. It may make sense for _ChunkedTransferDecoder to be an actual IProtocol
  1577. implementation. Currently, the only user of this class will only ever
  1578. call dataReceived on it. However, it might be an improvement if the
  1579. user could connect this to a transport and deliver connection lost
  1580. notification. This way, `dataCallback` becomes `self.transport.write`
  1581. and perhaps `finishCallback` becomes `self.transport.loseConnection()`
  1582. (although I'm not sure where the extra data goes in that case). This
  1583. could also allow this object to indicate to the receiver of data that
  1584. the stream was not completely received, an error case which should be
  1585. noticed. -exarkun
  1586. @ivar dataCallback: A one-argument callable which will be invoked each
  1587. time application data is received. This callback is not reentrant.
  1588. @ivar finishCallback: A one-argument callable which will be invoked when
  1589. the terminal chunk is received. It will be invoked with all bytes
  1590. which were delivered to this protocol which came after the terminal
  1591. chunk.
  1592. @ivar length: Counter keeping track of how many more bytes in a chunk there
  1593. are to receive.
  1594. @ivar state: One of C{'CHUNK_LENGTH'}, C{'CRLF'}, C{'TRAILER'},
  1595. C{'BODY'}, or C{'FINISHED'}. For C{'CHUNK_LENGTH'}, data for the
  1596. chunk length line is currently being read. For C{'CRLF'}, the CR LF
  1597. pair which follows each chunk is being read. For C{'TRAILER'}, the CR
  1598. LF pair which follows the terminal 0-length chunk is currently being
  1599. read. For C{'BODY'}, the contents of a chunk are being read. For
  1600. C{'FINISHED'}, the last chunk has been completely read and no more
  1601. input is valid.
  1602. @ivar _buffer: Accumulated received data for the current state. At each
  1603. state transition this is truncated at the front so that index 0 is
  1604. where the next state shall begin.
  1605. @ivar _start: While in the C{'CHUNK_LENGTH'} and C{'TRAILER'} states,
  1606. tracks the index into the buffer at which search for CRLF should resume.
  1607. Resuming the search at this position avoids doing quadratic work if the
  1608. chunk length line arrives over many calls to C{dataReceived}.
  1609. @ivar _trailerHeaders: Accumulates raw/unparsed trailer headers.
  1610. See https://github.com/twisted/twisted/issues/12014
  1611. @ivar _maxTrailerHeadersSize: Maximum bytes for trailer header from the
  1612. response.
  1613. @type _maxTrailerHeadersSize: C{int}
  1614. @ivar _receivedTrailerHeadersSize: Bytes received so far for the tailer headers.
  1615. @type _receivedTrailerHeadersSize: C{int}
  1616. """
  1617. state = "CHUNK_LENGTH"
  1618. def __init__(
  1619. self,
  1620. dataCallback: Callable[[bytes], None],
  1621. finishCallback: Callable[[bytes], None],
  1622. ) -> None:
  1623. self.dataCallback = dataCallback
  1624. self.finishCallback = finishCallback
  1625. self._buffer = bytearray()
  1626. self._start = 0
  1627. self._trailerHeaders: List[bytearray] = []
  1628. self._maxTrailerHeadersSize = 2**16
  1629. self._receivedTrailerHeadersSize = 0
  1630. def _dataReceived_CHUNK_LENGTH(self) -> bool:
  1631. """
  1632. Read the chunk size line, ignoring any extensions.
  1633. @returns: C{True} once the line has been read and removed from
  1634. C{self._buffer}. C{False} when more data is required.
  1635. @raises _MalformedChunkedDataError: when the chunk size cannot be
  1636. decoded or the length of the line exceeds L{maxChunkSizeLineLength}.
  1637. """
  1638. eolIndex = self._buffer.find(b"\r\n", self._start)
  1639. if eolIndex >= maxChunkSizeLineLength or (
  1640. eolIndex == -1 and len(self._buffer) > maxChunkSizeLineLength
  1641. ):
  1642. raise _MalformedChunkedDataError(
  1643. "Chunk size line exceeds maximum of {} bytes.".format(
  1644. maxChunkSizeLineLength
  1645. )
  1646. )
  1647. if eolIndex == -1:
  1648. # Restart the search upon receipt of more data at the start of the
  1649. # new data, minus one in case the last character of the buffer is
  1650. # CR.
  1651. self._start = len(self._buffer) - 1
  1652. return False
  1653. endOfLengthIndex = self._buffer.find(b";", 0, eolIndex)
  1654. if endOfLengthIndex == -1:
  1655. endOfLengthIndex = eolIndex
  1656. rawLength = self._buffer[0:endOfLengthIndex]
  1657. try:
  1658. length = _hexint(rawLength)
  1659. except ValueError:
  1660. raise _MalformedChunkedDataError("Chunk-size must be an integer.")
  1661. ext = self._buffer[endOfLengthIndex + 1 : eolIndex]
  1662. if ext and ext.translate(None, _chunkExtChars) != b"":
  1663. raise _MalformedChunkedDataError(
  1664. f"Invalid characters in chunk extensions: {ext!r}."
  1665. )
  1666. if length == 0:
  1667. self.state = "TRAILER"
  1668. else:
  1669. self.state = "BODY"
  1670. self.length = length
  1671. del self._buffer[0 : eolIndex + 2]
  1672. self._start = 0
  1673. return True
  1674. def _dataReceived_CRLF(self) -> bool:
  1675. """
  1676. Await the carriage return and line feed characters that are the end of
  1677. chunk marker that follow the chunk data.
  1678. @returns: C{True} when the CRLF have been read, otherwise C{False}.
  1679. @raises _MalformedChunkedDataError: when anything other than CRLF are
  1680. received.
  1681. """
  1682. if len(self._buffer) < 2:
  1683. return False
  1684. if not self._buffer.startswith(b"\r\n"):
  1685. raise _MalformedChunkedDataError("Chunk did not end with CRLF")
  1686. self.state = "CHUNK_LENGTH"
  1687. del self._buffer[0:2]
  1688. return True
  1689. def _dataReceived_TRAILER(self) -> bool:
  1690. """
  1691. Collect trailer headers if received and finish at the terminal zero-length
  1692. chunk. Then invoke C{finishCallback} and switch to state C{'FINISHED'}.
  1693. @returns: C{False}, as there is either insufficient data to continue,
  1694. or no data remains.
  1695. """
  1696. eolIndex = self._buffer.find(b"\r\n", self._start)
  1697. if eolIndex == -1:
  1698. # Still no end of network line marker found.
  1699. #
  1700. # Check if we've run up against the trailer size limit: if the next
  1701. # read contains the terminating CRLF then we'll have this many bytes
  1702. # of trailers (including the CRLFs).
  1703. minTrailerSize = (
  1704. self._receivedTrailerHeadersSize
  1705. + len(self._buffer)
  1706. + (1 if self._buffer.endswith(b"\r") else 2)
  1707. )
  1708. if minTrailerSize > self._maxTrailerHeadersSize:
  1709. raise _MalformedChunkedDataError("Trailer headers data is too long.")
  1710. # Continue processing more data.
  1711. return False
  1712. if eolIndex > 0:
  1713. # A trailer header was detected.
  1714. self._trailerHeaders.append(self._buffer[0:eolIndex])
  1715. del self._buffer[0 : eolIndex + 2]
  1716. self._start = 0
  1717. self._receivedTrailerHeadersSize += eolIndex + 2
  1718. if self._receivedTrailerHeadersSize > self._maxTrailerHeadersSize:
  1719. raise _MalformedChunkedDataError("Trailer headers data is too long.")
  1720. return True
  1721. # eolIndex in this part of code is equal to 0
  1722. data = memoryview(self._buffer)[2:].tobytes()
  1723. del self._buffer[:]
  1724. self.state = "FINISHED"
  1725. self.finishCallback(data)
  1726. return False
  1727. def _dataReceived_BODY(self) -> bool:
  1728. """
  1729. Deliver any available chunk data to the C{dataCallback}. When all the
  1730. remaining data for the chunk arrives, switch to state C{'CRLF'}.
  1731. @returns: C{True} to continue processing of any buffered data.
  1732. """
  1733. if len(self._buffer) >= self.length:
  1734. chunk = memoryview(self._buffer)[: self.length].tobytes()
  1735. del self._buffer[: self.length]
  1736. self.state = "CRLF"
  1737. self.dataCallback(chunk)
  1738. else:
  1739. chunk = bytes(self._buffer)
  1740. self.length -= len(chunk)
  1741. del self._buffer[:]
  1742. self.dataCallback(chunk)
  1743. return True
  1744. def _dataReceived_FINISHED(self) -> bool:
  1745. """
  1746. Once C{finishCallback} has been invoked receipt of additional data
  1747. raises L{RuntimeError} because it represents a programming error in
  1748. the caller.
  1749. """
  1750. raise RuntimeError(
  1751. "_ChunkedTransferDecoder.dataReceived called after last "
  1752. "chunk was processed"
  1753. )
  1754. def dataReceived(self, data: bytes) -> None:
  1755. """
  1756. Interpret data from a request or response body which uses the
  1757. I{chunked} Transfer-Encoding.
  1758. """
  1759. self._buffer += data
  1760. goOn = True
  1761. while goOn and self._buffer:
  1762. goOn = getattr(self, "_dataReceived_" + self.state)()
  1763. def noMoreData(self) -> None:
  1764. """
  1765. Verify that all data has been received. If it has not been, raise
  1766. L{_DataLoss}.
  1767. """
  1768. if self.state != "FINISHED":
  1769. raise _DataLoss(
  1770. "Chunked decoder in %r state, still expecting more data to "
  1771. "get to 'FINISHED' state." % (self.state,)
  1772. )
  1773. @implementer(interfaces.IPushProducer)
  1774. class _NoPushProducer:
  1775. """
  1776. A no-op version of L{interfaces.IPushProducer}, used to abstract over the
  1777. possibility that a L{HTTPChannel} transport does not provide
  1778. L{IPushProducer}.
  1779. """
  1780. def pauseProducing(self):
  1781. """
  1782. Pause producing data.
  1783. Tells a producer that it has produced too much data to process for
  1784. the time being, and to stop until resumeProducing() is called.
  1785. """
  1786. def resumeProducing(self):
  1787. """
  1788. Resume producing data.
  1789. This tells a producer to re-add itself to the main loop and produce
  1790. more data for its consumer.
  1791. """
  1792. def registerProducer(self, producer, streaming):
  1793. """
  1794. Register to receive data from a producer.
  1795. @param producer: The producer to register.
  1796. @param streaming: Whether this is a streaming producer or not.
  1797. """
  1798. def unregisterProducer(self):
  1799. """
  1800. Stop consuming data from a producer, without disconnecting.
  1801. """
  1802. def stopProducing(self):
  1803. """
  1804. IProducer.stopProducing
  1805. """
  1806. @implementer(interfaces.ITransport, interfaces.IPushProducer, interfaces.IConsumer)
  1807. class HTTPChannel(basic.LineReceiver, policies.TimeoutMixin):
  1808. """
  1809. A receiver for HTTP requests.
  1810. The L{HTTPChannel} provides L{interfaces.ITransport} and
  1811. L{interfaces.IConsumer} to the L{Request} objects it creates. It also
  1812. implements L{interfaces.IPushProducer} to C{self.transport}, allowing the
  1813. transport to pause it.
  1814. @ivar MAX_LENGTH: Maximum length for initial request line and each line
  1815. from the header.
  1816. @ivar _transferDecoder: L{None} or a decoder instance if the request body
  1817. uses the I{chunked} Transfer-Encoding.
  1818. @type _transferDecoder: L{_ChunkedTransferDecoder}
  1819. @ivar maxHeaders: Maximum number of headers allowed per request.
  1820. @type maxHeaders: C{int}
  1821. @ivar totalHeadersSize: Maximum bytes for request line plus all headers
  1822. from the request.
  1823. @type totalHeadersSize: C{int}
  1824. @ivar _receivedHeaderSize: Bytes received so far for the header.
  1825. @type _receivedHeaderSize: C{int}
  1826. @ivar _handlingRequest: Whether a request is currently being processed.
  1827. @type _handlingRequest: L{bool}
  1828. @ivar _dataBuffer: Any data that has been received from the connection
  1829. while processing an outstanding request.
  1830. @type _dataBuffer: L{list} of L{bytes}
  1831. @ivar _networkProducer: Either the transport, if it provides
  1832. L{interfaces.IPushProducer}, or a null implementation of
  1833. L{interfaces.IPushProducer}. Used to attempt to prevent the transport
  1834. from producing excess data when we're responding to a request.
  1835. @type _networkProducer: L{interfaces.IPushProducer}
  1836. @ivar _requestProducer: If the L{Request} object or anything it calls
  1837. registers itself as an L{interfaces.IProducer}, it will be stored here.
  1838. This is used to create a producing pipeline: pause/resume producing
  1839. methods will be propagated from the C{transport}, through the
  1840. L{HTTPChannel} instance, to the c{_requestProducer}.
  1841. The reason we proxy through the producing methods rather than the old
  1842. behaviour (where we literally just set the L{Request} object as the
  1843. producer on the transport) is because we want to be able to exert
  1844. backpressure on the client to prevent it from sending in arbitrarily
  1845. many requests without ever reading responses. Essentially, if the
  1846. client never reads our responses we will eventually stop reading its
  1847. requests.
  1848. @type _requestProducer: L{interfaces.IPushProducer}
  1849. @ivar _requestProducerStreaming: A boolean that tracks whether the producer
  1850. on the L{Request} side of this channel has registered itself as a
  1851. L{interfaces.IPushProducer} or an L{interfaces.IPullProducer}.
  1852. @type _requestProducerStreaming: L{bool} or L{None}
  1853. @ivar _waitingForTransport: A boolean that tracks whether the transport has
  1854. asked us to stop producing. This is used to keep track of what we're
  1855. waiting for: if the transport has asked us to stop producing then we
  1856. don't want to unpause the transport until it asks us to produce again.
  1857. @type _waitingForTransport: L{bool}
  1858. @ivar abortTimeout: The number of seconds to wait after we attempt to shut
  1859. the transport down cleanly to give up and forcibly terminate it. This
  1860. is only used when we time a connection out, to prevent errors causing
  1861. the FD to get leaked. If this is L{None}, we will wait forever.
  1862. @type abortTimeout: L{int}
  1863. @ivar _abortingCall: The L{twisted.internet.base.DelayedCall} that will be
  1864. used to forcibly close the transport if it doesn't close cleanly.
  1865. @type _abortingCall: L{twisted.internet.base.DelayedCall}
  1866. @ivar _optimisticEagerReadSize: When a resource takes a long time to answer
  1867. a request (via L{twisted.web.server.NOT_DONE_YET}, hopefully one day by
  1868. a L{Deferred}), we would like to be able to let that resource know
  1869. about the underlying transport disappearing as promptly as possible,
  1870. via L{Request.notifyFinish}, and therefore via
  1871. C{self.requests[...].connectionLost()} on this L{HTTPChannel}.
  1872. However, in order to simplify application logic, we implement
  1873. head-of-line blocking, and do not relay pipelined requests to the
  1874. application until the previous request has been answered. This means
  1875. that said application cannot dispose of any entity-body that comes in
  1876. from those subsequent requests, which may be arbitrarily large, and it
  1877. may need to be buffered in memory.
  1878. To implement this tradeoff between prompt notification when possible
  1879. (in the most frequent case of non-pipelined requests) and correct
  1880. behavior when not (say, if a client sends a very long-running GET
  1881. request followed by a PUT request with a very large body) we will
  1882. continue reading pipelined requests into C{self._dataBuffer} up to a
  1883. given limit.
  1884. C{_optimisticEagerReadSize} is the number of bytes we will accept from
  1885. the client and buffer before pausing the transport.
  1886. This behavior has been in place since Twisted 17.9.0 .
  1887. @type _optimisticEagerReadSize: L{int}
  1888. """
  1889. maxHeaders = 500
  1890. totalHeadersSize = 16384
  1891. abortTimeout = 15
  1892. length: Optional[int] = 0
  1893. persistent = 1
  1894. __header = b""
  1895. __first_line = 1
  1896. __content = None
  1897. # set in instances or subclasses
  1898. requestFactory = Request
  1899. _savedTimeOut = None
  1900. _receivedHeaderCount = 0
  1901. _receivedHeaderSize = 0
  1902. _requestProducer = None
  1903. _requestProducerStreaming = None
  1904. _waitingForTransport = False
  1905. _abortingCall = None
  1906. _optimisticEagerReadSize = 0x4000
  1907. _log = Logger()
  1908. def __init__(self):
  1909. # the request queue
  1910. self.requests = []
  1911. self._handlingRequest = False
  1912. self._dataBuffer = []
  1913. self._transferDecoder = None
  1914. def connectionMade(self):
  1915. if ITCPTransport.providedBy(self.transport):
  1916. self.transport.setTcpNoDelay(True)
  1917. self.setTimeout(self.timeOut)
  1918. self._networkProducer = interfaces.IPushProducer(
  1919. self.transport, _NoPushProducer()
  1920. )
  1921. self._networkProducer.registerProducer(self, True)
  1922. def dataReceived(self, data):
  1923. self.resetTimeout()
  1924. basic.LineReceiver.dataReceived(self, data)
  1925. def lineReceived(self, line):
  1926. """
  1927. Called for each line from request until the end of headers when
  1928. it enters binary mode.
  1929. """
  1930. self._receivedHeaderSize += len(line)
  1931. if self._receivedHeaderSize > self.totalHeadersSize:
  1932. self._respondToBadRequestAndDisconnect()
  1933. return
  1934. if self.__first_line:
  1935. # if this connection is not persistent, drop any data which
  1936. # the client (illegally) sent after the last request.
  1937. if not self.persistent:
  1938. self.dataReceived = self.lineReceived = lambda *args: None
  1939. return
  1940. # IE sends an extraneous empty line (\r\n) after a POST request;
  1941. # eat up such a line, but only ONCE
  1942. if not line and self.__first_line == 1:
  1943. self.__first_line = 2
  1944. return
  1945. # create a new Request object
  1946. if INonQueuedRequestFactory.providedBy(self.requestFactory):
  1947. request = self.requestFactory(self)
  1948. else:
  1949. request = self.requestFactory(self, len(self.requests))
  1950. self.requests.append(request)
  1951. self.__first_line = 0
  1952. try:
  1953. command, request, version = _parseRequestLine(line)
  1954. except ValueError:
  1955. self._respondToBadRequestAndDisconnect()
  1956. return
  1957. self._command = command
  1958. self._path = request
  1959. self._version = version
  1960. elif line == b"":
  1961. # End of headers.
  1962. if self.__header:
  1963. ok = self.headerReceived(self.__header)
  1964. # If the last header we got is invalid, we MUST NOT proceed
  1965. # with processing. We'll have sent a 400 anyway, so just stop.
  1966. if not ok:
  1967. return
  1968. self.__header = b""
  1969. self.allHeadersReceived()
  1970. if self.length == 0:
  1971. self.allContentReceived()
  1972. else:
  1973. self.setRawMode()
  1974. elif line[0] in b" \t":
  1975. # Continuation of a multi line header.
  1976. self.__header += b" " + line.lstrip(b" \t")
  1977. # Regular header line.
  1978. # Processing of header line is delayed to allow accumulating multi
  1979. # line headers.
  1980. else:
  1981. if self.__header:
  1982. self.headerReceived(self.__header)
  1983. self.__header = line
  1984. def _finishRequestBody(self, data):
  1985. self._dataBuffer.append(data)
  1986. self.allContentReceived()
  1987. def _failChooseTransferDecoder(self) -> bool:
  1988. """
  1989. Utility to indicate failure to choose a decoder.
  1990. """
  1991. self._respondToBadRequestAndDisconnect()
  1992. self.length = None
  1993. return False
  1994. def _maybeChooseTransferDecoder(self, header, data):
  1995. """
  1996. If the provided header is C{content-length} or
  1997. C{transfer-encoding}, choose the appropriate decoder if any.
  1998. Returns L{True} if the request can proceed and L{False} if not.
  1999. """
  2000. # Can this header determine the length?
  2001. if header == b"Content-Length":
  2002. if not data.isdigit():
  2003. return self._failChooseTransferDecoder()
  2004. length = int(data)
  2005. newTransferDecoder = _IdentityTransferDecoder(
  2006. length, self.requests[-1].handleContentChunk, self._finishRequestBody
  2007. )
  2008. elif header == b"Transfer-Encoding":
  2009. # XXX Rather poorly tested code block, apparently only exercised by
  2010. # test_chunkedEncoding
  2011. if data.lower() == b"chunked":
  2012. length = None
  2013. newTransferDecoder = _ChunkedTransferDecoder(
  2014. self.requests[-1].handleContentChunk, self._finishRequestBody
  2015. )
  2016. elif data.lower() == b"identity":
  2017. return True
  2018. else:
  2019. return self._failChooseTransferDecoder()
  2020. else:
  2021. # It's not a length related header, so exit
  2022. return True
  2023. if self._transferDecoder is not None:
  2024. return self._failChooseTransferDecoder()
  2025. else:
  2026. self.length = length
  2027. self._transferDecoder = newTransferDecoder
  2028. return True
  2029. def headerReceived(self, line):
  2030. """
  2031. Do pre-processing (for Content-Length) and store this header away.
  2032. Enforce the per-request header limit.
  2033. @type line: C{bytes}
  2034. @param line: A line from the header section of a request, excluding the
  2035. line delimiter.
  2036. @return: A flag indicating whether the header was valid.
  2037. @rtype: L{bool}
  2038. """
  2039. try:
  2040. header, data = line.split(b":", 1)
  2041. except ValueError:
  2042. self._respondToBadRequestAndDisconnect()
  2043. return False
  2044. # Canonicalize the header name.
  2045. try:
  2046. header = _nameEncoder.encode(header)
  2047. except InvalidHeaderName:
  2048. self._respondToBadRequestAndDisconnect()
  2049. return False
  2050. data = data.strip(b" \t")
  2051. if b"\x00" in data:
  2052. self._respondToBadRequestAndDisconnect()
  2053. return False
  2054. if not self._maybeChooseTransferDecoder(header, data):
  2055. return False
  2056. self.requests[-1].requestHeaders.addRawHeader(header, data)
  2057. self._receivedHeaderCount += 1
  2058. if self._receivedHeaderCount > self.maxHeaders:
  2059. self._respondToBadRequestAndDisconnect()
  2060. return False
  2061. return True
  2062. def allContentReceived(self):
  2063. command = self._command
  2064. path = self._path
  2065. version = self._version
  2066. # reset ALL state variables, so we don't interfere with next request
  2067. self.length = 0
  2068. self._receivedHeaderCount = 0
  2069. self._receivedHeaderSize = 0
  2070. self.__first_line = 1
  2071. self._transferDecoder = None
  2072. del self._command, self._path, self._version
  2073. # Disable the idle timeout, in case this request takes a long
  2074. # time to finish generating output.
  2075. if self.timeOut:
  2076. self._savedTimeOut = self.setTimeout(None)
  2077. self._handlingRequest = True
  2078. # We go into raw mode here even though we will be receiving lines next
  2079. # in the protocol; however, this data will be buffered and then passed
  2080. # back to line mode in the setLineMode call in requestDone.
  2081. self.setRawMode()
  2082. req = self.requests[-1]
  2083. req.requestReceived(command, path, version)
  2084. def rawDataReceived(self, data: bytes) -> None:
  2085. """
  2086. This is called when this HTTP/1.1 parser is in raw mode rather than
  2087. line mode.
  2088. It may be in raw mode for one of two reasons:
  2089. 1. All the headers of a request have been received and this
  2090. L{HTTPChannel} is currently receiving its body.
  2091. 2. The full content of a request has been received and is currently
  2092. being processed asynchronously, and this L{HTTPChannel} is
  2093. buffering the data of all subsequent requests to be parsed
  2094. later.
  2095. In the second state, the data will be played back later.
  2096. @note: This isn't really a public API, and should be invoked only by
  2097. L{LineReceiver}'s line parsing logic. If you wish to drive an
  2098. L{HTTPChannel} from a custom data source, call C{dataReceived} on
  2099. it directly.
  2100. @see: L{LineReceive.rawDataReceived}
  2101. """
  2102. if self._handlingRequest:
  2103. self._dataBuffer.append(data)
  2104. if (
  2105. sum(map(len, self._dataBuffer)) > self._optimisticEagerReadSize
  2106. ) and not self._waitingForTransport:
  2107. # If we received more data than a small limit while processing
  2108. # the head-of-line request, apply TCP backpressure to our peer
  2109. # to get them to stop sending more request data until we're
  2110. # ready. See docstring for _optimisticEagerReadSize above.
  2111. self._networkProducer.pauseProducing()
  2112. return
  2113. try:
  2114. self._transferDecoder.dataReceived(data)
  2115. except _MalformedChunkedDataError:
  2116. self._respondToBadRequestAndDisconnect()
  2117. def allHeadersReceived(self):
  2118. req = self.requests[-1]
  2119. req.parseCookies()
  2120. self.persistent = self.checkPersistence(req, self._version)
  2121. req.gotLength(self.length)
  2122. # Handle 'Expect: 100-continue' with automated 100 response code,
  2123. # a simplistic implementation of RFC 2686 8.2.3:
  2124. expectContinue = req.requestHeaders.getRawHeaders(b"Expect")
  2125. if (
  2126. expectContinue
  2127. and expectContinue[0].lower() == b"100-continue"
  2128. and self._version == b"HTTP/1.1"
  2129. ):
  2130. self._send100Continue()
  2131. def checkPersistence(self, request, version):
  2132. """
  2133. Check if the channel should close or not.
  2134. @param request: The request most recently received over this channel
  2135. against which checks will be made to determine if this connection
  2136. can remain open after a matching response is returned.
  2137. @type version: C{bytes}
  2138. @param version: The version of the request.
  2139. @rtype: C{bool}
  2140. @return: A flag which, if C{True}, indicates that this connection may
  2141. remain open to receive another request; if C{False}, the connection
  2142. must be closed in order to indicate the completion of the response
  2143. to C{request}.
  2144. """
  2145. connection = request.requestHeaders.getRawHeaders(b"Connection")
  2146. if connection:
  2147. tokens = [t.lower() for t in connection[0].split(b" ")]
  2148. else:
  2149. tokens = []
  2150. # Once any HTTP 0.9 or HTTP 1.0 request is received, the connection is
  2151. # no longer allowed to be persistent. At this point in processing the
  2152. # request, we don't yet know if it will be possible to set a
  2153. # Content-Length in the response. If it is not, then the connection
  2154. # will have to be closed to end an HTTP 0.9 or HTTP 1.0 response.
  2155. # If the checkPersistence call happened later, after the Content-Length
  2156. # has been determined (or determined not to be set), it would probably
  2157. # be possible to have persistent connections with HTTP 0.9 and HTTP 1.0.
  2158. # This may not be worth the effort, though. Just use HTTP 1.1, okay?
  2159. if version == b"HTTP/1.1":
  2160. if b"close" in tokens:
  2161. request.responseHeaders.setRawHeaders(b"Connection", [b"close"])
  2162. return False
  2163. else:
  2164. return True
  2165. else:
  2166. return False
  2167. def requestDone(self, request):
  2168. """
  2169. Called by first request in queue when it is done.
  2170. """
  2171. if request != self.requests[0]:
  2172. raise TypeError
  2173. del self.requests[0]
  2174. # We should only resume the producer if we're not waiting for the
  2175. # transport.
  2176. if not self._waitingForTransport:
  2177. self._networkProducer.resumeProducing()
  2178. if self.persistent:
  2179. self._handlingRequest = False
  2180. if self._savedTimeOut:
  2181. self.setTimeout(self._savedTimeOut)
  2182. # Receive our buffered data, if any.
  2183. data = b"".join(self._dataBuffer)
  2184. self._dataBuffer = []
  2185. self.setLineMode(data)
  2186. else:
  2187. self.loseConnection()
  2188. def timeoutConnection(self):
  2189. self._log.info("Timing out client: {peer}", peer=str(self.transport.getPeer()))
  2190. if self.abortTimeout is not None:
  2191. # We use self.callLater because that's what TimeoutMixin does.
  2192. self._abortingCall = self.callLater(
  2193. self.abortTimeout, self.forceAbortClient
  2194. )
  2195. self.loseConnection()
  2196. def forceAbortClient(self):
  2197. """
  2198. Called if C{abortTimeout} seconds have passed since the timeout fired,
  2199. and the connection still hasn't gone away. This can really only happen
  2200. on extremely bad connections or when clients are maliciously attempting
  2201. to keep connections open.
  2202. """
  2203. self._log.info(
  2204. "Forcibly timing out client: {peer}", peer=str(self.transport.getPeer())
  2205. )
  2206. # We want to lose track of the _abortingCall so that no-one tries to
  2207. # cancel it.
  2208. self._abortingCall = None
  2209. self.transport.abortConnection()
  2210. def connectionLost(self, reason):
  2211. self.setTimeout(None)
  2212. for request in self.requests:
  2213. request.connectionLost(reason)
  2214. # If we were going to force-close the transport, we don't have to now.
  2215. if self._abortingCall is not None:
  2216. self._abortingCall.cancel()
  2217. self._abortingCall = None
  2218. def isSecure(self):
  2219. """
  2220. Return L{True} if this channel is using a secure transport.
  2221. Normally this method returns L{True} if this instance is using a
  2222. transport that implements L{interfaces.ISSLTransport}.
  2223. @returns: L{True} if this request is secure
  2224. @rtype: C{bool}
  2225. """
  2226. if interfaces.ISSLTransport(self.transport, None) is not None:
  2227. return True
  2228. return False
  2229. def writeHeaders(self, version, code, reason, headers):
  2230. """Called by L{Request} objects to write a complete set of HTTP headers to
  2231. a transport.
  2232. @param version: The HTTP version in use.
  2233. @type version: L{bytes}
  2234. @param code: The HTTP status code to write.
  2235. @type code: L{bytes}
  2236. @param reason: The HTTP reason phrase to write.
  2237. @type reason: L{bytes}
  2238. @param headers: The headers to write to the transport.
  2239. @type headers: L{twisted.web.http_headers.Headers}, or (for backwards
  2240. compatibility purposes only) any iterable of two-tuples of
  2241. L{bytes}, representing header names and header values. The latter
  2242. option is not actually used by Twisted.
  2243. """
  2244. if not isinstance(headers, Headers):
  2245. # Turn into Headers instance for security reasons, to make sure we
  2246. # quite and sanitize everything. This variant should be removed
  2247. # eventually, it's only here for backwards compatibility.
  2248. sanitizedHeaders = Headers()
  2249. for name, value in headers:
  2250. sanitizedHeaders.addRawHeader(name, value)
  2251. headers = sanitizedHeaders
  2252. headerSequence = [version, b" ", code, b" ", reason, b"\r\n"]
  2253. for name, values in headers.getAllRawHeaders():
  2254. for value in values:
  2255. headerSequence.extend((name, b": ", value, b"\r\n"))
  2256. headerSequence.append(b"\r\n")
  2257. self.transport.writeSequence(headerSequence)
  2258. def write(self, data):
  2259. """
  2260. Called by L{Request} objects to write response data.
  2261. @param data: The data chunk to write to the stream.
  2262. @type data: L{bytes}
  2263. @return: L{None}
  2264. """
  2265. self.transport.write(data)
  2266. def writeSequence(self, iovec):
  2267. """
  2268. Write a list of strings to the HTTP response.
  2269. @param iovec: A list of byte strings to write to the stream.
  2270. @type iovec: L{list} of L{bytes}
  2271. @return: L{None}
  2272. """
  2273. self.transport.writeSequence(iovec)
  2274. def getPeer(self):
  2275. """
  2276. Get the remote address of this connection.
  2277. @return: An L{IAddress} provider.
  2278. """
  2279. return self.transport.getPeer()
  2280. def getHost(self):
  2281. """
  2282. Get the local address of this connection.
  2283. @return: An L{IAddress} provider.
  2284. """
  2285. return self.transport.getHost()
  2286. def loseConnection(self):
  2287. """
  2288. Closes the connection. Will write any data that is pending to be sent
  2289. on the network, but if this response has not yet been written to the
  2290. network will not write anything.
  2291. @return: L{None}
  2292. """
  2293. self._networkProducer.unregisterProducer()
  2294. return self.transport.loseConnection()
  2295. def registerProducer(self, producer, streaming):
  2296. """
  2297. Register to receive data from a producer.
  2298. This sets self to be a consumer for a producer. When this object runs
  2299. out of data (as when a send(2) call on a socket succeeds in moving the
  2300. last data from a userspace buffer into a kernelspace buffer), it will
  2301. ask the producer to resumeProducing().
  2302. For L{IPullProducer} providers, C{resumeProducing} will be called once
  2303. each time data is required.
  2304. For L{IPushProducer} providers, C{pauseProducing} will be called
  2305. whenever the write buffer fills up and C{resumeProducing} will only be
  2306. called when it empties.
  2307. @type producer: L{IProducer} provider
  2308. @param producer: The L{IProducer} that will be producing data.
  2309. @type streaming: L{bool}
  2310. @param streaming: C{True} if C{producer} provides L{IPushProducer},
  2311. C{False} if C{producer} provides L{IPullProducer}.
  2312. @raise RuntimeError: If a producer is already registered.
  2313. @return: L{None}
  2314. """
  2315. if self._requestProducer is not None:
  2316. raise RuntimeError(
  2317. "Cannot register producer %s, because producer %s was never "
  2318. "unregistered." % (producer, self._requestProducer)
  2319. )
  2320. if not streaming:
  2321. producer = _PullToPush(producer, self)
  2322. self._requestProducer = producer
  2323. self._requestProducerStreaming = streaming
  2324. if not streaming:
  2325. producer.startStreaming()
  2326. def unregisterProducer(self):
  2327. """
  2328. Stop consuming data from a producer, without disconnecting.
  2329. @return: L{None}
  2330. """
  2331. if self._requestProducer is None:
  2332. return
  2333. if not self._requestProducerStreaming:
  2334. self._requestProducer.stopStreaming()
  2335. self._requestProducer = None
  2336. self._requestProducerStreaming = None
  2337. def stopProducing(self):
  2338. """
  2339. Stop producing data.
  2340. The HTTPChannel doesn't *actually* implement this, beacuse the
  2341. assumption is that it will only be called just before C{loseConnection}
  2342. is called. There's nothing sensible we can do other than call
  2343. C{loseConnection} anyway.
  2344. """
  2345. if self._requestProducer is not None:
  2346. self._requestProducer.stopProducing()
  2347. def pauseProducing(self):
  2348. """
  2349. Pause producing data.
  2350. This will be called by the transport when the send buffers have been
  2351. filled up. We want to simultaneously pause the producing L{Request}
  2352. object and also pause our transport.
  2353. The logic behind pausing the transport is specifically to avoid issues
  2354. like https://twistedmatrix.com/trac/ticket/8868. In this case, our
  2355. inability to send does not prevent us handling more requests, which
  2356. means we increasingly queue up more responses in our send buffer
  2357. without end. The easiest way to handle this is to ensure that if we are
  2358. unable to send our responses, we will not read further data from the
  2359. connection until the client pulls some data out. This is a bit of a
  2360. blunt instrument, but it's ok.
  2361. Note that this potentially interacts with timeout handling in a
  2362. positive way. Once the transport is paused the client may run into a
  2363. timeout which will cause us to tear the connection down. That's a good
  2364. thing!
  2365. """
  2366. self._waitingForTransport = True
  2367. # The first step is to tell any producer we might currently have
  2368. # registered to stop producing. If we can slow our applications down
  2369. # we should.
  2370. if self._requestProducer is not None:
  2371. self._requestProducer.pauseProducing()
  2372. # The next step here is to pause our own transport, as discussed in the
  2373. # docstring.
  2374. if not self._handlingRequest:
  2375. self._networkProducer.pauseProducing()
  2376. def resumeProducing(self):
  2377. """
  2378. Resume producing data.
  2379. This will be called by the transport when the send buffer has dropped
  2380. enough to actually send more data. When this happens we can unpause any
  2381. outstanding L{Request} producers we have, and also unpause our
  2382. transport.
  2383. """
  2384. self._waitingForTransport = False
  2385. if self._requestProducer is not None:
  2386. self._requestProducer.resumeProducing()
  2387. # We only want to resume the network producer if we're not currently
  2388. # waiting for a response to show up.
  2389. if not self._handlingRequest:
  2390. self._networkProducer.resumeProducing()
  2391. def _send100Continue(self):
  2392. """
  2393. Sends a 100 Continue response, used to signal to clients that further
  2394. processing will be performed.
  2395. """
  2396. self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")
  2397. def _respondToBadRequestAndDisconnect(self):
  2398. """
  2399. This is a quick and dirty way of responding to bad requests.
  2400. As described by HTTP standard we should be patient and accept the
  2401. whole request from the client before sending a polite bad request
  2402. response, even in the case when clients send tons of data.
  2403. """
  2404. self.transport.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
  2405. self.loseConnection()
  2406. def _escape(s):
  2407. """
  2408. Return a string like python repr, but always escaped as if surrounding
  2409. quotes were double quotes.
  2410. @param s: The string to escape.
  2411. @type s: L{bytes} or L{str}
  2412. @return: An escaped string.
  2413. @rtype: L{str}
  2414. """
  2415. if not isinstance(s, bytes):
  2416. s = s.encode("ascii")
  2417. r = repr(s)
  2418. if not isinstance(r, str):
  2419. r = r.decode("ascii")
  2420. if r.startswith("b"):
  2421. r = r[1:]
  2422. if r.startswith("'"):
  2423. return r[1:-1].replace('"', '\\"').replace("\\'", "'")
  2424. return r[1:-1]
  2425. @provider(IAccessLogFormatter)
  2426. def combinedLogFormatter(timestamp, request):
  2427. """
  2428. @return: A combined log formatted log line for the given request.
  2429. @see: L{IAccessLogFormatter}
  2430. """
  2431. clientAddr = request.getClientAddress()
  2432. if isinstance(
  2433. clientAddr, (address.IPv4Address, address.IPv6Address, _XForwardedForAddress)
  2434. ):
  2435. ip = clientAddr.host
  2436. else:
  2437. ip = b"-"
  2438. referrer = _escape(request.getHeader(b"referer") or b"-")
  2439. agent = _escape(request.getHeader(b"user-agent") or b"-")
  2440. line = (
  2441. '"%(ip)s" - - %(timestamp)s "%(method)s %(uri)s %(protocol)s" '
  2442. '%(code)d %(length)s "%(referrer)s" "%(agent)s"'
  2443. % dict(
  2444. ip=_escape(ip),
  2445. timestamp=timestamp,
  2446. method=_escape(request.method),
  2447. uri=_escape(request.uri),
  2448. protocol=_escape(request.clientproto),
  2449. code=request.code,
  2450. length=request.sentLength or "-",
  2451. referrer=referrer,
  2452. agent=agent,
  2453. )
  2454. )
  2455. return line
  2456. @implementer(interfaces.IAddress)
  2457. class _XForwardedForAddress:
  2458. """
  2459. L{IAddress} which represents the client IP to log for a request, as gleaned
  2460. from an X-Forwarded-For header.
  2461. @ivar host: An IP address or C{b"-"}.
  2462. @type host: L{bytes}
  2463. @see: L{proxiedLogFormatter}
  2464. """
  2465. def __init__(self, host):
  2466. self.host = host
  2467. class _XForwardedForRequest(proxyForInterface(IRequest, "_request")): # type: ignore[misc]
  2468. """
  2469. Add a layer on top of another request that only uses the value of an
  2470. X-Forwarded-For header as the result of C{getClientAddress}.
  2471. """
  2472. def getClientAddress(self):
  2473. """
  2474. The client address (the first address) in the value of the
  2475. I{X-Forwarded-For header}. If the header is not present, the IP is
  2476. considered to be C{b"-"}.
  2477. @return: L{_XForwardedForAddress} which wraps the client address as
  2478. expected by L{combinedLogFormatter}.
  2479. """
  2480. host = (
  2481. self._request.requestHeaders.getRawHeaders(b"X-Forwarded-For", [b"-"])[0]
  2482. .split(b",")[0]
  2483. .strip()
  2484. )
  2485. return _XForwardedForAddress(host)
  2486. # These are missing from the interface. Forward them manually.
  2487. @property
  2488. def clientproto(self):
  2489. """
  2490. @return: The protocol version in the request.
  2491. @rtype: L{bytes}
  2492. """
  2493. return self._request.clientproto
  2494. @property
  2495. def code(self):
  2496. """
  2497. @return: The response code for the request.
  2498. @rtype: L{int}
  2499. """
  2500. return self._request.code
  2501. @property
  2502. def sentLength(self):
  2503. """
  2504. @return: The number of bytes sent in the response body.
  2505. @rtype: L{int}
  2506. """
  2507. return self._request.sentLength
  2508. @provider(IAccessLogFormatter)
  2509. def proxiedLogFormatter(timestamp, request):
  2510. """
  2511. @return: A combined log formatted log line for the given request but use
  2512. the value of the I{X-Forwarded-For} header as the value for the client
  2513. IP address.
  2514. @see: L{IAccessLogFormatter}
  2515. """
  2516. return combinedLogFormatter(timestamp, _XForwardedForRequest(request))
  2517. class _GenericHTTPChannelProtocol(proxyForInterface(IProtocol, "_channel")): # type: ignore[misc]
  2518. """
  2519. A proxy object that wraps one of the HTTP protocol objects, and switches
  2520. between them depending on TLS negotiated protocol.
  2521. @ivar _negotiatedProtocol: The protocol negotiated with ALPN or NPN, if
  2522. any.
  2523. @type _negotiatedProtocol: Either a bytestring containing the ALPN token
  2524. for the negotiated protocol, or L{None} if no protocol has yet been
  2525. negotiated.
  2526. @ivar _channel: The object capable of behaving like a L{HTTPChannel} that
  2527. is backing this object. By default this is a L{HTTPChannel}, but if a
  2528. HTTP protocol upgrade takes place this may be a different channel
  2529. object. Must implement L{IProtocol}.
  2530. @type _channel: L{HTTPChannel}
  2531. @ivar _requestFactory: A callable to use to build L{IRequest} objects.
  2532. @type _requestFactory: L{IRequest}
  2533. @ivar _site: A reference to the creating L{twisted.web.server.Site} object.
  2534. @type _site: L{twisted.web.server.Site}
  2535. @ivar _factory: A reference to the creating L{HTTPFactory} object.
  2536. @type _factory: L{HTTPFactory}
  2537. @ivar _timeOut: A timeout value to pass to the backing channel.
  2538. @type _timeOut: L{int} or L{None}
  2539. @ivar _callLater: A value for the C{callLater} callback.
  2540. @type _callLater: L{callable}
  2541. """
  2542. _negotiatedProtocol = None
  2543. _requestFactory = Request
  2544. _factory = None
  2545. _site = None
  2546. _timeOut = None
  2547. _callLater = None
  2548. @property
  2549. def factory(self):
  2550. """
  2551. @see: L{_genericHTTPChannelProtocolFactory}
  2552. """
  2553. return self._channel.factory
  2554. @factory.setter
  2555. def factory(self, value):
  2556. self._factory = value
  2557. self._channel.factory = value
  2558. @property
  2559. def requestFactory(self):
  2560. """
  2561. A callable to use to build L{IRequest} objects.
  2562. Retries the object from the current backing channel.
  2563. """
  2564. return self._channel.requestFactory
  2565. @requestFactory.setter
  2566. def requestFactory(self, value):
  2567. """
  2568. A callable to use to build L{IRequest} objects.
  2569. Sets the object on the backing channel and also stores the value for
  2570. propagation to any new channel.
  2571. @param value: The new callable to use.
  2572. @type value: A L{callable} returning L{IRequest}
  2573. """
  2574. self._requestFactory = value
  2575. self._channel.requestFactory = value
  2576. @property
  2577. def site(self):
  2578. """
  2579. A reference to the creating L{twisted.web.server.Site} object.
  2580. Returns the site object from the backing channel.
  2581. """
  2582. return self._channel.site
  2583. @site.setter
  2584. def site(self, value):
  2585. """
  2586. A reference to the creating L{twisted.web.server.Site} object.
  2587. Sets the object on the backing channel and also stores the value for
  2588. propagation to any new channel.
  2589. @param value: The L{twisted.web.server.Site} object to set.
  2590. @type value: L{twisted.web.server.Site}
  2591. """
  2592. self._site = value
  2593. self._channel.site = value
  2594. @property
  2595. def timeOut(self):
  2596. """
  2597. The idle timeout for the backing channel.
  2598. """
  2599. return self._channel.timeOut
  2600. @timeOut.setter
  2601. def timeOut(self, value):
  2602. """
  2603. The idle timeout for the backing channel.
  2604. Sets the idle timeout on both the backing channel and stores it for
  2605. propagation to any new backing channel.
  2606. @param value: The timeout to set.
  2607. @type value: L{int} or L{float}
  2608. """
  2609. self._timeOut = value
  2610. self._channel.timeOut = value
  2611. @property
  2612. def callLater(self):
  2613. """
  2614. A value for the C{callLater} callback. This callback is used by the
  2615. L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
  2616. """
  2617. return self._channel.callLater
  2618. @callLater.setter
  2619. def callLater(self, value):
  2620. """
  2621. Sets the value for the C{callLater} callback. This callback is used by
  2622. the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
  2623. @param value: The new callback to use.
  2624. @type value: L{callable}
  2625. """
  2626. self._callLater = value
  2627. self._channel.callLater = value
  2628. def dataReceived(self, data):
  2629. """
  2630. An override of L{IProtocol.dataReceived} that checks what protocol we're
  2631. using.
  2632. """
  2633. if self._negotiatedProtocol is None:
  2634. negotiatedProtocol = getattr(
  2635. self._channel.transport, "negotiatedProtocol", b"http/1.1"
  2636. )
  2637. if negotiatedProtocol is None:
  2638. negotiatedProtocol = b"http/1.1"
  2639. if negotiatedProtocol == b"h2":
  2640. if not H2_ENABLED:
  2641. raise ValueError("Negotiated HTTP/2 without support.")
  2642. # We need to make sure that the HTTPChannel is unregistered
  2643. # from the transport so that the H2Connection can register
  2644. # itself if possible.
  2645. networkProducer = self._channel._networkProducer
  2646. networkProducer.unregisterProducer()
  2647. # Cancel the old channel's timeout.
  2648. self._channel.setTimeout(None)
  2649. transport = self._channel.transport
  2650. self._channel = H2Connection()
  2651. self._channel.requestFactory = self._requestFactory
  2652. self._channel.site = self._site
  2653. self._channel.factory = self._factory
  2654. self._channel.timeOut = self._timeOut
  2655. self._channel.callLater = self._callLater
  2656. self._channel.makeConnection(transport)
  2657. # Register the H2Connection as the transport's
  2658. # producer, so that the transport can apply back
  2659. # pressure.
  2660. networkProducer.registerProducer(self._channel, True)
  2661. else:
  2662. # Only HTTP/2 and HTTP/1.1 are supported right now.
  2663. assert (
  2664. negotiatedProtocol == b"http/1.1"
  2665. ), "Unsupported protocol negotiated"
  2666. self._negotiatedProtocol = negotiatedProtocol
  2667. return self._channel.dataReceived(data)
  2668. def _genericHTTPChannelProtocolFactory(self):
  2669. """
  2670. Returns an appropriately initialized _GenericHTTPChannelProtocol.
  2671. """
  2672. return _GenericHTTPChannelProtocol(HTTPChannel())
  2673. class _MinimalLogFile(TypingProtocol):
  2674. def write(self, data: str, /) -> object:
  2675. """
  2676. Write some data.
  2677. """
  2678. def close(self) -> None:
  2679. """
  2680. Close the file.
  2681. """
  2682. value: type[_MinimalLogFile] = TextIOWrapper
  2683. class HTTPFactory(protocol.ServerFactory):
  2684. """
  2685. Factory for HTTP server.
  2686. @ivar _logDateTime: A cached datetime string for log messages, updated by
  2687. C{_logDateTimeCall}.
  2688. @type _logDateTime: C{str}
  2689. @ivar _logDateTimeCall: A delayed call for the next update to the cached
  2690. log datetime string.
  2691. @type _logDateTimeCall: L{IDelayedCall} provided
  2692. @ivar _logFormatter: See the C{logFormatter} parameter to L{__init__}
  2693. @ivar _nativeize: A flag that indicates whether the log file being written
  2694. to wants native strings (C{True}) or bytes (C{False}). This is only to
  2695. support writing to L{twisted.python.log} which, unfortunately, works
  2696. with native strings.
  2697. @ivar reactor: An L{IReactorTime} provider used to manage connection
  2698. timeouts and compute logging timestamps.
  2699. """
  2700. # We need to ignore the mypy error here, because
  2701. # _genericHTTPChannelProtocolFactory is a callable which returns a proxy
  2702. # to a Protocol, instead of a concrete Protocol object, as expected in
  2703. # the protocol.Factory interface
  2704. protocol = _genericHTTPChannelProtocolFactory # type: ignore[assignment]
  2705. logPath = None
  2706. _logFile: _MinimalLogFile | None = None
  2707. timeOut: int | float | None = _REQUEST_TIMEOUT
  2708. def __init__(
  2709. self,
  2710. logPath: str | bytes | None = None,
  2711. timeout: int | float = _REQUEST_TIMEOUT,
  2712. logFormatter: IAccessLogFormatter | None = None,
  2713. reactor: IReactorTime | None = None,
  2714. ):
  2715. """
  2716. @param logPath: File path to which access log messages will be written
  2717. or C{None} to disable logging.
  2718. @type logPath: L{str} or L{bytes}
  2719. @param timeout: The initial value of L{timeOut}, which defines the idle
  2720. connection timeout in seconds, or C{None} to disable the idle
  2721. timeout.
  2722. @type timeout: L{float}
  2723. @param logFormatter: An object to format requests into log lines for
  2724. the access log. L{combinedLogFormatter} when C{None} is passed.
  2725. @type logFormatter: L{IAccessLogFormatter} provider
  2726. @param reactor: An L{IReactorTime} provider used to manage connection
  2727. timeouts and compute logging timestamps. Defaults to the global
  2728. reactor.
  2729. """
  2730. if reactor is None:
  2731. from twisted.internet import reactor # type:ignore[assignment]
  2732. self.reactor: IReactorTime = reactor # type:ignore[assignment]
  2733. if logPath is not None:
  2734. logPath = os.path.abspath(logPath)
  2735. self.logPath = logPath
  2736. self.timeOut = timeout
  2737. if logFormatter is None:
  2738. logFormatter = combinedLogFormatter
  2739. self._logFormatter = logFormatter
  2740. # For storing the cached log datetime and the callback to update it
  2741. self._logDateTime: str | None = None
  2742. self._logDateTimeCall: IDelayedCall | None = None
  2743. logFile = property()
  2744. """
  2745. A file (object with C{write(data: str)} and C{close()} methods) that will
  2746. be used for logging HTTP requests and responses in the standard U{Combined
  2747. Log Format <https://en.wikipedia.org/wiki/Common_Log_Format>} .
  2748. @note: for backwards compatibility purposes, this may be I{set} to an
  2749. object with a C{write(data: bytes)} method, but these will be detected
  2750. (by checking if it's an instance of L{BufferedIOBase}) and replaced
  2751. with a L{TextIOWrapper} when retrieved by getting the attribute again.
  2752. """
  2753. @logFile.getter
  2754. def _get_logFile(self) -> _MinimalLogFile:
  2755. if self._logFile is None:
  2756. raise AttributeError("no log file present")
  2757. return self._logFile
  2758. @_get_logFile.setter
  2759. def _set_logFile(self, newLogFile: BufferedIOBase | _MinimalLogFile) -> None:
  2760. if isinstance(newLogFile, BufferedIOBase):
  2761. newLogFile = TextIOWrapper(
  2762. newLogFile, # type:ignore[arg-type]
  2763. "utf-8",
  2764. write_through=True,
  2765. newline="\n",
  2766. )
  2767. self._logFile = newLogFile
  2768. logFile = _set_logFile
  2769. def _updateLogDateTime(self) -> None:
  2770. """
  2771. Update log datetime periodically, so we aren't always recalculating it.
  2772. """
  2773. self._logDateTime = datetimeToLogString(self.reactor.seconds())
  2774. self._logDateTimeCall = self.reactor.callLater(1, self._updateLogDateTime)
  2775. def buildProtocol(self, addr: IAddress) -> Protocol | None:
  2776. p = protocol.ServerFactory.buildProtocol(self, addr)
  2777. # This is a bit of a hack to ensure that the HTTPChannel timeouts
  2778. # occur on the same reactor as the one we're using here. This could
  2779. # ideally be resolved by passing the reactor more generally to the
  2780. # HTTPChannel, but that won't work for the TimeoutMixin until we fix
  2781. # https://twistedmatrix.com/trac/ticket/8488
  2782. p.callLater = self.reactor.callLater # type:ignore[union-attr]
  2783. # timeOut needs to be on the Protocol instance cause
  2784. # TimeoutMixin expects it there
  2785. p.timeOut = self.timeOut # type:ignore[union-attr]
  2786. return p
  2787. def startFactory(self) -> None:
  2788. """
  2789. Set up request logging if necessary.
  2790. """
  2791. if self._logDateTimeCall is None:
  2792. self._updateLogDateTime()
  2793. self._logFile = self._openLogFile(self.logPath) if self.logPath else log.logfile
  2794. def stopFactory(self) -> None:
  2795. if self._logFile is not None:
  2796. if self._logFile != log.logfile:
  2797. self._logFile.close()
  2798. self._logFile = None
  2799. if self._logDateTimeCall is not None and self._logDateTimeCall.active():
  2800. self._logDateTimeCall.cancel()
  2801. self._logDateTimeCall = None
  2802. def _openLogFile(self, path: str | bytes) -> _MinimalLogFile:
  2803. """
  2804. Override in subclasses, e.g. to use L{twisted.python.logfile}.
  2805. """
  2806. return open(path, "a", 1, newline="\n")
  2807. def log(self, request: Request) -> None:
  2808. """
  2809. Write a line representing C{request} to the access log file.
  2810. @param request: The request object about which to log.
  2811. """
  2812. logFile = self._logFile
  2813. if logFile is not None:
  2814. line = self._logFormatter(self._logDateTime, request) + "\n"
  2815. logFile.write(line)