http.py 114 KB

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