_newclient.py 60 KB

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