_http2.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. # -*- test-case-name: twisted.web.test.test_http2 -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. HTTP2 Implementation
  6. This is the basic server-side protocol implementation used by the Twisted
  7. Web server for HTTP2. This functionality is intended to be combined with the
  8. HTTP/1.1 and HTTP/1.0 functionality in twisted.web.http to provide complete
  9. protocol support for HTTP-type protocols.
  10. This API is currently considered private because it's in early draft form. When
  11. it has stabilised, it'll be made public.
  12. """
  13. from __future__ import absolute_import, division
  14. import io
  15. import warnings
  16. import sys
  17. from collections import deque
  18. from zope.interface import implementer
  19. import priority
  20. import h2.config
  21. import h2.connection
  22. import h2.errors
  23. import h2.events
  24. import h2.exceptions
  25. from twisted.internet.defer import Deferred
  26. from twisted.internet.interfaces import (
  27. IProtocol, ITransport, IConsumer, IPushProducer, ISSLTransport
  28. )
  29. from twisted.internet._producer_helpers import _PullToPush
  30. from twisted.internet.protocol import Protocol
  31. from twisted.logger import Logger
  32. from twisted.protocols.policies import TimeoutMixin
  33. # This API is currently considered private.
  34. __all__ = []
  35. _END_STREAM_SENTINEL = object()
  36. # Python versions 2.7.3 and older don't have a memoryview object that plays
  37. # well with the struct module, which h2 needs. On those versions, just refuse
  38. # to import.
  39. if sys.version_info < (2, 7, 4):
  40. warnings.warn(
  41. "HTTP/2 cannot be enabled because this version of Python is too "
  42. "old, and does not fully support memoryview objects.",
  43. UserWarning,
  44. stacklevel=2,
  45. )
  46. raise ImportError("HTTP/2 not supported on this Python version.")
  47. @implementer(IProtocol, IPushProducer)
  48. class H2Connection(Protocol, TimeoutMixin):
  49. """
  50. A class representing a single HTTP/2 connection.
  51. This implementation of L{IProtocol} works hand in hand with L{H2Stream}.
  52. This is because we have the requirement to register multiple producers for
  53. a single HTTP/2 connection, one for each stream. The standard Twisted
  54. interfaces don't really allow for this, so instead there's a custom
  55. interface between the two objects that allows them to work hand-in-hand here.
  56. @ivar conn: The HTTP/2 connection state machine.
  57. @type conn: L{h2.connection.H2Connection}
  58. @ivar streams: A mapping of stream IDs to L{H2Stream} objects, used to call
  59. specific methods on streams when events occur.
  60. @type streams: L{dict}, mapping L{int} stream IDs to L{H2Stream} objects.
  61. @ivar priority: A HTTP/2 priority tree used to ensure that responses are
  62. prioritised appropriately.
  63. @type priority: L{priority.PriorityTree}
  64. @ivar _consumerBlocked: A flag tracking whether or not the L{IConsumer}
  65. that is consuming this data has asked us to stop producing.
  66. @type _consumerBlocked: L{bool}
  67. @ivar _sendingDeferred: A L{Deferred} used to restart the data-sending loop
  68. when more response data has been produced. Will not be present if there
  69. is outstanding data still to send.
  70. @type _consumerBlocked: A L{twisted.internet.defer.Deferred}, or L{None}
  71. @ivar _outboundStreamQueues: A map of stream IDs to queues, used to store
  72. data blocks that are yet to be sent on the connection. These are used
  73. both to handle producers that do not respect L{IConsumer} but also to
  74. allow priority to multiplex data appropriately.
  75. @type _outboundStreamQueues: A L{dict} mapping L{int} stream IDs to
  76. L{collections.deque} queues, which contain either L{bytes} objects or
  77. C{_END_STREAM_SENTINEL}.
  78. @ivar _sender: A handle to the data-sending loop, allowing it to be
  79. terminated if needed.
  80. @type _sender: L{twisted.internet.task.LoopingCall}
  81. @ivar abortTimeout: The number of seconds to wait after we attempt to shut
  82. the transport down cleanly to give up and forcibly terminate it. This
  83. is only used when we time a connection out, to prevent errors causing
  84. the FD to get leaked. If this is L{None}, we will wait forever.
  85. @type abortTimeout: L{int}
  86. @ivar _abortingCall: The L{twisted.internet.base.DelayedCall} that will be
  87. used to forcibly close the transport if it doesn't close cleanly.
  88. @type _abortingCall: L{twisted.internet.base.DelayedCall
  89. """
  90. factory = None
  91. site = None
  92. abortTimeout = 15
  93. _log = Logger()
  94. _abortingCall = None
  95. def __init__(self, reactor=None):
  96. config = h2.config.H2Configuration(
  97. client_side=False, header_encoding=None
  98. )
  99. self.conn = h2.connection.H2Connection(config=config)
  100. self.streams = {}
  101. self.priority = priority.PriorityTree()
  102. self._consumerBlocked = None
  103. self._sendingDeferred = None
  104. self._outboundStreamQueues = {}
  105. self._streamCleanupCallbacks = {}
  106. self._stillProducing = True
  107. if reactor is None:
  108. from twisted.internet import reactor
  109. self._reactor = reactor
  110. # Start the data sending function.
  111. self._reactor.callLater(0, self._sendPrioritisedData)
  112. # Implementation of IProtocol
  113. def connectionMade(self):
  114. """
  115. Called by the reactor when a connection is received. May also be called
  116. by the L{twisted.web.http._GenericHTTPChannelProtocol} during upgrade
  117. to HTTP/2.
  118. """
  119. self.setTimeout(self.timeOut)
  120. self.conn.initiate_connection()
  121. self.transport.write(self.conn.data_to_send())
  122. def dataReceived(self, data):
  123. """
  124. Called whenever a chunk of data is received from the transport.
  125. @param data: The data received from the transport.
  126. @type data: L{bytes}
  127. """
  128. self.resetTimeout()
  129. try:
  130. events = self.conn.receive_data(data)
  131. except h2.exceptions.ProtocolError:
  132. # A remote protocol error terminates the connection.
  133. dataToSend = self.conn.data_to_send()
  134. self.transport.write(dataToSend)
  135. self.transport.loseConnection()
  136. self.connectionLost("Protocol error from peer.")
  137. return
  138. for event in events:
  139. if isinstance(event, h2.events.RequestReceived):
  140. self._requestReceived(event)
  141. elif isinstance(event, h2.events.DataReceived):
  142. self._requestDataReceived(event)
  143. elif isinstance(event, h2.events.StreamEnded):
  144. self._requestEnded(event)
  145. elif isinstance(event, h2.events.StreamReset):
  146. self._requestAborted(event)
  147. elif isinstance(event, h2.events.WindowUpdated):
  148. self._handleWindowUpdate(event)
  149. elif isinstance(event, h2.events.PriorityUpdated):
  150. self._handlePriorityUpdate(event)
  151. elif isinstance(event, h2.events.ConnectionTerminated):
  152. self.transport.loseConnection()
  153. self.connectionLost("Shutdown by remote peer")
  154. dataToSend = self.conn.data_to_send()
  155. if dataToSend:
  156. self.transport.write(dataToSend)
  157. def timeoutConnection(self):
  158. """
  159. Called when the connection has been inactive for
  160. L{self.timeOut<twisted.protocols.policies.TimeoutMixin.timeOut>}
  161. seconds. Cleanly tears the connection down, attempting to notify the
  162. peer if needed.
  163. We override this method to add two extra bits of functionality:
  164. - We want to log the timeout.
  165. - We want to send a GOAWAY frame indicating that the connection is
  166. being terminated, and whether it was clean or not. We have to do this
  167. before the connection is torn down.
  168. """
  169. self._log.info(
  170. "Timing out client {client}", client=self.transport.getPeer()
  171. )
  172. # Check whether there are open streams. If there are, we're going to
  173. # want to use the error code PROTOCOL_ERROR. If there aren't, use
  174. # NO_ERROR.
  175. if (self.conn.open_outbound_streams > 0 or
  176. self.conn.open_inbound_streams > 0):
  177. error_code = h2.errors.ErrorCodes.PROTOCOL_ERROR
  178. else:
  179. error_code = h2.errors.ErrorCodes.NO_ERROR
  180. self.conn.close_connection(error_code=error_code)
  181. self.transport.write(self.conn.data_to_send())
  182. # Don't let the client hold this connection open too long.
  183. if self.abortTimeout is not None:
  184. # We use self.callLater because that's what TimeoutMixin does, even
  185. # though we have a perfectly good reactor sitting around. See
  186. # https://twistedmatrix.com/trac/ticket/8488.
  187. self._abortingCall = self.callLater(
  188. self.abortTimeout, self.forceAbortClient
  189. )
  190. # We're done, throw the connection away.
  191. self.transport.loseConnection()
  192. def forceAbortClient(self):
  193. """
  194. Called if C{abortTimeout} seconds have passed since the timeout fired,
  195. and the connection still hasn't gone away. This can really only happen
  196. on extremely bad connections or when clients are maliciously attempting
  197. to keep connections open.
  198. """
  199. self._log.info(
  200. "Forcibly timing out client: {client}",
  201. client=self.transport.getPeer()
  202. )
  203. self.transport.abortConnection()
  204. def connectionLost(self, reason):
  205. """
  206. Called when the transport connection is lost.
  207. Informs all outstanding response handlers that the connection has been
  208. lost, and cleans up all internal state.
  209. """
  210. self._stillProducing = False
  211. self.setTimeout(None)
  212. for stream in self.streams.values():
  213. stream.connectionLost(reason)
  214. for streamID in list(self.streams.keys()):
  215. self._requestDone(streamID)
  216. # If we were going to force-close the transport, we don't have to now.
  217. if self._abortingCall is not None:
  218. self._abortingCall.cancel()
  219. self._abortingCall = None
  220. # Implementation of IPushProducer
  221. #
  222. # Here's how we handle IPushProducer. We have multiple outstanding
  223. # H2Streams. Each of these exposes an IConsumer interface to the response
  224. # handler that allows it to push data into the H2Stream. The H2Stream then
  225. # writes the data into the H2Connection object.
  226. #
  227. # The H2Connection needs to manage these writes to account for:
  228. #
  229. # - flow control
  230. # - priority
  231. #
  232. # We manage each of these in different ways.
  233. #
  234. # For flow control, we simply use the equivalent of the IPushProducer
  235. # interface. We simply tell the H2Stream: "Hey, you can't send any data
  236. # right now, sorry!". When that stream becomes unblocked, we free it up
  237. # again. This allows the H2Stream to propagate this backpressure up the
  238. # chain.
  239. #
  240. # For priority, we need to keep a backlog of data frames that we can send,
  241. # and interleave them appropriately. This backlog is most sensibly kept in
  242. # the H2Connection object itself. We keep one queue per stream, which is
  243. # where the writes go, and then we have a loop that manages popping these
  244. # streams off in priority order.
  245. #
  246. # Logically then, we go as follows:
  247. #
  248. # 1. Stream calls writeDataToStream(). This causes a DataFrame to be placed
  249. # on the queue for that stream. It also informs the priority
  250. # implementation that this stream is unblocked.
  251. # 2. The _sendPrioritisedData() function spins in a tight loop. Each
  252. # iteration it asks the priority implementation which stream should send
  253. # next, and pops a data frame off that stream's queue. If, after sending
  254. # that frame, there is no data left on that stream's queue, the function
  255. # informs the priority implementation that the stream is blocked.
  256. #
  257. # If all streams are blocked, or if there are no outstanding streams, the
  258. # _sendPrioritisedData function waits to be awoken when more data is ready
  259. # to send.
  260. #
  261. # Note that all of this only applies to *data*. Headers and other control
  262. # frames deliberately skip this processing as they are not subject to flow
  263. # control or priority constraints.
  264. def stopProducing(self):
  265. """
  266. Stop producing data.
  267. This tells the L{H2Connection} that its consumer has died, so it must
  268. stop producing data for good.
  269. """
  270. self.connectionLost("stopProducing")
  271. def pauseProducing(self):
  272. """
  273. Pause producing data.
  274. Tells the L{H2Connection} that it has produced too much data to process
  275. for the time being, and to stop until resumeProducing() is called.
  276. """
  277. self._consumerBlocked = Deferred()
  278. def resumeProducing(self):
  279. """
  280. Resume producing data.
  281. This tells the L{H2Connection} to re-add itself to the main loop and
  282. produce more data for the consumer.
  283. """
  284. if self._consumerBlocked is not None:
  285. d = self._consumerBlocked
  286. self._consumerBlocked = None
  287. d.callback(None)
  288. def _sendPrioritisedData(self, *args):
  289. """
  290. The data sending loop. This function repeatedly calls itself, either
  291. from L{Deferred}s or from
  292. L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>}
  293. This function sends data on streams according to the rules of HTTP/2
  294. priority. It ensures that the data from each stream is interleved
  295. according to the priority signalled by the client, making sure that the
  296. connection is used with maximal efficiency.
  297. This function will execute if data is available: if all data is
  298. exhausted, the function will place a deferred onto the L{H2Connection}
  299. object and wait until it is called to resume executing.
  300. """
  301. # If producing has stopped, we're done. Don't reschedule ourselves
  302. if not self._stillProducing:
  303. return
  304. stream = None
  305. while stream is None:
  306. try:
  307. stream = next(self.priority)
  308. except priority.DeadlockError:
  309. # All streams are currently blocked or not progressing. Wait
  310. # until a new one becomes available.
  311. assert self._sendingDeferred is None
  312. self._sendingDeferred = Deferred()
  313. self._sendingDeferred.addCallback(self._sendPrioritisedData)
  314. return
  315. # Wait behind the transport.
  316. if self._consumerBlocked is not None:
  317. self._consumerBlocked.addCallback(self._sendPrioritisedData)
  318. return
  319. remainingWindow = self.conn.local_flow_control_window(stream)
  320. frameData = self._outboundStreamQueues[stream].popleft()
  321. maxFrameSize = min(self.conn.max_outbound_frame_size, remainingWindow)
  322. if frameData is _END_STREAM_SENTINEL:
  323. # There's no error handling here even though this can throw
  324. # ProtocolError because we really shouldn't encounter this problem.
  325. # If we do, that's a nasty bug.
  326. self.conn.end_stream(stream)
  327. self.transport.write(self.conn.data_to_send())
  328. # Clean up the stream
  329. self._requestDone(stream)
  330. else:
  331. # Respect the max frame size.
  332. if len(frameData) > maxFrameSize:
  333. excessData = frameData[maxFrameSize:]
  334. frameData = frameData[:maxFrameSize]
  335. self._outboundStreamQueues[stream].appendleft(excessData)
  336. # There's deliberately no error handling here, because this just
  337. # absolutely should not happen.
  338. # If for whatever reason the max frame length is zero and so we
  339. # have no frame data to send, don't send any.
  340. if frameData:
  341. self.conn.send_data(stream, frameData)
  342. self.transport.write(self.conn.data_to_send())
  343. # If there's no data left, this stream is now blocked.
  344. if not self._outboundStreamQueues[stream]:
  345. self.priority.block(stream)
  346. # Also, if the stream's flow control window is exhausted, tell it
  347. # to stop.
  348. if self.remainingOutboundWindow(stream) <= 0:
  349. self.streams[stream].flowControlBlocked()
  350. self._reactor.callLater(0, self._sendPrioritisedData)
  351. # Internal functions.
  352. def _requestReceived(self, event):
  353. """
  354. Internal handler for when a request has been received.
  355. @param event: The Hyper-h2 event that encodes information about the
  356. received request.
  357. @type event: L{h2.events.RequestReceived}
  358. """
  359. stream = H2Stream(
  360. event.stream_id,
  361. self, event.headers,
  362. self.requestFactory,
  363. self.site,
  364. self.factory
  365. )
  366. self.streams[event.stream_id] = stream
  367. self._streamCleanupCallbacks[event.stream_id] = Deferred()
  368. self._outboundStreamQueues[event.stream_id] = deque()
  369. # Add the stream to the priority tree but immediately block it.
  370. try:
  371. self.priority.insert_stream(event.stream_id)
  372. except priority.DuplicateStreamError:
  373. # Stream already in the tree. This can happen if we received a
  374. # PRIORITY frame before a HEADERS frame. Just move on: we set the
  375. # stream up properly in _handlePriorityUpdate.
  376. pass
  377. else:
  378. self.priority.block(event.stream_id)
  379. def _requestDataReceived(self, event):
  380. """
  381. Internal handler for when a chunk of data is received for a given
  382. request.
  383. @param event: The Hyper-h2 event that encodes information about the
  384. received data.
  385. @type event: L{h2.events.DataReceived}
  386. """
  387. stream = self.streams[event.stream_id]
  388. stream.receiveDataChunk(event.data, event.flow_controlled_length)
  389. def _requestEnded(self, event):
  390. """
  391. Internal handler for when a request is complete, and we expect no
  392. further data for that request.
  393. @param event: The Hyper-h2 event that encodes information about the
  394. completed stream.
  395. @type event: L{h2.events.StreamEnded}
  396. """
  397. stream = self.streams[event.stream_id]
  398. stream.requestComplete()
  399. def _requestAborted(self, event):
  400. """
  401. Internal handler for when a request is aborted by a remote peer.
  402. @param event: The Hyper-h2 event that encodes information about the
  403. reset stream.
  404. @type event: L{h2.events.StreamReset}
  405. """
  406. stream = self.streams[event.stream_id]
  407. stream.connectionLost("Stream reset")
  408. self._requestDone(event.stream_id)
  409. def _handlePriorityUpdate(self, event):
  410. """
  411. Internal handler for when a stream priority is updated.
  412. @param event: The Hyper-h2 event that encodes information about the
  413. stream reprioritization.
  414. @type event: L{h2.events.PriorityUpdated}
  415. """
  416. try:
  417. self.priority.reprioritize(
  418. stream_id=event.stream_id,
  419. depends_on=event.depends_on or None,
  420. weight=event.weight,
  421. exclusive=event.exclusive,
  422. )
  423. except priority.MissingStreamError:
  424. # A PRIORITY frame arrived before the HEADERS frame that would
  425. # trigger us to insert the stream into the tree. That's fine: we
  426. # can create the stream here and mark it as blocked.
  427. self.priority.insert_stream(
  428. stream_id=event.stream_id,
  429. depends_on=event.depends_on or None,
  430. weight=event.weight,
  431. exclusive=event.exclusive,
  432. )
  433. self.priority.block(event.stream_id)
  434. def writeHeaders(self, version, code, reason, headers, streamID):
  435. """
  436. Called by L{twisted.web.http.Request} objects to write a complete set
  437. of HTTP headers to a stream.
  438. @param version: The HTTP version in use. Unused in HTTP/2.
  439. @type version: L{bytes}
  440. @param code: The HTTP status code to write.
  441. @type code: L{bytes}
  442. @param reason: The HTTP reason phrase to write. Unused in HTTP/2.
  443. @type reason: L{bytes}
  444. @param headers: The headers to write to the stream.
  445. @type headers: L{twisted.web.http_headers.Headers}
  446. @param streamID: The ID of the stream to write the headers to.
  447. @type streamID: L{int}
  448. """
  449. headers.insert(0, (b':status', code))
  450. try:
  451. self.conn.send_headers(streamID, headers)
  452. except h2.exceptions.StreamClosedError:
  453. # Stream was closed by the client at some point. We need to not
  454. # explode here: just swallow the error. That's what write() does
  455. # when a connection is lost, so that's what we do too.
  456. return
  457. else:
  458. self.transport.write(self.conn.data_to_send())
  459. def writeDataToStream(self, streamID, data):
  460. """
  461. May be called by L{H2Stream} objects to write response data to a given
  462. stream. Writes a single data frame.
  463. @param streamID: The ID of the stream to write the data to.
  464. @type streamID: L{int}
  465. @param data: The data chunk to write to the stream.
  466. @type data: L{bytes}
  467. """
  468. self._outboundStreamQueues[streamID].append(data)
  469. # There's obviously no point unblocking this stream and the sending
  470. # loop if the data can't actually be sent, so confirm that there's
  471. # some room to send data.
  472. if self.conn.local_flow_control_window(streamID) > 0:
  473. self.priority.unblock(streamID)
  474. if self._sendingDeferred is not None:
  475. d = self._sendingDeferred
  476. self._sendingDeferred = None
  477. d.callback(streamID)
  478. if self.remainingOutboundWindow(streamID) <= 0:
  479. self.streams[streamID].flowControlBlocked()
  480. def endRequest(self, streamID):
  481. """
  482. Called by L{H2Stream} objects to signal completion of a response.
  483. @param streamID: The ID of the stream to write the data to.
  484. @type streamID: L{int}
  485. """
  486. self._outboundStreamQueues[streamID].append(_END_STREAM_SENTINEL)
  487. self.priority.unblock(streamID)
  488. if self._sendingDeferred is not None:
  489. d = self._sendingDeferred
  490. self._sendingDeferred = None
  491. d.callback(streamID)
  492. def abortRequest(self, streamID):
  493. """
  494. Called by L{H2Stream} objects to request early termination of a stream.
  495. This emits a RstStream frame and then removes all stream state.
  496. @param streamID: The ID of the stream to write the data to.
  497. @type streamID: L{int}
  498. """
  499. self.conn.reset_stream(streamID)
  500. self.transport.write(self.conn.data_to_send())
  501. self._requestDone(streamID)
  502. def _requestDone(self, streamID):
  503. """
  504. Called internally by the data sending loop to clean up state that was
  505. being used for the stream. Called when the stream is complete.
  506. @param streamID: The ID of the stream to clean up state for.
  507. @type streamID: L{int}
  508. """
  509. del self._outboundStreamQueues[streamID]
  510. self.priority.remove_stream(streamID)
  511. del self.streams[streamID]
  512. cleanupCallback = self._streamCleanupCallbacks.pop(streamID)
  513. cleanupCallback.callback(streamID)
  514. def remainingOutboundWindow(self, streamID):
  515. """
  516. Called to determine how much room is left in the send window for a
  517. given stream. Allows us to handle blocking and unblocking producers.
  518. @param streamID: The ID of the stream whose flow control window we'll
  519. check.
  520. @type streamID: L{int}
  521. @return: The amount of room remaining in the send window for the given
  522. stream, including the data queued to be sent.
  523. @rtype: L{int}
  524. """
  525. # TODO: This involves a fair bit of looping and computation for
  526. # something that is called a lot. Consider caching values somewhere.
  527. windowSize = self.conn.local_flow_control_window(streamID)
  528. sendQueue = self._outboundStreamQueues[streamID]
  529. alreadyConsumed = sum(
  530. len(chunk) for chunk in sendQueue
  531. if chunk is not _END_STREAM_SENTINEL
  532. )
  533. return windowSize - alreadyConsumed
  534. def _handleWindowUpdate(self, event):
  535. """
  536. Manage flow control windows.
  537. Streams that are blocked on flow control will register themselves with
  538. the connection. This will fire deferreds that wake those streams up and
  539. allow them to continue processing.
  540. @param event: The Hyper-h2 event that encodes information about the
  541. flow control window change.
  542. @type event: L{h2.events.WindowUpdated}
  543. """
  544. streamID = event.stream_id
  545. if streamID:
  546. if not self._streamIsActive(streamID):
  547. # We may have already cleaned up our stream state, making this
  548. # a late WINDOW_UPDATE frame. That's fine: the update is
  549. # unnecessary but benign. We'll ignore it.
  550. return
  551. # If we haven't got any data to send, don't unblock the stream. If
  552. # we do, we'll eventually get an exception inside the
  553. # _sendPrioritisedData loop some time later.
  554. if self._outboundStreamQueues.get(streamID):
  555. self.priority.unblock(streamID)
  556. self.streams[streamID].windowUpdated()
  557. else:
  558. # Update strictly applies to all streams.
  559. for stream in self.streams.values():
  560. stream.windowUpdated()
  561. # If we still have data to send for this stream, unblock it.
  562. if self._outboundStreamQueues.get(stream.streamID):
  563. self.priority.unblock(stream.streamID)
  564. def getPeer(self):
  565. """
  566. Get the remote address of this connection.
  567. Treat this method with caution. It is the unfortunate result of the
  568. CGI and Jabber standards, but should not be considered reliable for
  569. the usual host of reasons; port forwarding, proxying, firewalls, IP
  570. masquerading, etc.
  571. @return: An L{IAddress} provider.
  572. """
  573. return self.transport.getPeer()
  574. def getHost(self):
  575. """
  576. Similar to getPeer, but returns an address describing this side of the
  577. connection.
  578. @return: An L{IAddress} provider.
  579. """
  580. return self.transport.getHost()
  581. def openStreamWindow(self, streamID, increment):
  582. """
  583. Open the stream window by a given increment.
  584. @param streamID: The ID of the stream whose window needs to be opened.
  585. @type streamID: L{int}
  586. @param increment: The amount by which the stream window must be
  587. incremented.
  588. @type increment: L{int}
  589. """
  590. self.conn.acknowledge_received_data(increment, streamID)
  591. data = self.conn.data_to_send()
  592. if data:
  593. self.transport.write(data)
  594. def _isSecure(self):
  595. """
  596. Returns L{True} if this channel is using a secure transport.
  597. @returns: L{True} if this channel is secure.
  598. @rtype: L{bool}
  599. """
  600. # A channel is secure if its transport is ISSLTransport.
  601. return ISSLTransport(self.transport, None) is not None
  602. def _send100Continue(self, streamID):
  603. """
  604. Sends a 100 Continue response, used to signal to clients that further
  605. processing will be performed.
  606. @param streamID: The ID of the stream that needs the 100 Continue
  607. response
  608. @type streamID: L{int}
  609. """
  610. headers = [(b':status', b'100')]
  611. self.conn.send_headers(headers=headers, stream_id=streamID)
  612. self.transport.write(self.conn.data_to_send())
  613. def _respondToBadRequestAndDisconnect(self, streamID):
  614. """
  615. This is a quick and dirty way of responding to bad requests.
  616. As described by HTTP standard we should be patient and accept the
  617. whole request from the client before sending a polite bad request
  618. response, even in the case when clients send tons of data.
  619. Unlike in the HTTP/1.1 case, this does not actually disconnect the
  620. underlying transport: there's no need. This instead just sends a 400
  621. response and terminates the stream.
  622. @param streamID: The ID of the stream that needs the 100 Continue
  623. response
  624. @type streamID: L{int}
  625. """
  626. headers = [(b':status', b'400')]
  627. self.conn.send_headers(
  628. headers=headers,
  629. stream_id=streamID,
  630. end_stream=True
  631. )
  632. self.transport.write(self.conn.data_to_send())
  633. stream = self.streams[streamID]
  634. stream.connectionLost("Stream reset")
  635. self._requestDone(streamID)
  636. def _streamIsActive(self, streamID):
  637. """
  638. Checks whether Twisted has still got state for a given stream and so
  639. can process events for that stream.
  640. @param streamID: The ID of the stream that needs processing.
  641. @type streamID: L{int}
  642. @return: Whether the stream still has state allocated.
  643. @rtype: L{bool}
  644. """
  645. return streamID in self.streams
  646. @implementer(ITransport, IConsumer, IPushProducer)
  647. class H2Stream(object):
  648. """
  649. A class representing a single HTTP/2 stream.
  650. This class works hand-in-hand with L{H2Connection}. It acts to provide an
  651. implementation of L{ITransport}, L{IConsumer}, and L{IProducer} that work
  652. for a single HTTP/2 connection, while tightly cleaving to the interface
  653. provided by those interfaces. It does this by having a tight coupling to
  654. L{H2Connection}, which allows associating many of the functions of
  655. L{ITransport}, L{IConsumer}, and L{IProducer} to objects on a
  656. stream-specific level.
  657. @ivar streamID: The numerical stream ID that this object corresponds to.
  658. @type streamID: L{int}
  659. @ivar producing: Whether this stream is currently allowed to produce data
  660. to its consumer.
  661. @type producing: L{bool}
  662. @ivar command: The HTTP verb used on the request.
  663. @type command: L{unicode}
  664. @ivar path: The HTTP path used on the request.
  665. @type path: L{unicode}
  666. @ivar producer: The object producing the response, if any.
  667. @type producer: L{IProducer}
  668. @ivar site: The L{twisted.web.server.Site} object this stream belongs to,
  669. if any.
  670. @type site: L{twisted.web.server.Site}
  671. @ivar factory: The L{twisted.web.http.HTTPFactory} object that constructed
  672. this stream's parent connection.
  673. @type factory: L{twisted.web.http.HTTPFactory}
  674. @ivar _producerProducing: Whether the producer stored in producer is
  675. currently producing data.
  676. @type _producerProducing: L{bool}
  677. @ivar _inboundDataBuffer: Any data that has been received from the network
  678. but has not yet been received by the consumer.
  679. @type _inboundDataBuffer: A L{collections.deque} containing L{bytes}
  680. @ivar _conn: A reference to the connection this stream belongs to.
  681. @type _conn: L{H2Connection}
  682. @ivar _request: A request object that this stream corresponds to.
  683. @type _request: L{twisted.web.iweb.IRequest}
  684. @ivar _buffer: A buffer containing data produced by the producer that could
  685. not be sent on the network at this time.
  686. @type _buffer: L{io.BytesIO}
  687. """
  688. # We need a transport property for t.w.h.Request, but HTTP/2 doesn't want
  689. # to expose it. So we just set it to None.
  690. transport = None
  691. def __init__(self, streamID, connection, headers,
  692. requestFactory, site, factory):
  693. """
  694. Initialize this HTTP/2 stream.
  695. @param streamID: The numerical stream ID that this object corresponds
  696. to.
  697. @type streamID: L{int}
  698. @param connection: The HTTP/2 connection this stream belongs to.
  699. @type connection: L{H2Connection}
  700. @param headers: The HTTP/2 request headers.
  701. @type headers: A L{list} of L{tuple}s of header name and header value,
  702. both as L{bytes}.
  703. @param requestFactory: A function that builds appropriate request
  704. request objects.
  705. @type requestFactory: A callable that returns a
  706. L{twisted.web.iweb.IRequest}.
  707. @param site: The L{twisted.web.server.Site} object this stream belongs
  708. to, if any.
  709. @type site: L{twisted.web.server.Site}
  710. @param factory: The L{twisted.web.http.HTTPFactory} object that
  711. constructed this stream's parent connection.
  712. @type factory: L{twisted.web.http.HTTPFactory}
  713. """
  714. self.streamID = streamID
  715. self.site = site
  716. self.factory = factory
  717. self.producing = True
  718. self.command = None
  719. self.path = None
  720. self.producer = None
  721. self._producerProducing = False
  722. self._hasStreamingProducer = None
  723. self._inboundDataBuffer = deque()
  724. self._conn = connection
  725. self._request = requestFactory(self, queued=False)
  726. self._buffer = io.BytesIO()
  727. self._convertHeaders(headers)
  728. def _convertHeaders(self, headers):
  729. """
  730. This method converts the HTTP/2 header set into something that looks
  731. like HTTP/1.1. In particular, it strips the 'special' headers and adds
  732. a Host: header.
  733. @param headers: The HTTP/2 header set.
  734. @type headers: A L{list} of L{tuple}s of header name and header value,
  735. both as L{bytes}.
  736. """
  737. gotLength = False
  738. for header in headers:
  739. if not header[0].startswith(b':'):
  740. gotLength = (
  741. _addHeaderToRequest(self._request, header) or gotLength
  742. )
  743. elif header[0] == b':method':
  744. self.command = header[1]
  745. elif header[0] == b':path':
  746. self.path = header[1]
  747. elif header[0] == b':authority':
  748. # This is essentially the Host: header from HTTP/1.1
  749. _addHeaderToRequest(self._request, (b'host', header[1]))
  750. if not gotLength:
  751. if self.command in (b'GET', b'HEAD'):
  752. self._request.gotLength(0)
  753. else:
  754. self._request.gotLength(None)
  755. self._request.parseCookies()
  756. expectContinue = self._request.requestHeaders.getRawHeaders(b'expect')
  757. if expectContinue and expectContinue[0].lower() == b'100-continue':
  758. self._send100Continue()
  759. # Methods called by the H2Connection
  760. def receiveDataChunk(self, data, flowControlledLength):
  761. """
  762. Called when the connection has received a chunk of data from the
  763. underlying transport. If the stream has been registered with a
  764. consumer, and is currently able to push data, immediately passes it
  765. through. Otherwise, buffers the chunk until we can start producing.
  766. @param data: The chunk of data that was received.
  767. @type data: L{bytes}
  768. @param flowControlledLength: The total flow controlled length of this
  769. chunk, which is used when we want to re-open the window. May be
  770. different to C{len(data)}.
  771. @type flowControlledLength: L{int}
  772. """
  773. if not self.producing:
  774. # Buffer data.
  775. self._inboundDataBuffer.append((data, flowControlledLength))
  776. else:
  777. self._request.handleContentChunk(data)
  778. self._conn.openStreamWindow(self.streamID, flowControlledLength)
  779. def requestComplete(self):
  780. """
  781. Called by the L{H2Connection} when the all data for a request has been
  782. received. Currently, with the legacy L{twisted.web.http.Request}
  783. object, just calls requestReceived unless the producer wants us to be
  784. quiet.
  785. """
  786. if self.producing:
  787. self._request.requestReceived(self.command, self.path, b'HTTP/2')
  788. else:
  789. self._inboundDataBuffer.append((_END_STREAM_SENTINEL, None))
  790. def connectionLost(self, reason):
  791. """
  792. Called by the L{H2Connection} when a connection is lost or a stream is
  793. reset.
  794. @param reason: The reason the connection was lost.
  795. @type reason: L{str}
  796. """
  797. self._request.connectionLost(reason)
  798. def windowUpdated(self):
  799. """
  800. Called by the L{H2Connection} when this stream's flow control window
  801. has been opened.
  802. """
  803. # If we don't have a producer, we have no-one to tell.
  804. if not self.producer:
  805. return
  806. # If we're not blocked on flow control, we don't care.
  807. if self._producerProducing:
  808. return
  809. # We check whether the stream's flow control window is actually above
  810. # 0, and then, if a producer is registered and we still have space in
  811. # the window, we unblock it.
  812. remainingWindow = self._conn.remainingOutboundWindow(self.streamID)
  813. if not remainingWindow > 0:
  814. return
  815. # We have a producer and space in the window, so that producer can
  816. # start producing again!
  817. self._producerProducing = True
  818. self.producer.resumeProducing()
  819. def flowControlBlocked(self):
  820. """
  821. Called by the L{H2Connection} when this stream's flow control window
  822. has been exhausted.
  823. """
  824. if not self.producer:
  825. return
  826. if self._producerProducing:
  827. self.producer.pauseProducing()
  828. self._producerProducing = False
  829. # Methods called by the consumer (usually an IRequest).
  830. def writeHeaders(self, version, code, reason, headers):
  831. """
  832. Called by the consumer to write headers to the stream.
  833. @param version: The HTTP version.
  834. @type version: L{bytes}
  835. @param code: The status code.
  836. @type code: L{int}
  837. @param reason: The reason phrase. Ignored in HTTP/2.
  838. @type reason: L{bytes}
  839. @param headers: The HTTP response headers.
  840. @type: Any iterable of two-tuples of L{bytes}, representing header
  841. names and header values.
  842. """
  843. self._conn.writeHeaders(version, code, reason, headers, self.streamID)
  844. def requestDone(self, request):
  845. """
  846. Called by a consumer to clean up whatever permanent state is in use.
  847. @param request: The request calling the method.
  848. @type request: L{twisted.web.iweb.IRequest}
  849. """
  850. self._conn.endRequest(self.streamID)
  851. def _send100Continue(self):
  852. """
  853. Sends a 100 Continue response, used to signal to clients that further
  854. processing will be performed.
  855. """
  856. self._conn._send100Continue(self.streamID)
  857. def _respondToBadRequestAndDisconnect(self):
  858. """
  859. This is a quick and dirty way of responding to bad requests.
  860. As described by HTTP standard we should be patient and accept the
  861. whole request from the client before sending a polite bad request
  862. response, even in the case when clients send tons of data.
  863. Unlike in the HTTP/1.1 case, this does not actually disconnect the
  864. underlying transport: there's no need. This instead just sends a 400
  865. response and terminates the stream.
  866. """
  867. self._conn._respondToBadRequestAndDisconnect(self.streamID)
  868. # Implementation: ITransport
  869. def write(self, data):
  870. """
  871. Write a single chunk of data into a data frame.
  872. @param data: The data chunk to send.
  873. @type data: L{bytes}
  874. """
  875. self._conn.writeDataToStream(self.streamID, data)
  876. return
  877. def writeSequence(self, iovec):
  878. """
  879. Write a sequence of chunks of data into data frames.
  880. @param iovec: A sequence of chunks to send.
  881. @type iovec: An iterable of L{bytes} chunks.
  882. """
  883. for chunk in iovec:
  884. self.write(chunk)
  885. def loseConnection(self):
  886. """
  887. Close the connection after writing all pending data.
  888. """
  889. self._conn.endRequest(self.streamID)
  890. def abortConnection(self):
  891. """
  892. Forcefully abort the connection by sending a RstStream frame.
  893. """
  894. self._conn.abortRequest(self.streamID)
  895. def getPeer(self):
  896. """
  897. Get information about the peer.
  898. """
  899. return self._conn.getPeer()
  900. def getHost(self):
  901. """
  902. Similar to getPeer, but for this side of the connection.
  903. """
  904. return self._conn.getHost()
  905. def isSecure(self):
  906. """
  907. Returns L{True} if this channel is using a secure transport.
  908. @returns: L{True} if this channel is secure.
  909. @rtype: L{bool}
  910. """
  911. return self._conn._isSecure()
  912. # Implementation: IConsumer
  913. def registerProducer(self, producer, streaming):
  914. """
  915. Register to receive data from a producer.
  916. This sets self to be a consumer for a producer. When this object runs
  917. out of data (as when a send(2) call on a socket succeeds in moving the
  918. last data from a userspace buffer into a kernelspace buffer), it will
  919. ask the producer to resumeProducing().
  920. For L{IPullProducer} providers, C{resumeProducing} will be called once
  921. each time data is required.
  922. For L{IPushProducer} providers, C{pauseProducing} will be called
  923. whenever the write buffer fills up and C{resumeProducing} will only be
  924. called when it empties.
  925. @param producer: The producer to register.
  926. @type producer: L{IProducer} provider
  927. @param streaming: L{True} if C{producer} provides L{IPushProducer},
  928. L{False} if C{producer} provides L{IPullProducer}.
  929. @type streaming: L{bool}
  930. @raise RuntimeError: If a producer is already registered.
  931. @return: L{None}
  932. """
  933. if self.producer:
  934. raise ValueError(
  935. "registering producer %s before previous one (%s) was "
  936. "unregistered" % (producer, self.producer))
  937. if not streaming:
  938. self.hasStreamingProducer = False
  939. producer = _PullToPush(producer, self)
  940. producer.startStreaming()
  941. else:
  942. self.hasStreamingProducer = True
  943. self.producer = producer
  944. self._producerProducing = True
  945. def unregisterProducer(self):
  946. """
  947. @see: L{IConsumer.unregisterProducer}
  948. """
  949. # When the producer is unregistered, we're done.
  950. if self.producer is not None and not self.hasStreamingProducer:
  951. self.producer.stopStreaming()
  952. self._producerProducing = False
  953. self.producer = None
  954. self.hasStreamingProducer = None
  955. # Implementation: IPushProducer
  956. def stopProducing(self):
  957. """
  958. @see: L{IProducer.stopProducing}
  959. """
  960. self.producing = False
  961. self.abortConnection()
  962. def pauseProducing(self):
  963. """
  964. @see: L{IPushProducer.pauseProducing}
  965. """
  966. self.producing = False
  967. def resumeProducing(self):
  968. """
  969. @see: L{IPushProducer.resumeProducing}
  970. """
  971. self.producing = True
  972. consumedLength = 0
  973. while self.producing and self._inboundDataBuffer:
  974. # Allow for pauseProducing to be called in response to a call to
  975. # resumeProducing.
  976. chunk, flowControlledLength = self._inboundDataBuffer.popleft()
  977. if chunk is _END_STREAM_SENTINEL:
  978. self.requestComplete()
  979. else:
  980. consumedLength += flowControlledLength
  981. self._request.handleContentChunk(chunk)
  982. self._conn.openStreamWindow(self.streamID, consumedLength)
  983. def _addHeaderToRequest(request, header):
  984. """
  985. Add a header tuple to a request header object.
  986. @param request: The request to add the header tuple to.
  987. @type request: L{twisted.web.http.Request}
  988. @param header: The header tuple to add to the request.
  989. @type header: A L{tuple} with two elements, the header name and header
  990. value, both as L{bytes}.
  991. @return: If the header being added was the C{Content-Length} header.
  992. @rtype: L{bool}
  993. """
  994. requestHeaders = request.requestHeaders
  995. name, value = header
  996. values = requestHeaders.getRawHeaders(name)
  997. if values is not None:
  998. values.append(value)
  999. else:
  1000. requestHeaders.setRawHeaders(name, [value])
  1001. if name == b'content-length':
  1002. request.gotLength(int(value))
  1003. return True
  1004. return False