You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_newclient.py 62KB

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