_newclient.py 64 KB

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