Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

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