_http2.py 48 KB

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