_newclient.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804
  1. # -*- test-case-name: twisted.web.test.test_newclient -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. An U{HTTP 1.1<http://www.w3.org/Protocols/rfc2616/rfc2616.html>} client.
  6. The way to use the functionality provided by this module is to:
  7. - Connect a L{HTTP11ClientProtocol} to an HTTP server
  8. - Create a L{Request} with the appropriate data
  9. - Pass the request to L{HTTP11ClientProtocol.request}
  10. - The returned Deferred will fire with a L{Response} object
  11. - Create a L{IProtocol} provider which can handle the response body
  12. - Connect it to the response with L{Response.deliverBody}
  13. - When the protocol's C{connectionLost} method is called, the response is
  14. complete. See L{Response.deliverBody} for details.
  15. Various other classes in this module support this usage:
  16. - HTTPParser is the basic HTTP parser. It can handle the parts of HTTP which
  17. are symmetric between requests and responses.
  18. - HTTPClientParser extends HTTPParser to handle response-specific parts of
  19. HTTP. One instance is created for each request to parse the corresponding
  20. response.
  21. """
  22. from __future__ import annotations
  23. import re
  24. from typing import TYPE_CHECKING, Optional
  25. from zope.interface import implementer
  26. from twisted.internet.defer import CancelledError, Deferred, fail, succeed
  27. from twisted.internet.error import ConnectionDone
  28. from twisted.internet.interfaces import IConsumer, IPushProducer
  29. from twisted.internet.protocol import Protocol
  30. from twisted.logger import Logger
  31. from twisted.protocols.basic import LineReceiver
  32. from twisted.python.compat import networkString
  33. from twisted.python.components import proxyForInterface
  34. from twisted.python.failure import Failure
  35. from twisted.web.http import (
  36. NO_CONTENT,
  37. NOT_MODIFIED,
  38. PotentialDataLoss,
  39. _ChunkedTransferDecoder,
  40. _DataLoss,
  41. _IdentityTransferDecoder,
  42. )
  43. from twisted.web.http_headers import Headers
  44. from twisted.web.iweb import UNKNOWN_LENGTH, IClientRequest, IResponse
  45. # States HTTPParser can be in
  46. STATUS = "STATUS"
  47. HEADER = "HEADER"
  48. BODY = "BODY"
  49. DONE = "DONE"
  50. _moduleLog = Logger()
  51. class BadHeaders(Exception):
  52. """
  53. Headers passed to L{Request} were in some way invalid.
  54. """
  55. class ExcessWrite(Exception):
  56. """
  57. The body L{IBodyProducer} for a request tried to write data after
  58. indicating it had finished writing data.
  59. """
  60. class ParseError(Exception):
  61. """
  62. Some received data could not be parsed.
  63. @ivar data: The string which could not be parsed.
  64. """
  65. def __init__(self, reason, data):
  66. Exception.__init__(self, reason, data)
  67. self.data = data
  68. class BadResponseVersion(ParseError):
  69. """
  70. The version string in a status line was unparsable.
  71. """
  72. class _WrapperException(Exception):
  73. """
  74. L{_WrapperException} is the base exception type for exceptions which
  75. include one or more other exceptions as the low-level causes.
  76. @ivar reasons: A L{list} of one or more L{Failure} instances encountered
  77. during an HTTP request. See subclass documentation for more details.
  78. """
  79. def __init__(self, reasons):
  80. Exception.__init__(self, reasons)
  81. self.reasons = reasons
  82. class RequestGenerationFailed(_WrapperException):
  83. """
  84. There was an error while creating the bytes which make up a request.
  85. @ivar reasons: A C{list} of one or more L{Failure} instances giving the
  86. reasons the request generation was considered to have failed.
  87. """
  88. class RequestTransmissionFailed(_WrapperException):
  89. """
  90. There was an error while sending the bytes which make up a request.
  91. @ivar reasons: A C{list} of one or more L{Failure} instances giving the
  92. reasons the request transmission was considered to have failed.
  93. """
  94. class ConnectionAborted(Exception):
  95. """
  96. The connection was explicitly aborted by application code.
  97. """
  98. class WrongBodyLength(Exception):
  99. """
  100. An L{IBodyProducer} declared the number of bytes it was going to
  101. produce (via its C{length} attribute) and then produced a different number
  102. of bytes.
  103. """
  104. class ResponseDone(Exception):
  105. """
  106. L{ResponseDone} may be passed to L{IProtocol.connectionLost} on the
  107. protocol passed to L{Response.deliverBody} and indicates that the entire
  108. response has been delivered.
  109. """
  110. class ResponseFailed(_WrapperException):
  111. """
  112. L{ResponseFailed} indicates that all of the response to a request was not
  113. received for some reason.
  114. @ivar reasons: A C{list} of one or more L{Failure} instances giving the
  115. reasons the response was considered to have failed.
  116. @ivar response: If specified, the L{Response} received from the server (and
  117. in particular the status code and the headers).
  118. """
  119. def __init__(self, reasons, response=None):
  120. _WrapperException.__init__(self, reasons)
  121. self.response = response
  122. class ResponseNeverReceived(ResponseFailed):
  123. """
  124. A L{ResponseFailed} that knows no response bytes at all have been received.
  125. """
  126. class RequestNotSent(Exception):
  127. """
  128. L{RequestNotSent} indicates that an attempt was made to issue a request but
  129. for reasons unrelated to the details of the request itself, the request
  130. could not be sent. For example, this may indicate that an attempt was made
  131. to send a request using a protocol which is no longer connected to a
  132. server.
  133. """
  134. class HTTPParser(LineReceiver):
  135. """
  136. L{HTTPParser} handles the parsing side of HTTP processing. With a suitable
  137. subclass, it can parse either the client side or the server side of the
  138. connection.
  139. @ivar headers: All of the non-connection control message headers yet
  140. received.
  141. @ivar connHeaders: All of the connection control message headers yet
  142. received. See L{CONNECTION_CONTROL_HEADERS} and
  143. L{isConnectionControlHeader}.
  144. @ivar state: State indicator for the response parsing state machine. One
  145. of C{STATUS}, C{HEADER}, C{BODY}, C{DONE}.
  146. @ivar _partialHeader: L{None} or a C{list} of the lines of a multiline
  147. header while that header is being received.
  148. """
  149. # NOTE: According to HTTP spec, we're supposed to eat the
  150. # 'Proxy-Authenticate' and 'Proxy-Authorization' headers also, but that
  151. # doesn't sound like a good idea to me, because it makes it impossible to
  152. # have a non-authenticating transparent proxy in front of an authenticating
  153. # proxy. An authenticating proxy can eat them itself. -jknight
  154. #
  155. # Further, quoting
  156. # http://homepages.tesco.net/J.deBoynePollard/FGA/web-proxy-connection-header.html
  157. # regarding the 'Proxy-Connection' header:
  158. #
  159. # The Proxy-Connection: header is a mistake in how some web browsers
  160. # use HTTP. Its name is the result of a false analogy. It is not a
  161. # standard part of the protocol. There is a different standard
  162. # protocol mechanism for doing what it does. And its existence
  163. # imposes a requirement upon HTTP servers such that no proxy HTTP
  164. # server can be standards-conforming in practice.
  165. #
  166. # -exarkun
  167. # Some servers (like http://news.ycombinator.com/) return status lines and
  168. # HTTP headers delimited by \n instead of \r\n.
  169. delimiter = b"\n"
  170. CONNECTION_CONTROL_HEADERS = {
  171. b"content-length",
  172. b"connection",
  173. b"keep-alive",
  174. b"te",
  175. b"trailers",
  176. b"transfer-encoding",
  177. b"upgrade",
  178. b"proxy-connection",
  179. }
  180. def connectionMade(self):
  181. self.headers = Headers()
  182. self.connHeaders = Headers()
  183. self.state = STATUS
  184. self._partialHeader = None
  185. def switchToBodyMode(self, decoder):
  186. """
  187. Switch to body parsing mode - interpret any more bytes delivered as
  188. part of the message body and deliver them to the given decoder.
  189. """
  190. if self.state == BODY:
  191. raise RuntimeError("already in body mode")
  192. self.bodyDecoder = decoder
  193. self.state = BODY
  194. self.setRawMode()
  195. def lineReceived(self, line):
  196. """
  197. Handle one line from a response.
  198. """
  199. # Handle the normal CR LF case.
  200. if line[-1:] == b"\r":
  201. line = line[:-1]
  202. if self.state == STATUS:
  203. self.statusReceived(line)
  204. self.state = HEADER
  205. elif self.state == HEADER:
  206. if not line or line[0] not in b" \t":
  207. if self._partialHeader is not None:
  208. header = b"".join(self._partialHeader)
  209. name, value = header.split(b":", 1)
  210. value = value.strip()
  211. self.headerReceived(name, value)
  212. if not line:
  213. # Empty line means the header section is over.
  214. self.allHeadersReceived()
  215. else:
  216. # Line not beginning with LWS is another header.
  217. self._partialHeader = [line]
  218. else:
  219. # A line beginning with LWS is a continuation of a header
  220. # begun on a previous line.
  221. self._partialHeader.append(line)
  222. def rawDataReceived(self, data):
  223. """
  224. Pass data from the message body to the body decoder object.
  225. """
  226. self.bodyDecoder.dataReceived(data)
  227. def isConnectionControlHeader(self, name):
  228. """
  229. Return C{True} if the given lower-cased name is the name of a
  230. connection control header (rather than an entity header).
  231. According to RFC 2616, section 14.10, the tokens in the Connection
  232. header are probably relevant here. However, I am not sure what the
  233. practical consequences of either implementing or ignoring that are.
  234. So I leave it unimplemented for the time being.
  235. """
  236. return name in self.CONNECTION_CONTROL_HEADERS
  237. def statusReceived(self, status):
  238. """
  239. Callback invoked whenever the first line of a new message is received.
  240. Override this.
  241. @param status: The first line of an HTTP request or response message
  242. without trailing I{CR LF}.
  243. @type status: C{bytes}
  244. """
  245. def headerReceived(self, name, value):
  246. """
  247. Store the given header in C{self.headers}.
  248. """
  249. name = name.lower()
  250. if self.isConnectionControlHeader(name):
  251. headers = self.connHeaders
  252. else:
  253. headers = self.headers
  254. headers.addRawHeader(name, value)
  255. def allHeadersReceived(self):
  256. """
  257. Callback invoked after the last header is passed to C{headerReceived}.
  258. Override this to change to the C{BODY} or C{DONE} state.
  259. """
  260. self.switchToBodyMode(None)
  261. _ignoreDecoderErrors = _moduleLog.failureHandler("while interacting with body decoder:")
  262. _ignoreStopProducerStopWriting = _moduleLog.failureHandler(
  263. "while calling stopProducing() in stopWriting():"
  264. )
  265. _ignoreStopProducerWrite = _moduleLog.failureHandler(
  266. "while calling stopProducing() in write():"
  267. )
  268. class HTTPClientParser(HTTPParser):
  269. """
  270. An HTTP parser which only handles HTTP responses.
  271. @ivar request: The request with which the expected response is associated.
  272. @type request: L{Request}
  273. @ivar NO_BODY_CODES: A C{set} of response codes which B{MUST NOT} have a
  274. body.
  275. @ivar finisher: A callable to invoke when this response is fully parsed.
  276. @ivar _responseDeferred: A L{Deferred} which will be called back with the
  277. response when all headers in the response have been received.
  278. Thereafter, L{None}.
  279. @ivar _everReceivedData: C{True} if any bytes have been received.
  280. """
  281. NO_BODY_CODES = {NO_CONTENT, NOT_MODIFIED}
  282. _transferDecoders = {
  283. b"chunked": _ChunkedTransferDecoder,
  284. }
  285. bodyDecoder: _IdentityTransferDecoder | None = None
  286. _log = Logger()
  287. def __init__(self, request, finisher):
  288. self.request = request
  289. self.finisher = finisher
  290. self._responseDeferred = Deferred()
  291. self._everReceivedData = False
  292. def dataReceived(self, data):
  293. """
  294. Override so that we know if any response has been received.
  295. """
  296. self._everReceivedData = True
  297. HTTPParser.dataReceived(self, data)
  298. def parseVersion(self, strversion):
  299. """
  300. Parse version strings of the form Protocol '/' Major '.' Minor. E.g.
  301. b'HTTP/1.1'. Returns (protocol, major, minor). Will raise ValueError
  302. on bad syntax.
  303. """
  304. # Vast majority of the time this will be the response, so just
  305. # immediately return the result:
  306. if strversion == b"HTTP/1.1":
  307. return (b"HTTP", 1, 1)
  308. try:
  309. proto, strnumber = strversion.split(b"/")
  310. major, minor = strnumber.split(b".")
  311. major, minor = int(major), int(minor)
  312. except ValueError as e:
  313. raise BadResponseVersion(str(e), strversion)
  314. if major < 0 or minor < 0:
  315. raise BadResponseVersion("version may not be negative", strversion)
  316. return (proto, major, minor)
  317. def statusReceived(self, status):
  318. """
  319. Parse the status line into its components and create a response object
  320. to keep track of this response's state.
  321. """
  322. parts = status.split(b" ", 2)
  323. if len(parts) == 2:
  324. # Some broken servers omit the required `phrase` portion of
  325. # `status-line`. One such server identified as
  326. # "cloudflare-nginx". Others fail to identify themselves
  327. # entirely. Fill in an empty phrase for such cases.
  328. version, codeBytes = parts
  329. phrase = b""
  330. elif len(parts) == 3:
  331. version, codeBytes, phrase = parts
  332. else:
  333. raise ParseError("wrong number of parts", status)
  334. try:
  335. statusCode = int(codeBytes)
  336. except ValueError:
  337. raise ParseError("non-integer status code", status)
  338. self.response = Response._construct(
  339. self.parseVersion(version),
  340. statusCode,
  341. phrase,
  342. self.headers,
  343. self.transport,
  344. self.request,
  345. )
  346. def _finished(self, rest):
  347. """
  348. Called to indicate that an entire response has been received. No more
  349. bytes will be interpreted by this L{HTTPClientParser}. Extra bytes are
  350. passed up and the state of this L{HTTPClientParser} is set to I{DONE}.
  351. @param rest: A C{bytes} giving any extra bytes delivered to this
  352. L{HTTPClientParser} which are not part of the response being
  353. parsed.
  354. """
  355. self.state = DONE
  356. self.finisher(rest)
  357. def isConnectionControlHeader(self, name):
  358. """
  359. Content-Length in the response to a HEAD request is an entity header,
  360. not a connection control header.
  361. """
  362. if self.request.method == b"HEAD" and name == b"content-length":
  363. return False
  364. return HTTPParser.isConnectionControlHeader(self, name)
  365. def allHeadersReceived(self):
  366. """
  367. Figure out how long the response body is going to be by examining
  368. headers and stuff.
  369. """
  370. if 100 <= self.response.code < 200:
  371. # RFC 7231 Section 6.2 says that if we receive a 1XX status code
  372. # and aren't expecting it, we MAY ignore it. That's what we're
  373. # going to do. We reset the parser here, but we leave
  374. # _everReceivedData in its True state because we have, in fact,
  375. # received data.
  376. self._log.info(
  377. "Ignoring unexpected {code} response", code=self.response.code
  378. )
  379. self.connectionMade()
  380. del self.response
  381. return
  382. if self.response.code in self.NO_BODY_CODES or self.request.method == b"HEAD":
  383. self.response.length = 0
  384. # The order of the next two lines might be of interest when adding
  385. # support for pipelining.
  386. self._finished(self.clearLineBuffer())
  387. self.response._bodyDataFinished()
  388. else:
  389. transferEncodingHeaders = self.connHeaders.getRawHeaders(
  390. b"transfer-encoding"
  391. )
  392. if transferEncodingHeaders:
  393. # This could be a KeyError. However, that would mean we do not
  394. # know how to decode the response body, so failing the request
  395. # is as good a behavior as any. Perhaps someday we will want
  396. # to normalize/document/test this specifically, but failing
  397. # seems fine to me for now.
  398. transferDecoder = self._transferDecoders[
  399. transferEncodingHeaders[0].lower()
  400. ]
  401. # If anyone ever invents a transfer encoding other than
  402. # chunked (yea right), and that transfer encoding can predict
  403. # the length of the response body, it might be sensible to
  404. # allow the transfer decoder to set the response object's
  405. # length attribute.
  406. else:
  407. contentLength = _contentLength(self.connHeaders)
  408. if contentLength is not None:
  409. self.response.length = contentLength
  410. if contentLength == 0:
  411. self._finished(self.clearLineBuffer())
  412. transferDecoder = None
  413. else:
  414. transferDecoder = lambda x, y: _IdentityTransferDecoder(
  415. contentLength, x, y
  416. )
  417. if transferDecoder is None:
  418. self.response._bodyDataFinished()
  419. else:
  420. # Make sure as little data as possible from the response body
  421. # gets delivered to the response object until the response
  422. # object actually indicates it is ready to handle bytes
  423. # (probably because an application gave it a way to interpret
  424. # them).
  425. self.transport.pauseProducing()
  426. self.switchToBodyMode(
  427. transferDecoder(self.response._bodyDataReceived, self._finished)
  428. )
  429. # This must be last. If it were first, then application code might
  430. # change some state (for example, registering a protocol to receive the
  431. # response body). Then the pauseProducing above would be wrong since
  432. # the response is ready for bytes and nothing else would ever resume
  433. # the transport.
  434. self._responseDeferred.callback(self.response)
  435. del self._responseDeferred
  436. def connectionLost(self, reason: Failure | None = None) -> None:
  437. if self.bodyDecoder is not None:
  438. # Handle exceptions from both the body decoder itself and the
  439. # various invocations of _bodyDataFinished; treat them all as
  440. # application code. The response is part of the HTTP server and
  441. # really shouldn't raise exceptions, but maybe there's some buggy
  442. # application code somewhere making things difficult.
  443. with _ignoreDecoderErrors:
  444. try:
  445. self.bodyDecoder.noMoreData()
  446. except PotentialDataLoss:
  447. self.response._bodyDataFinished(Failure())
  448. except _DataLoss:
  449. self.response._bodyDataFinished(
  450. Failure(ResponseFailed([reason, Failure()], self.response))
  451. )
  452. else:
  453. self.response._bodyDataFinished()
  454. elif self.state != DONE:
  455. if self._everReceivedData:
  456. exceptionClass = ResponseFailed
  457. else:
  458. exceptionClass = ResponseNeverReceived
  459. self._responseDeferred.errback(Failure(exceptionClass([reason])))
  460. del self._responseDeferred
  461. _VALID_METHOD = re.compile(
  462. rb"\A[%s]+\Z"
  463. % (
  464. bytes().join(
  465. (
  466. b"!",
  467. b"#",
  468. b"$",
  469. b"%",
  470. b"&",
  471. b"'",
  472. b"*",
  473. b"+",
  474. b"-",
  475. b".",
  476. b"^",
  477. b"_",
  478. b"`",
  479. b"|",
  480. b"~",
  481. b"\x30-\x39",
  482. b"\x41-\x5a",
  483. b"\x61-\x7a",
  484. ),
  485. ),
  486. ),
  487. )
  488. def _ensureValidMethod(method):
  489. """
  490. An HTTP method is an HTTP token, which consists of any visible
  491. ASCII character that is not a delimiter (i.e. one of
  492. C{"(),/:;<=>?@[\\]{}}.)
  493. @param method: the method to check
  494. @type method: L{bytes}
  495. @return: the method if it is valid
  496. @rtype: L{bytes}
  497. @raise ValueError: if the method is not valid
  498. @see: U{https://tools.ietf.org/html/rfc7230#section-3.1.1},
  499. U{https://tools.ietf.org/html/rfc7230#section-3.2.6},
  500. U{https://tools.ietf.org/html/rfc5234#appendix-B.1}
  501. """
  502. if _VALID_METHOD.match(method):
  503. return method
  504. raise ValueError(f"Invalid method {method!r}")
  505. _VALID_URI = re.compile(rb"\A[\x21-\x7e]+\Z")
  506. def _ensureValidURI(uri):
  507. """
  508. A valid URI cannot contain control characters (i.e., characters
  509. between 0-32, inclusive and 127) or non-ASCII characters (i.e.,
  510. characters with values between 128-255, inclusive).
  511. @param uri: the URI to check
  512. @type uri: L{bytes}
  513. @return: the URI if it is valid
  514. @rtype: L{bytes}
  515. @raise ValueError: if the URI is not valid
  516. @see: U{https://tools.ietf.org/html/rfc3986#section-3.3},
  517. U{https://tools.ietf.org/html/rfc3986#appendix-A},
  518. U{https://tools.ietf.org/html/rfc5234#appendix-B.1}
  519. """
  520. if _VALID_URI.match(uri):
  521. return uri
  522. raise ValueError(f"Invalid URI {uri!r}")
  523. def _decint(data: bytes) -> int:
  524. """
  525. Parse a decimal integer of the form C{1*DIGIT}, i.e. consisting only of
  526. decimal digits. The integer may be embedded in whitespace (space and
  527. horizontal tab). This differs from the built-in L{int()} function by
  528. disallowing a leading C{+} character and various forms of whitespace
  529. (note that we sanitize linear whitespace in header values in
  530. L{twisted.web.http_headers.Headers}).
  531. @param data: Value to parse.
  532. @returns: A non-negative integer.
  533. @raises ValueError: When I{value} contains non-decimal characters.
  534. """
  535. data = data.strip(b" \t")
  536. if not data.isdigit():
  537. raise ValueError(f"Value contains non-decimal digits: {data!r}")
  538. return int(data)
  539. def _contentLength(connHeaders: Headers) -> Optional[int]:
  540. """
  541. Parse the I{Content-Length} connection header.
  542. Two forms of duplicates are permitted. Header repetition:
  543. Content-Length: 42
  544. Content-Length: 42
  545. And field value repetition:
  546. Content-Length: 42, 42
  547. Duplicates are only permitted if they have the same decimal value
  548. (so C{7, 007} are also permitted).
  549. @param connHeaders: Connection headers per L{HTTPParser.connHeaders}
  550. @returns: A non-negative number of octets, or L{None} when there is
  551. no I{Content-Length} header.
  552. @raises ValueError: when there are conflicting headers, a header value
  553. isn't an integer, or a header value is negative.
  554. @see: U{https://datatracker.ietf.org/doc/html/rfc9110#section-8.6}
  555. """
  556. headers = connHeaders.getRawHeaders(b"content-length")
  557. if headers is None:
  558. return None
  559. if len(headers) > 1:
  560. fieldValues = b",".join(headers)
  561. else:
  562. [fieldValues] = headers
  563. if b"," in fieldValues:
  564. # Duplicates of the form b'42, 42' are allowed.
  565. values = {_decint(v) for v in fieldValues.split(b",")}
  566. if len(values) != 1:
  567. # "HTTP Message Splitting" or "HTTP Response Smuggling"
  568. # potentially happening. Or it's just a buggy server.
  569. raise ValueError(
  570. f"Invalid response: conflicting Content-Length headers: {fieldValues!r}"
  571. )
  572. [value] = values
  573. else:
  574. value = _decint(fieldValues)
  575. return value
  576. @implementer(IClientRequest)
  577. class Request:
  578. """
  579. A L{Request} instance describes an HTTP request to be sent to an HTTP
  580. server.
  581. @ivar method: See L{__init__}.
  582. @ivar uri: See L{__init__}.
  583. @ivar headers: See L{__init__}.
  584. @ivar bodyProducer: See L{__init__}.
  585. @ivar persistent: See L{__init__}.
  586. @ivar _parsedURI: Parsed I{URI} for the request, or L{None}.
  587. @type _parsedURI: L{twisted.web.client.URI} or L{None}
  588. """
  589. _log = Logger()
  590. def __init__(self, method, uri, headers, bodyProducer, persistent=False):
  591. """
  592. @param method: The HTTP method for this request, ex: b'GET', b'HEAD',
  593. b'POST', etc.
  594. @type method: L{bytes}
  595. @param uri: The relative URI of the resource to request. For example,
  596. C{b'/foo/bar?baz=quux'}.
  597. @type uri: L{bytes}
  598. @param headers: Headers to be sent to the server. It is important to
  599. note that this object does not create any implicit headers. So it
  600. is up to the HTTP Client to add required headers such as 'Host'.
  601. @type headers: L{twisted.web.http_headers.Headers}
  602. @param bodyProducer: L{None} or an L{IBodyProducer} provider which
  603. produces the content body to send to the remote HTTP server.
  604. @param persistent: Set to C{True} when you use HTTP persistent
  605. connection, defaults to C{False}.
  606. @type persistent: L{bool}
  607. """
  608. self.method = _ensureValidMethod(method)
  609. self.uri = _ensureValidURI(uri)
  610. self.headers = headers
  611. self.bodyProducer = bodyProducer
  612. self.persistent = persistent
  613. self._parsedURI = None
  614. @classmethod
  615. def _construct(
  616. cls, method, uri, headers, bodyProducer, persistent=False, parsedURI=None
  617. ):
  618. """
  619. Private constructor.
  620. @param method: See L{__init__}.
  621. @param uri: See L{__init__}.
  622. @param headers: See L{__init__}.
  623. @param bodyProducer: See L{__init__}.
  624. @param persistent: See L{__init__}.
  625. @param parsedURI: See L{Request._parsedURI}.
  626. @return: L{Request} instance.
  627. """
  628. request = cls(method, uri, headers, bodyProducer, persistent)
  629. request._parsedURI = parsedURI
  630. return request
  631. @property
  632. def absoluteURI(self):
  633. """
  634. The absolute URI of the request as C{bytes}, or L{None} if the
  635. absolute URI cannot be determined.
  636. """
  637. return getattr(self._parsedURI, "toBytes", lambda: None)()
  638. def _writeHeaders(self, transport, TEorCL):
  639. hosts = self.headers.getRawHeaders(b"host", ())
  640. if len(hosts) != 1:
  641. raise BadHeaders("Exactly one Host header required")
  642. # In the future, having the protocol version be a parameter to this
  643. # method would probably be good. It would be nice if this method
  644. # weren't limited to issuing HTTP/1.1 requests.
  645. requestLines = []
  646. requestLines.append(
  647. b" ".join(
  648. [
  649. _ensureValidMethod(self.method),
  650. _ensureValidURI(self.uri),
  651. b"HTTP/1.1\r\n",
  652. ]
  653. ),
  654. )
  655. if not self.persistent:
  656. requestLines.append(b"Connection: close\r\n")
  657. if TEorCL is not None:
  658. requestLines.append(TEorCL)
  659. for name, values in self.headers.getAllRawHeaders():
  660. requestLines.extend([name + b": " + v + b"\r\n" for v in values])
  661. requestLines.append(b"\r\n")
  662. transport.writeSequence(requestLines)
  663. def _writeToBodyProducerChunked(self, transport):
  664. """
  665. Write this request to the given transport using chunked
  666. transfer-encoding to frame the body.
  667. @param transport: See L{writeTo}.
  668. @return: See L{writeTo}.
  669. """
  670. self._writeHeaders(transport, b"Transfer-Encoding: chunked\r\n")
  671. encoder = ChunkedEncoder(transport)
  672. encoder.registerProducer(self.bodyProducer, True)
  673. d = self.bodyProducer.startProducing(encoder)
  674. def cbProduced(ignored):
  675. encoder.unregisterProducer()
  676. def ebProduced(err):
  677. encoder._allowNoMoreWrites()
  678. # Don't call the encoder's unregisterProducer because it will write
  679. # a zero-length chunk. This would indicate to the server that the
  680. # request body is complete. There was an error, though, so we
  681. # don't want to do that.
  682. transport.unregisterProducer()
  683. return err
  684. d.addCallbacks(cbProduced, ebProduced)
  685. return d
  686. def _writeToBodyProducerContentLength(self, transport):
  687. """
  688. Write this request to the given transport using content-length to frame
  689. the body.
  690. @param transport: See L{writeTo}.
  691. @return: See L{writeTo}.
  692. """
  693. self._writeHeaders(
  694. transport,
  695. networkString("Content-Length: %d\r\n" % (self.bodyProducer.length,)),
  696. )
  697. # This Deferred is used to signal an error in the data written to the
  698. # encoder below. It can only errback and it will only do so before too
  699. # many bytes have been written to the encoder and before the producer
  700. # Deferred fires.
  701. finishedConsuming = Deferred()
  702. # This makes sure the producer writes the correct number of bytes for
  703. # the request body.
  704. encoder = LengthEnforcingConsumer(
  705. self.bodyProducer, transport, finishedConsuming
  706. )
  707. transport.registerProducer(self.bodyProducer, True)
  708. finishedProducing = self.bodyProducer.startProducing(encoder)
  709. def combine(consuming, producing):
  710. # This Deferred is returned and will be fired when the first of
  711. # consuming or producing fires. If it's cancelled, forward that
  712. # cancellation to the producer.
  713. def cancelConsuming(ign):
  714. finishedProducing.cancel()
  715. ultimate = Deferred(cancelConsuming)
  716. # Keep track of what has happened so far. This initially
  717. # contains None, then an integer uniquely identifying what
  718. # sequence of events happened. See the callbacks and errbacks
  719. # defined below for the meaning of each value.
  720. state = [None]
  721. def ebConsuming(err):
  722. if state == [None]:
  723. # The consuming Deferred failed first. This means the
  724. # overall writeTo Deferred is going to errback now. The
  725. # producing Deferred should not fire later (because the
  726. # consumer should have called stopProducing on the
  727. # producer), but if it does, a callback will be ignored
  728. # and an errback will be logged.
  729. state[0] = 1
  730. ultimate.errback(err)
  731. else:
  732. # The consuming Deferred errbacked after the producing
  733. # Deferred fired. This really shouldn't ever happen.
  734. # If it does, I goofed. Log the error anyway, just so
  735. # there's a chance someone might notice and complain.
  736. self._log.failure(
  737. "Buggy state machine in {request}/[{state}]: "
  738. "ebConsuming called",
  739. failure=err,
  740. request=repr(self),
  741. state=state[0],
  742. )
  743. def cbProducing(result):
  744. if state == [None]:
  745. # The producing Deferred succeeded first. Nothing will
  746. # ever happen to the consuming Deferred. Tell the
  747. # encoder we're done so it can check what the producer
  748. # wrote and make sure it was right.
  749. state[0] = 2
  750. try:
  751. encoder._noMoreWritesExpected()
  752. except BaseException:
  753. # Fail the overall writeTo Deferred - something the
  754. # producer did was wrong.
  755. ultimate.errback()
  756. else:
  757. # Success - succeed the overall writeTo Deferred.
  758. ultimate.callback(None)
  759. # Otherwise, the consuming Deferred already errbacked. The
  760. # producing Deferred wasn't supposed to fire, but it did
  761. # anyway. It's buggy, but there's not really anything to be
  762. # done about it. Just ignore this result.
  763. def ebProducing(err):
  764. if state == [None]:
  765. # The producing Deferred failed first. This means the
  766. # overall writeTo Deferred is going to errback now.
  767. # Tell the encoder that we're done so it knows to reject
  768. # further writes from the producer (which should not
  769. # happen, but the producer may be buggy).
  770. state[0] = 3
  771. encoder._allowNoMoreWrites()
  772. ultimate.errback(err)
  773. else:
  774. # The producing Deferred failed after the consuming
  775. # Deferred failed. It shouldn't have, so it's buggy.
  776. # Log the exception in case anyone who can fix the code
  777. # is watching.
  778. self._log.failure("Producer is buggy", failure=err)
  779. consuming.addErrback(ebConsuming)
  780. producing.addCallbacks(cbProducing, ebProducing)
  781. return ultimate
  782. d = combine(finishedConsuming, finishedProducing)
  783. def f(passthrough):
  784. # Regardless of what happens with the overall Deferred, once it
  785. # fires, the producer registered way up above the definition of
  786. # combine should be unregistered.
  787. transport.unregisterProducer()
  788. return passthrough
  789. d.addBoth(f)
  790. return d
  791. def _writeToEmptyBodyContentLength(self, transport):
  792. """
  793. Write this request to the given transport using content-length to frame
  794. the (empty) body.
  795. @param transport: See L{writeTo}.
  796. @return: See L{writeTo}.
  797. """
  798. self._writeHeaders(transport, b"Content-Length: 0\r\n")
  799. return succeed(None)
  800. def writeTo(self, transport):
  801. """
  802. Format this L{Request} as an HTTP/1.1 request and write it to the given
  803. transport. If bodyProducer is not None, it will be associated with an
  804. L{IConsumer}.
  805. @param transport: The transport to which to write.
  806. @type transport: L{twisted.internet.interfaces.ITransport} provider
  807. @return: A L{Deferred} which fires with L{None} when the request has
  808. been completely written to the transport or with a L{Failure} if
  809. there is any problem generating the request bytes.
  810. """
  811. if self.bodyProducer is None:
  812. # If the method semantics anticipate a body, include a
  813. # Content-Length even if it is 0.
  814. # https://tools.ietf.org/html/rfc7230#section-3.3.2
  815. if self.method in (b"PUT", b"POST"):
  816. self._writeToEmptyBodyContentLength(transport)
  817. else:
  818. self._writeHeaders(transport, None)
  819. return succeed(None)
  820. elif self.bodyProducer.length is UNKNOWN_LENGTH:
  821. return self._writeToBodyProducerChunked(transport)
  822. else:
  823. return self._writeToBodyProducerContentLength(transport)
  824. def stopWriting(self) -> None:
  825. """
  826. Stop writing this request to the transport. This can only be called
  827. after C{writeTo} and before the L{Deferred} returned by C{writeTo}
  828. fires. It should cancel any asynchronous task started by C{writeTo}.
  829. The L{Deferred} returned by C{writeTo} need not be fired if this method
  830. is called.
  831. """
  832. # If bodyProducer is None, then the Deferred returned by writeTo has
  833. # fired already and this method cannot be called.
  834. with _ignoreStopProducerStopWriting:
  835. self.bodyProducer.stopProducing()
  836. class LengthEnforcingConsumer:
  837. """
  838. An L{IConsumer} proxy which enforces an exact length requirement on the
  839. total data written to it.
  840. @ivar _length: The number of bytes remaining to be written.
  841. @ivar _producer: The L{IBodyProducer} which is writing to this
  842. consumer.
  843. @ivar _consumer: The consumer to which at most C{_length} bytes will be
  844. forwarded.
  845. @ivar _finished: A L{Deferred} which will be fired with a L{Failure} if too
  846. many bytes are written to this consumer.
  847. """
  848. def __init__(self, producer, consumer, finished):
  849. self._length = producer.length
  850. self._producer = producer
  851. self._consumer = consumer
  852. self._finished = finished
  853. def _allowNoMoreWrites(self):
  854. """
  855. Indicate that no additional writes are allowed. Attempts to write
  856. after calling this method will be met with an exception.
  857. """
  858. self._finished = None
  859. def write(self, bytes):
  860. """
  861. Write C{bytes} to the underlying consumer unless
  862. C{_noMoreWritesExpected} has been called or there are/have been too
  863. many bytes.
  864. """
  865. if self._finished is None:
  866. # No writes are supposed to happen any more. Try to convince the
  867. # calling code to stop calling this method by calling its
  868. # stopProducing method and then throwing an exception at it. This
  869. # exception isn't documented as part of the API because you're
  870. # never supposed to expect it: only buggy code will ever receive
  871. # it.
  872. self._producer.stopProducing()
  873. raise ExcessWrite()
  874. if len(bytes) <= self._length:
  875. self._length -= len(bytes)
  876. self._consumer.write(bytes)
  877. else:
  878. # No synchronous exception is raised in *this* error path because
  879. # we still have _finished which we can use to report the error to a
  880. # better place than the direct caller of this method (some
  881. # arbitrary application code).
  882. with _ignoreStopProducerWrite:
  883. self._producer.stopProducing()
  884. self._finished.errback(WrongBodyLength("too many bytes written"))
  885. self._allowNoMoreWrites()
  886. def _noMoreWritesExpected(self):
  887. """
  888. Called to indicate no more bytes will be written to this consumer.
  889. Check to see that the correct number have been written.
  890. @raise WrongBodyLength: If not enough bytes have been written.
  891. """
  892. if self._finished is not None:
  893. self._allowNoMoreWrites()
  894. if self._length:
  895. raise WrongBodyLength("too few bytes written")
  896. def makeStatefulDispatcher(name, template):
  897. """
  898. Given a I{dispatch} name and a function, return a function which can be
  899. used as a method and which, when called, will call another method defined
  900. on the instance and return the result. The other method which is called is
  901. determined by the value of the C{_state} attribute of the instance.
  902. @param name: A string which is used to construct the name of the subsidiary
  903. method to invoke. The subsidiary method is named like C{'_%s_%s' %
  904. (name, _state)}.
  905. @param template: A function object which is used to give the returned
  906. function a docstring.
  907. @return: The dispatcher function.
  908. """
  909. pfx = f"_{name}_"
  910. def dispatcher(self, *args, **kwargs):
  911. func = getattr(self, f"{pfx}{self._state}", None)
  912. if func is None:
  913. raise RuntimeError(f"{self!r} has no {name} method in state {self._state}")
  914. return func(*args, **kwargs)
  915. dispatcher.__doc__ = template.__doc__
  916. return dispatcher
  917. # This proxy class is used only in the private constructor of the Response
  918. # class below, in order to prevent users relying on any property of the
  919. # concrete request object: they can only use what is provided by
  920. # IClientRequest.
  921. _ClientRequestProxy = proxyForInterface(IClientRequest)
  922. @implementer(IResponse)
  923. class Response:
  924. """
  925. A L{Response} instance describes an HTTP response received from an HTTP
  926. server.
  927. L{Response} should not be subclassed or instantiated.
  928. @ivar _transport: See L{__init__}.
  929. @ivar _bodyProtocol: The L{IProtocol} provider to which the body is
  930. delivered. L{None} before one has been registered with
  931. C{deliverBody}.
  932. @ivar _bodyBuffer: A C{list} of the strings passed to C{bodyDataReceived}
  933. before C{deliverBody} is called. L{None} afterwards.
  934. @ivar _state: Indicates what state this L{Response} instance is in,
  935. particularly with respect to delivering bytes from the response body
  936. to an application-supplied protocol object. This may be one of
  937. C{'INITIAL'}, C{'CONNECTED'}, C{'DEFERRED_CLOSE'}, or C{'FINISHED'},
  938. with the following meanings:
  939. - INITIAL: This is the state L{Response} objects start in. No
  940. protocol has yet been provided and the underlying transport may
  941. still have bytes to deliver to it.
  942. - DEFERRED_CLOSE: If the underlying transport indicates all bytes
  943. have been delivered but no application-provided protocol is yet
  944. available, the L{Response} moves to this state. Data is
  945. buffered and waiting for a protocol to be delivered to.
  946. - CONNECTED: If a protocol is provided when the state is INITIAL,
  947. the L{Response} moves to this state. Any buffered data is
  948. delivered and any data which arrives from the transport
  949. subsequently is given directly to the protocol.
  950. - FINISHED: If a protocol is provided in the DEFERRED_CLOSE state,
  951. the L{Response} moves to this state after delivering all
  952. buffered data to the protocol. Otherwise, if the L{Response} is
  953. in the CONNECTED state, if the transport indicates there is no
  954. more data, the L{Response} moves to this state. Nothing else
  955. can happen once the L{Response} is in this state.
  956. @type _state: C{str}
  957. """
  958. length = UNKNOWN_LENGTH
  959. _bodyProtocol = None
  960. _bodyFinished = False
  961. def __init__(self, version, code, phrase, headers, _transport):
  962. """
  963. @param version: HTTP version components protocol, major, minor. E.g.
  964. C{(b'HTTP', 1, 1)} to mean C{b'HTTP/1.1'}.
  965. @param code: HTTP status code.
  966. @type code: L{int}
  967. @param phrase: HTTP reason phrase, intended to give a short description
  968. of the HTTP status code.
  969. @param headers: HTTP response headers.
  970. @type headers: L{twisted.web.http_headers.Headers}
  971. @param _transport: The transport which is delivering this response.
  972. """
  973. self.version = version
  974. self.code = code
  975. self.phrase = phrase
  976. self.headers = headers
  977. self._transport = _transport
  978. self._bodyBuffer = []
  979. self._state = "INITIAL"
  980. self.request = None
  981. self.previousResponse = None
  982. @classmethod
  983. def _construct(cls, version, code, phrase, headers, _transport, request):
  984. """
  985. Private constructor.
  986. @param version: See L{__init__}.
  987. @param code: See L{__init__}.
  988. @param phrase: See L{__init__}.
  989. @param headers: See L{__init__}.
  990. @param _transport: See L{__init__}.
  991. @param request: See L{IResponse.request}.
  992. @return: L{Response} instance.
  993. """
  994. response = Response(version, code, phrase, headers, _transport)
  995. response.request = _ClientRequestProxy(request)
  996. return response
  997. def setPreviousResponse(self, previousResponse):
  998. self.previousResponse = previousResponse
  999. def deliverBody(self, protocol):
  1000. """
  1001. Dispatch the given L{IProtocol} depending of the current state of the
  1002. response.
  1003. """
  1004. deliverBody = makeStatefulDispatcher("deliverBody", deliverBody)
  1005. def _deliverBody_INITIAL(self, protocol):
  1006. """
  1007. Deliver any buffered data to C{protocol} and prepare to deliver any
  1008. future data to it. Move to the C{'CONNECTED'} state.
  1009. """
  1010. protocol.makeConnection(self._transport)
  1011. self._bodyProtocol = protocol
  1012. for data in self._bodyBuffer:
  1013. self._bodyProtocol.dataReceived(data)
  1014. self._bodyBuffer = None
  1015. self._state = "CONNECTED"
  1016. # Now that there's a protocol to consume the body, resume the
  1017. # transport. It was previously paused by HTTPClientParser to avoid
  1018. # reading too much data before it could be handled. We need to do this
  1019. # after we transition our state as it may recursively lead to more data
  1020. # being delivered, or even the body completing.
  1021. self._transport.resumeProducing()
  1022. def _deliverBody_CONNECTED(self, protocol):
  1023. """
  1024. It is invalid to attempt to deliver data to a protocol when it is
  1025. already being delivered to another protocol.
  1026. """
  1027. raise RuntimeError(
  1028. "Response already has protocol %r, cannot deliverBody "
  1029. "again" % (self._bodyProtocol,)
  1030. )
  1031. def _deliverBody_DEFERRED_CLOSE(self, protocol):
  1032. """
  1033. Deliver any buffered data to C{protocol} and then disconnect the
  1034. protocol. Move to the C{'FINISHED'} state.
  1035. """
  1036. # Unlike _deliverBody_INITIAL, there is no need to resume the
  1037. # transport here because all of the response data has been received
  1038. # already. Some higher level code may want to resume the transport if
  1039. # that code expects further data to be received over it.
  1040. protocol.makeConnection(self._transport)
  1041. for data in self._bodyBuffer:
  1042. protocol.dataReceived(data)
  1043. self._bodyBuffer = None
  1044. protocol.connectionLost(self._reason)
  1045. self._state = "FINISHED"
  1046. def _deliverBody_FINISHED(self, protocol):
  1047. """
  1048. It is invalid to attempt to deliver data to a protocol after the
  1049. response body has been delivered to another protocol.
  1050. """
  1051. raise RuntimeError("Response already finished, cannot deliverBody now.")
  1052. def _bodyDataReceived(self, data):
  1053. """
  1054. Called by HTTPClientParser with chunks of data from the response body.
  1055. They will be buffered or delivered to the protocol passed to
  1056. deliverBody.
  1057. """
  1058. _bodyDataReceived = makeStatefulDispatcher("bodyDataReceived", _bodyDataReceived)
  1059. def _bodyDataReceived_INITIAL(self, data):
  1060. """
  1061. Buffer any data received for later delivery to a protocol passed to
  1062. C{deliverBody}.
  1063. Little or no data should be buffered by this method, since the
  1064. transport has been paused and will not be resumed until a protocol
  1065. is supplied.
  1066. """
  1067. self._bodyBuffer.append(data)
  1068. def _bodyDataReceived_CONNECTED(self, data):
  1069. """
  1070. Deliver any data received to the protocol to which this L{Response}
  1071. is connected.
  1072. """
  1073. self._bodyProtocol.dataReceived(data)
  1074. def _bodyDataReceived_DEFERRED_CLOSE(self, data):
  1075. """
  1076. It is invalid for data to be delivered after it has been indicated
  1077. that the response body has been completely delivered.
  1078. """
  1079. raise RuntimeError("Cannot receive body data after _bodyDataFinished")
  1080. def _bodyDataReceived_FINISHED(self, data):
  1081. """
  1082. It is invalid for data to be delivered after the response body has
  1083. been delivered to a protocol.
  1084. """
  1085. raise RuntimeError("Cannot receive body data after " "protocol disconnected")
  1086. def _bodyDataFinished(self, reason=None):
  1087. """
  1088. Called by HTTPClientParser when no more body data is available. If the
  1089. optional reason is supplied, this indicates a problem or potential
  1090. problem receiving all of the response body.
  1091. """
  1092. _bodyDataFinished = makeStatefulDispatcher("bodyDataFinished", _bodyDataFinished)
  1093. def _bodyDataFinished_INITIAL(self, reason=None):
  1094. """
  1095. Move to the C{'DEFERRED_CLOSE'} state to wait for a protocol to
  1096. which to deliver the response body.
  1097. """
  1098. self._state = "DEFERRED_CLOSE"
  1099. if reason is None:
  1100. reason = Failure._withoutTraceback(
  1101. ResponseDone("Response body fully received")
  1102. )
  1103. self._reason = reason
  1104. def _bodyDataFinished_CONNECTED(self, reason=None):
  1105. """
  1106. Disconnect the protocol and move to the C{'FINISHED'} state.
  1107. """
  1108. if reason is None:
  1109. reason = Failure._withoutTraceback(
  1110. ResponseDone("Response body fully received")
  1111. )
  1112. self._bodyProtocol.connectionLost(reason)
  1113. self._bodyProtocol = None
  1114. self._state = "FINISHED"
  1115. def _bodyDataFinished_DEFERRED_CLOSE(self):
  1116. """
  1117. It is invalid to attempt to notify the L{Response} of the end of the
  1118. response body data more than once.
  1119. """
  1120. raise RuntimeError("Cannot finish body data more than once")
  1121. def _bodyDataFinished_FINISHED(self):
  1122. """
  1123. It is invalid to attempt to notify the L{Response} of the end of the
  1124. response body data more than once.
  1125. """
  1126. raise RuntimeError("Cannot finish body data after " "protocol disconnected")
  1127. @implementer(IConsumer)
  1128. class ChunkedEncoder:
  1129. """
  1130. Helper object which exposes L{IConsumer} on top of L{HTTP11ClientProtocol}
  1131. for streaming request bodies to the server.
  1132. """
  1133. def __init__(self, transport):
  1134. self.transport = transport
  1135. def _allowNoMoreWrites(self):
  1136. """
  1137. Indicate that no additional writes are allowed. Attempts to write
  1138. after calling this method will be met with an exception.
  1139. """
  1140. self.transport = None
  1141. def registerProducer(self, producer, streaming):
  1142. """
  1143. Register the given producer with C{self.transport}.
  1144. """
  1145. self.transport.registerProducer(producer, streaming)
  1146. def write(self, data):
  1147. """
  1148. Write the given request body bytes to the transport using chunked
  1149. encoding.
  1150. @type data: C{bytes}
  1151. """
  1152. if self.transport is None:
  1153. raise ExcessWrite()
  1154. self.transport.writeSequence(
  1155. (networkString("%x\r\n" % len(data)), data, b"\r\n")
  1156. )
  1157. def unregisterProducer(self):
  1158. """
  1159. Indicate that the request body is complete and finish the request.
  1160. """
  1161. self.write(b"")
  1162. self.transport.unregisterProducer()
  1163. self._allowNoMoreWrites()
  1164. @implementer(IPushProducer)
  1165. class TransportProxyProducer:
  1166. """
  1167. An L{twisted.internet.interfaces.IPushProducer} implementation which
  1168. wraps another such thing and proxies calls to it until it is told to stop.
  1169. @ivar _producer: The wrapped L{twisted.internet.interfaces.IPushProducer}
  1170. provider or L{None} after this proxy has been stopped.
  1171. """
  1172. # LineReceiver uses this undocumented attribute of transports to decide
  1173. # when to stop calling lineReceived or rawDataReceived (if it finds it to
  1174. # be true, it doesn't bother to deliver any more data). Set disconnecting
  1175. # to False here and never change it to true so that all data is always
  1176. # delivered to us and so that LineReceiver doesn't fail with an
  1177. # AttributeError.
  1178. disconnecting = False
  1179. def __init__(self, producer):
  1180. self._producer = producer
  1181. def stopProxying(self):
  1182. """
  1183. Stop forwarding calls of L{twisted.internet.interfaces.IPushProducer}
  1184. methods to the underlying L{twisted.internet.interfaces.IPushProducer}
  1185. provider.
  1186. """
  1187. self._producer = None
  1188. def stopProducing(self):
  1189. """
  1190. Proxy the stoppage to the underlying producer, unless this proxy has
  1191. been stopped.
  1192. """
  1193. if self._producer is not None:
  1194. self._producer.stopProducing()
  1195. def resumeProducing(self):
  1196. """
  1197. Proxy the resumption to the underlying producer, unless this proxy has
  1198. been stopped.
  1199. """
  1200. if self._producer is not None:
  1201. self._producer.resumeProducing()
  1202. def pauseProducing(self):
  1203. """
  1204. Proxy the pause to the underlying producer, unless this proxy has been
  1205. stopped.
  1206. """
  1207. if self._producer is not None:
  1208. self._producer.pauseProducing()
  1209. def loseConnection(self):
  1210. """
  1211. Proxy the request to lose the connection to the underlying producer,
  1212. unless this proxy has been stopped.
  1213. """
  1214. if self._producer is not None:
  1215. self._producer.loseConnection()
  1216. class HTTP11ClientProtocol(Protocol):
  1217. """
  1218. L{HTTP11ClientProtocol} is an implementation of the HTTP 1.1 client
  1219. protocol. It supports as few features as possible.
  1220. @ivar _parser: After a request is issued, the L{HTTPClientParser} to
  1221. which received data making up the response to that request is
  1222. delivered.
  1223. @ivar _finishedRequest: After a request is issued, the L{Deferred} which
  1224. will fire when a L{Response} object corresponding to that request is
  1225. available. This allows L{HTTP11ClientProtocol} to fail the request
  1226. if there is a connection or parsing problem.
  1227. @ivar _currentRequest: After a request is issued, the L{Request}
  1228. instance used to make that request. This allows
  1229. L{HTTP11ClientProtocol} to stop request generation if necessary (for
  1230. example, if the connection is lost).
  1231. @ivar _transportProxy: After a request is issued, the
  1232. L{TransportProxyProducer} to which C{_parser} is connected. This
  1233. allows C{_parser} to pause and resume the transport in a way which
  1234. L{HTTP11ClientProtocol} can exert some control over.
  1235. @ivar _responseDeferred: After a request is issued, the L{Deferred} from
  1236. C{_parser} which will fire with a L{Response} when one has been
  1237. received. This is eventually chained with C{_finishedRequest}, but
  1238. only in certain cases to avoid double firing that Deferred.
  1239. @ivar _state: Indicates what state this L{HTTP11ClientProtocol} instance
  1240. is in with respect to transmission of a request and reception of a
  1241. response. This may be one of the following strings:
  1242. - QUIESCENT: This is the state L{HTTP11ClientProtocol} instances
  1243. start in. Nothing is happening: no request is being sent and no
  1244. response is being received or expected.
  1245. - TRANSMITTING: When a request is made (via L{request}), the
  1246. instance moves to this state. L{Request.writeTo} has been used
  1247. to start to send a request but it has not yet finished.
  1248. - TRANSMITTING_AFTER_RECEIVING_RESPONSE: The server has returned a
  1249. complete response but the request has not yet been fully sent
  1250. yet. The instance will remain in this state until the request
  1251. is fully sent.
  1252. - GENERATION_FAILED: There was an error while the request. The
  1253. request was not fully sent to the network.
  1254. - WAITING: The request was fully sent to the network. The
  1255. instance is now waiting for the response to be fully received.
  1256. - ABORTING: Application code has requested that the HTTP connection
  1257. be aborted.
  1258. - CONNECTION_LOST: The connection has been lost.
  1259. @type _state: C{str}
  1260. @ivar _abortDeferreds: A list of C{Deferred} instances that will fire when
  1261. the connection is lost.
  1262. """
  1263. _state = "QUIESCENT"
  1264. _parser: HTTPClientParser | None = None
  1265. _finishedRequest: Deferred[Response] | None = None
  1266. _currentRequest: Request | None = None
  1267. _transportProxy = None
  1268. _responseDeferred: Deferred[Response] | None = None
  1269. _log = Logger()
  1270. def __init__(self, quiescentCallback=lambda c: None):
  1271. self._quiescentCallback = quiescentCallback
  1272. self._abortDeferreds = []
  1273. @property
  1274. def state(self):
  1275. return self._state
  1276. def request(self, request):
  1277. """
  1278. Issue C{request} over C{self.transport} and return a L{Deferred} which
  1279. will fire with a L{Response} instance or an error.
  1280. @param request: The object defining the parameters of the request to
  1281. issue.
  1282. @type request: L{Request}
  1283. @rtype: L{Deferred}
  1284. @return: The deferred may errback with L{RequestGenerationFailed} if
  1285. the request was not fully written to the transport due to a local
  1286. error. It may errback with L{RequestTransmissionFailed} if it was
  1287. not fully written to the transport due to a network error. It may
  1288. errback with L{ResponseFailed} if the request was sent (not
  1289. necessarily received) but some or all of the response was lost. It
  1290. may errback with L{RequestNotSent} if it is not possible to send
  1291. any more requests using this L{HTTP11ClientProtocol}.
  1292. """
  1293. if self._state != "QUIESCENT":
  1294. return fail(RequestNotSent())
  1295. self._state = "TRANSMITTING"
  1296. try:
  1297. _requestDeferred = request.writeTo(self.transport)
  1298. except BaseException:
  1299. _requestDeferred = fail()
  1300. def cancelRequest(ign):
  1301. # Explicitly cancel the request's deferred if it's still trying to
  1302. # write when this request is cancelled.
  1303. if self._state in ("TRANSMITTING", "TRANSMITTING_AFTER_RECEIVING_RESPONSE"):
  1304. _requestDeferred.cancel()
  1305. else:
  1306. self.transport.abortConnection()
  1307. self._disconnectParser(Failure(CancelledError()))
  1308. self._finishedRequest = Deferred(cancelRequest)
  1309. # Keep track of the Request object in case we need to call stopWriting
  1310. # on it.
  1311. self._currentRequest = request
  1312. self._transportProxy = TransportProxyProducer(self.transport)
  1313. self._parser = HTTPClientParser(request, self._finishResponse)
  1314. self._parser.makeConnection(self._transportProxy)
  1315. self._responseDeferred = self._parser._responseDeferred
  1316. def cbRequestWritten(ignored):
  1317. if self._state == "TRANSMITTING":
  1318. self._state = "WAITING"
  1319. self._responseDeferred.chainDeferred(self._finishedRequest)
  1320. def ebRequestWriting(err):
  1321. if self._state == "TRANSMITTING":
  1322. self._state = "GENERATION_FAILED"
  1323. self.transport.abortConnection()
  1324. self._finishedRequest.errback(Failure(RequestGenerationFailed([err])))
  1325. else:
  1326. self._log.failure(
  1327. "Error writing request, but not in valid state "
  1328. "to finalize request: {state}",
  1329. failure=err,
  1330. state=self._state,
  1331. )
  1332. _requestDeferred.addCallbacks(cbRequestWritten, ebRequestWriting)
  1333. return self._finishedRequest
  1334. def _finishResponse(self, rest: bytes) -> None:
  1335. """
  1336. Called by an L{HTTPClientParser} to indicate that it has parsed a
  1337. complete response.
  1338. @param rest: A C{bytes} giving any trailing bytes which were given to
  1339. the L{HTTPClientParser} which were not part of the response it
  1340. was parsing.
  1341. """
  1342. _finishResponse = makeStatefulDispatcher("finishResponse", _finishResponse)
  1343. def _finishResponse_WAITING(self, rest: bytes) -> None:
  1344. # Currently the rest parameter is ignored. Don't forget to use it if
  1345. # we ever add support for pipelining. And maybe check what trailers
  1346. # mean.
  1347. if TYPE_CHECKING:
  1348. assert self._responseDeferred is not None
  1349. assert self._finishedRequest is not None
  1350. assert self._currentRequest is not None
  1351. assert self.transport is not None
  1352. if self._state == "WAITING":
  1353. self._state = "QUIESCENT"
  1354. else:
  1355. # The server sent the entire response before we could send the
  1356. # whole request. That sucks. Oh well. Fire the request()
  1357. # Deferred with the response. But first, make sure that if the
  1358. # request does ever finish being written that it won't try to fire
  1359. # that Deferred.
  1360. self._state = "TRANSMITTING_AFTER_RECEIVING_RESPONSE"
  1361. self._responseDeferred.chainDeferred(self._finishedRequest)
  1362. # This will happen if we're being called due to connection being lost;
  1363. # if so, no need to disconnect parser again, or to call
  1364. # _quiescentCallback.
  1365. if self._parser is None:
  1366. return
  1367. reason = ConnectionDone("synthetic!")
  1368. connHeaders = self._parser.connHeaders.getRawHeaders(b"connection", ())
  1369. if (
  1370. (b"close" in connHeaders)
  1371. or self._state != "QUIESCENT"
  1372. or not self._currentRequest.persistent
  1373. ):
  1374. self._giveUp(Failure._withoutTraceback(reason))
  1375. else:
  1376. # Just in case we had paused the transport, resume it before
  1377. # considering it quiescent again.
  1378. producer: IPushProducer = self.transport # type:ignore[assignment]
  1379. producer.resumeProducing()
  1380. # We call the quiescent callback first, to ensure connection gets
  1381. # added back to connection pool before we finish the request.
  1382. with _moduleLog.failuresHandled("while invoking quiescent callback:") as op:
  1383. self._quiescentCallback(self)
  1384. if op.failed:
  1385. # If callback throws exception, just log it and disconnect;
  1386. # keeping persistent connections around is an optimisation:
  1387. self.transport.loseConnection()
  1388. self._disconnectParser(reason)
  1389. _finishResponse_TRANSMITTING = _finishResponse_WAITING
  1390. def _disconnectParser(self, reason):
  1391. """
  1392. If there is still a parser, call its C{connectionLost} method with the
  1393. given reason. If there is not, do nothing.
  1394. @type reason: L{Failure}
  1395. """
  1396. if self._parser is not None:
  1397. parser = self._parser
  1398. self._parser = None
  1399. self._currentRequest = None
  1400. self._finishedRequest = None
  1401. self._responseDeferred = None
  1402. # The parser is no longer allowed to do anything to the real
  1403. # transport. Stop proxying from the parser's transport to the real
  1404. # transport before telling the parser it's done so that it can't do
  1405. # anything.
  1406. self._transportProxy.stopProxying()
  1407. self._transportProxy = None
  1408. parser.connectionLost(reason)
  1409. def _giveUp(self, reason):
  1410. """
  1411. Lose the underlying connection and disconnect the parser with the given
  1412. L{Failure}.
  1413. Use this method instead of calling the transport's loseConnection
  1414. method directly otherwise random things will break.
  1415. """
  1416. self.transport.loseConnection()
  1417. self._disconnectParser(reason)
  1418. def dataReceived(self, bytes):
  1419. """
  1420. Handle some stuff from some place.
  1421. """
  1422. try:
  1423. self._parser.dataReceived(bytes)
  1424. except BaseException:
  1425. self._giveUp(Failure())
  1426. def connectionLost(self, reason):
  1427. """
  1428. The underlying transport went away. If appropriate, notify the parser
  1429. object.
  1430. """
  1431. connectionLost = makeStatefulDispatcher("connectionLost", connectionLost)
  1432. def _connectionLost_QUIESCENT(self, reason):
  1433. """
  1434. Nothing is currently happening. Move to the C{'CONNECTION_LOST'}
  1435. state but otherwise do nothing.
  1436. """
  1437. self._state = "CONNECTION_LOST"
  1438. def _connectionLost_GENERATION_FAILED(self, reason):
  1439. """
  1440. The connection was in an inconsistent state. Move to the
  1441. C{'CONNECTION_LOST'} state but otherwise do nothing.
  1442. """
  1443. self._state = "CONNECTION_LOST"
  1444. def _connectionLost_TRANSMITTING(self, reason):
  1445. """
  1446. Fail the L{Deferred} for the current request, notify the request
  1447. object that it does not need to continue transmitting itself, and
  1448. move to the C{'CONNECTION_LOST'} state.
  1449. """
  1450. self._state = "CONNECTION_LOST"
  1451. self._finishedRequest.errback(Failure(RequestTransmissionFailed([reason])))
  1452. del self._finishedRequest
  1453. # Tell the request that it should stop bothering now.
  1454. self._currentRequest.stopWriting()
  1455. def _connectionLost_TRANSMITTING_AFTER_RECEIVING_RESPONSE(self, reason):
  1456. """
  1457. Move to the C{'CONNECTION_LOST'} state.
  1458. """
  1459. self._state = "CONNECTION_LOST"
  1460. def _connectionLost_WAITING(self, reason):
  1461. """
  1462. Disconnect the response parser so that it can propagate the event as
  1463. necessary (for example, to call an application protocol's
  1464. C{connectionLost} method, or to fail a request L{Deferred}) and move
  1465. to the C{'CONNECTION_LOST'} state.
  1466. """
  1467. self._disconnectParser(reason)
  1468. self._state = "CONNECTION_LOST"
  1469. def _connectionLost_ABORTING(self, reason):
  1470. """
  1471. Disconnect the response parser with a L{ConnectionAborted} failure, and
  1472. move to the C{'CONNECTION_LOST'} state.
  1473. """
  1474. self._disconnectParser(Failure(ConnectionAborted()))
  1475. self._state = "CONNECTION_LOST"
  1476. for d in self._abortDeferreds:
  1477. d.callback(None)
  1478. self._abortDeferreds = []
  1479. def abort(self):
  1480. """
  1481. Close the connection and cause all outstanding L{request} L{Deferred}s
  1482. to fire with an error.
  1483. """
  1484. if self._state == "CONNECTION_LOST":
  1485. return succeed(None)
  1486. self.transport.loseConnection()
  1487. self._state = "ABORTING"
  1488. d = Deferred()
  1489. self._abortDeferreds.append(d)
  1490. return d