connection.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074
  1. # -*- coding: utf-8 -*-
  2. """
  3. h2/connection
  4. ~~~~~~~~~~~~~
  5. An implementation of a HTTP/2 connection.
  6. """
  7. import base64
  8. from enum import Enum, IntEnum
  9. from hyperframe.exceptions import InvalidPaddingError
  10. from hyperframe.frame import (
  11. GoAwayFrame, WindowUpdateFrame, HeadersFrame, DataFrame, PingFrame,
  12. PushPromiseFrame, SettingsFrame, RstStreamFrame, PriorityFrame,
  13. ContinuationFrame, AltSvcFrame
  14. )
  15. from hpack.hpack import Encoder, Decoder
  16. from hpack.exceptions import HPACKError
  17. from .config import H2Configuration
  18. from .errors import ErrorCodes, _error_code_from_int
  19. from .events import (
  20. WindowUpdated, RemoteSettingsChanged, PingAcknowledged,
  21. SettingsAcknowledged, ConnectionTerminated, PriorityUpdated,
  22. AlternativeServiceAvailable,
  23. )
  24. from .exceptions import (
  25. ProtocolError, NoSuchStreamError, FlowControlError, FrameTooLargeError,
  26. TooManyStreamsError, StreamClosedError, StreamIDTooLowError,
  27. NoAvailableStreamIDError, RFC1122Error, DenialOfServiceError
  28. )
  29. from .frame_buffer import FrameBuffer
  30. from .settings import Settings, SettingCodes
  31. from .stream import H2Stream, StreamClosedBy
  32. from .utilities import guard_increment_window
  33. from .windows import WindowManager
  34. try:
  35. from hpack.exceptions import OversizedHeaderListError
  36. except ImportError: # Platform-specific: HPACK < 2.3.0
  37. # If the exception doesn't exist, it cannot possibly be thrown. Define a
  38. # placeholder name, but don't otherwise worry about it.
  39. class OversizedHeaderListError(Exception):
  40. pass
  41. try:
  42. from hyperframe.frame import ExtensionFrame
  43. except ImportError: # Platform-specific: Hyperframe < 5.0.0
  44. # If the frame doesn't exist, that's just fine: we'll define it ourselves
  45. # and the method will just never be called.
  46. class ExtensionFrame(object):
  47. pass
  48. class ConnectionState(Enum):
  49. IDLE = 0
  50. CLIENT_OPEN = 1
  51. SERVER_OPEN = 2
  52. CLOSED = 3
  53. class ConnectionInputs(Enum):
  54. SEND_HEADERS = 0
  55. SEND_PUSH_PROMISE = 1
  56. SEND_DATA = 2
  57. SEND_GOAWAY = 3
  58. SEND_WINDOW_UPDATE = 4
  59. SEND_PING = 5
  60. SEND_SETTINGS = 6
  61. SEND_RST_STREAM = 7
  62. SEND_PRIORITY = 8
  63. RECV_HEADERS = 9
  64. RECV_PUSH_PROMISE = 10
  65. RECV_DATA = 11
  66. RECV_GOAWAY = 12
  67. RECV_WINDOW_UPDATE = 13
  68. RECV_PING = 14
  69. RECV_SETTINGS = 15
  70. RECV_RST_STREAM = 16
  71. RECV_PRIORITY = 17
  72. SEND_ALTERNATIVE_SERVICE = 18 # Added in 2.3.0
  73. RECV_ALTERNATIVE_SERVICE = 19 # Added in 2.3.0
  74. class AllowedStreamIDs(IntEnum):
  75. EVEN = 0
  76. ODD = 1
  77. class H2ConnectionStateMachine(object):
  78. """
  79. A single HTTP/2 connection state machine.
  80. This state machine, while defined in its own class, is logically part of
  81. the H2Connection class also defined in this file. The state machine itself
  82. maintains very little state directly, instead focusing entirely on managing
  83. state transitions.
  84. """
  85. # For the purposes of this state machine we treat HEADERS and their
  86. # associated CONTINUATION frames as a single jumbo frame. The protocol
  87. # allows/requires this by preventing other frames from being interleved in
  88. # between HEADERS/CONTINUATION frames.
  89. #
  90. # The _transitions dictionary contains a mapping of tuples of
  91. # (state, input) to tuples of (side_effect_function, end_state). This map
  92. # contains all allowed transitions: anything not in this map is invalid
  93. # and immediately causes a transition to ``closed``.
  94. _transitions = {
  95. # State: idle
  96. (ConnectionState.IDLE, ConnectionInputs.SEND_HEADERS):
  97. (None, ConnectionState.CLIENT_OPEN),
  98. (ConnectionState.IDLE, ConnectionInputs.RECV_HEADERS):
  99. (None, ConnectionState.SERVER_OPEN),
  100. (ConnectionState.IDLE, ConnectionInputs.SEND_SETTINGS):
  101. (None, ConnectionState.IDLE),
  102. (ConnectionState.IDLE, ConnectionInputs.RECV_SETTINGS):
  103. (None, ConnectionState.IDLE),
  104. (ConnectionState.IDLE, ConnectionInputs.SEND_WINDOW_UPDATE):
  105. (None, ConnectionState.IDLE),
  106. (ConnectionState.IDLE, ConnectionInputs.RECV_WINDOW_UPDATE):
  107. (None, ConnectionState.IDLE),
  108. (ConnectionState.IDLE, ConnectionInputs.SEND_PING):
  109. (None, ConnectionState.IDLE),
  110. (ConnectionState.IDLE, ConnectionInputs.RECV_PING):
  111. (None, ConnectionState.IDLE),
  112. (ConnectionState.IDLE, ConnectionInputs.SEND_GOAWAY):
  113. (None, ConnectionState.CLOSED),
  114. (ConnectionState.IDLE, ConnectionInputs.RECV_GOAWAY):
  115. (None, ConnectionState.CLOSED),
  116. (ConnectionState.IDLE, ConnectionInputs.SEND_PRIORITY):
  117. (None, ConnectionState.IDLE),
  118. (ConnectionState.IDLE, ConnectionInputs.RECV_PRIORITY):
  119. (None, ConnectionState.IDLE),
  120. (ConnectionState.IDLE, ConnectionInputs.SEND_ALTERNATIVE_SERVICE):
  121. (None, ConnectionState.SERVER_OPEN),
  122. (ConnectionState.IDLE, ConnectionInputs.RECV_ALTERNATIVE_SERVICE):
  123. (None, ConnectionState.CLIENT_OPEN),
  124. # State: open, client side.
  125. (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_HEADERS):
  126. (None, ConnectionState.CLIENT_OPEN),
  127. (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_DATA):
  128. (None, ConnectionState.CLIENT_OPEN),
  129. (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_GOAWAY):
  130. (None, ConnectionState.CLOSED),
  131. (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_WINDOW_UPDATE):
  132. (None, ConnectionState.CLIENT_OPEN),
  133. (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_PING):
  134. (None, ConnectionState.CLIENT_OPEN),
  135. (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_SETTINGS):
  136. (None, ConnectionState.CLIENT_OPEN),
  137. (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_PRIORITY):
  138. (None, ConnectionState.CLIENT_OPEN),
  139. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_HEADERS):
  140. (None, ConnectionState.CLIENT_OPEN),
  141. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PUSH_PROMISE):
  142. (None, ConnectionState.CLIENT_OPEN),
  143. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_DATA):
  144. (None, ConnectionState.CLIENT_OPEN),
  145. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_GOAWAY):
  146. (None, ConnectionState.CLOSED),
  147. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_WINDOW_UPDATE):
  148. (None, ConnectionState.CLIENT_OPEN),
  149. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PING):
  150. (None, ConnectionState.CLIENT_OPEN),
  151. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_SETTINGS):
  152. (None, ConnectionState.CLIENT_OPEN),
  153. (ConnectionState.CLIENT_OPEN, ConnectionInputs.SEND_RST_STREAM):
  154. (None, ConnectionState.CLIENT_OPEN),
  155. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_RST_STREAM):
  156. (None, ConnectionState.CLIENT_OPEN),
  157. (ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PRIORITY):
  158. (None, ConnectionState.CLIENT_OPEN),
  159. (ConnectionState.CLIENT_OPEN,
  160. ConnectionInputs.RECV_ALTERNATIVE_SERVICE):
  161. (None, ConnectionState.CLIENT_OPEN),
  162. # State: open, server side.
  163. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_HEADERS):
  164. (None, ConnectionState.SERVER_OPEN),
  165. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PUSH_PROMISE):
  166. (None, ConnectionState.SERVER_OPEN),
  167. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_DATA):
  168. (None, ConnectionState.SERVER_OPEN),
  169. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_GOAWAY):
  170. (None, ConnectionState.CLOSED),
  171. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_WINDOW_UPDATE):
  172. (None, ConnectionState.SERVER_OPEN),
  173. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PING):
  174. (None, ConnectionState.SERVER_OPEN),
  175. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_SETTINGS):
  176. (None, ConnectionState.SERVER_OPEN),
  177. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_PRIORITY):
  178. (None, ConnectionState.SERVER_OPEN),
  179. (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_HEADERS):
  180. (None, ConnectionState.SERVER_OPEN),
  181. (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_DATA):
  182. (None, ConnectionState.SERVER_OPEN),
  183. (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_GOAWAY):
  184. (None, ConnectionState.CLOSED),
  185. (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_WINDOW_UPDATE):
  186. (None, ConnectionState.SERVER_OPEN),
  187. (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_PING):
  188. (None, ConnectionState.SERVER_OPEN),
  189. (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_SETTINGS):
  190. (None, ConnectionState.SERVER_OPEN),
  191. (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_PRIORITY):
  192. (None, ConnectionState.SERVER_OPEN),
  193. (ConnectionState.SERVER_OPEN, ConnectionInputs.SEND_RST_STREAM):
  194. (None, ConnectionState.SERVER_OPEN),
  195. (ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_RST_STREAM):
  196. (None, ConnectionState.SERVER_OPEN),
  197. (ConnectionState.SERVER_OPEN,
  198. ConnectionInputs.SEND_ALTERNATIVE_SERVICE):
  199. (None, ConnectionState.SERVER_OPEN),
  200. (ConnectionState.SERVER_OPEN,
  201. ConnectionInputs.RECV_ALTERNATIVE_SERVICE):
  202. (None, ConnectionState.SERVER_OPEN),
  203. # State: closed
  204. (ConnectionState.CLOSED, ConnectionInputs.SEND_GOAWAY):
  205. (None, ConnectionState.CLOSED),
  206. (ConnectionState.CLOSED, ConnectionInputs.RECV_GOAWAY):
  207. (None, ConnectionState.CLOSED),
  208. }
  209. def __init__(self):
  210. self.state = ConnectionState.IDLE
  211. def process_input(self, input_):
  212. """
  213. Process a specific input in the state machine.
  214. """
  215. if not isinstance(input_, ConnectionInputs):
  216. raise ValueError("Input must be an instance of ConnectionInputs")
  217. try:
  218. func, target_state = self._transitions[(self.state, input_)]
  219. except KeyError:
  220. old_state = self.state
  221. self.state = ConnectionState.CLOSED
  222. raise ProtocolError(
  223. "Invalid input %s in state %s" % (input_, old_state)
  224. )
  225. else:
  226. self.state = target_state
  227. if func is not None: # pragma: no cover
  228. return func()
  229. return []
  230. class H2Connection(object):
  231. """
  232. A low-level HTTP/2 connection object. This handles building and receiving
  233. frames and maintains both connection and per-stream state for all streams
  234. on this connection.
  235. This wraps a HTTP/2 Connection state machine implementation, ensuring that
  236. frames can only be sent/received when the connection is in a valid state.
  237. It also builds stream state machines on demand to ensure that the
  238. constraints of those state machines are met as well. Attempts to create
  239. frames that cannot be sent will raise a ``ProtocolError``.
  240. .. versionchanged:: 2.3.0
  241. Added the ``header_encoding`` keyword argument.
  242. .. versionchanged:: 2.5.0
  243. Added the ``config`` keyword argument. Deprecated the ``client_side``
  244. and ``header_encoding`` parameters.
  245. :param client_side: Whether this object is to be used on the client side of
  246. a connection, or on the server side. Affects the logic used by the
  247. state machine, the default settings values, the allowable stream IDs,
  248. and several other properties. Defaults to ``True``.
  249. .. deprecated:: 2.5.0
  250. :type client_side: ``bool``
  251. :param header_encoding: Controls whether the headers emitted by this object
  252. in events are transparently decoded to ``unicode`` strings, and what
  253. encoding is used to do that decoding. For historical reason, this
  254. defaults to ``'utf-8'``. To prevent the decoding of headers (that is,
  255. to force them to be returned as bytestrings), this can be set to
  256. ``False`` or the empty string.
  257. .. deprecated:: 2.5.0
  258. :type header_encoding: ``str`` or ``False``
  259. :param config: The configuration for the HTTP/2 connection. If provided,
  260. supersedes the deprecated ``client_side`` and ``header_encoding``
  261. values.
  262. .. versionadded:: 2.5.0
  263. :type config: :class:`H2Configuration <h2.config.H2Configuration>`
  264. """
  265. # The initial maximum outbound frame size. This can be changed by receiving
  266. # a settings frame.
  267. DEFAULT_MAX_OUTBOUND_FRAME_SIZE = 65535
  268. # The initial maximum inbound frame size. This is somewhat arbitrarily
  269. # chosen.
  270. DEFAULT_MAX_INBOUND_FRAME_SIZE = 2**24
  271. # The highest acceptable stream ID.
  272. HIGHEST_ALLOWED_STREAM_ID = 2**31 - 1
  273. # The largest acceptable window increment.
  274. MAX_WINDOW_INCREMENT = 2**31 - 1
  275. # The initial default value of SETTINGS_MAX_HEADER_LIST_SIZE.
  276. DEFAULT_MAX_HEADER_LIST_SIZE = 2**16
  277. def __init__(self, client_side=True, header_encoding='utf-8', config=None):
  278. self.state_machine = H2ConnectionStateMachine()
  279. self.streams = {}
  280. self.highest_inbound_stream_id = 0
  281. self.highest_outbound_stream_id = 0
  282. self.encoder = Encoder()
  283. self.decoder = Decoder()
  284. # This won't always actually do anything: for versions of HPACK older
  285. # than 2.3.0 it does nothing. However, we have to try!
  286. self.decoder.max_header_list_size = self.DEFAULT_MAX_HEADER_LIST_SIZE
  287. #: The configuration for this HTTP/2 connection object.
  288. #:
  289. #: .. versionadded:: 2.5.0
  290. self.config = config
  291. if self.config is None:
  292. self.config = H2Configuration(
  293. client_side=client_side,
  294. header_encoding=header_encoding,
  295. )
  296. # Objects that store settings, including defaults.
  297. #
  298. # We set the MAX_CONCURRENT_STREAMS value to 100 because its default is
  299. # unbounded, and that's a dangerous default because it allows
  300. # essentially unbounded resources to be allocated regardless of how
  301. # they will be used. 100 should be suitable for the average
  302. # application. This default obviously does not apply to the remote
  303. # peer's settings: the remote peer controls them!
  304. #
  305. # We also set MAX_HEADER_LIST_SIZE to a reasonable value. This is to
  306. # advertise our defence against CVE-2016-6581. However, not all
  307. # versions of HPACK will let us do it. That's ok: we should at least
  308. # suggest that we're not vulnerable.
  309. self.local_settings = Settings(
  310. client=self.config.client_side,
  311. initial_values={
  312. SettingCodes.MAX_CONCURRENT_STREAMS: 100,
  313. SettingCodes.MAX_HEADER_LIST_SIZE:
  314. self.DEFAULT_MAX_HEADER_LIST_SIZE,
  315. }
  316. )
  317. self.remote_settings = Settings(client=not self.config.client_side)
  318. # The curent value of the connection flow control windows on the
  319. # connection.
  320. self.outbound_flow_control_window = (
  321. self.remote_settings.initial_window_size
  322. )
  323. #: The maximum size of a frame that can be emitted by this peer, in
  324. #: bytes.
  325. self.max_outbound_frame_size = self.remote_settings.max_frame_size
  326. #: The maximum size of a frame that can be received by this peer, in
  327. #: bytes.
  328. self.max_inbound_frame_size = self.local_settings.max_frame_size
  329. # Buffer for incoming data.
  330. self.incoming_buffer = FrameBuffer(server=not self.config.client_side)
  331. # A private variable to store a sequence of received header frames
  332. # until completion.
  333. self._header_frames = []
  334. # Data that needs to be sent.
  335. self._data_to_send = b''
  336. # Keeps track of how streams are closed.
  337. # Used to ensure that we don't blow up in the face of frames that were
  338. # in flight when a RST_STREAM was sent.
  339. # Also used to determine whether we should consider a frame received
  340. # while a stream is closed as either a stream error or a connection
  341. # error.
  342. self._closed_streams = {}
  343. # The flow control window manager for the connection.
  344. self._inbound_flow_control_window_manager = WindowManager(
  345. max_window_size=self.local_settings.initial_window_size
  346. )
  347. # When in doubt use dict-dispatch.
  348. self._frame_dispatch_table = {
  349. HeadersFrame: self._receive_headers_frame,
  350. PushPromiseFrame: self._receive_push_promise_frame,
  351. SettingsFrame: self._receive_settings_frame,
  352. DataFrame: self._receive_data_frame,
  353. WindowUpdateFrame: self._receive_window_update_frame,
  354. PingFrame: self._receive_ping_frame,
  355. RstStreamFrame: self._receive_rst_stream_frame,
  356. PriorityFrame: self._receive_priority_frame,
  357. GoAwayFrame: self._receive_goaway_frame,
  358. ContinuationFrame: self._receive_naked_continuation,
  359. AltSvcFrame: self._receive_alt_svc_frame,
  360. ExtensionFrame: self._receive_unknown_frame
  361. }
  362. def _prepare_for_sending(self, frames):
  363. if not frames:
  364. return
  365. self._data_to_send += b''.join(f.serialize() for f in frames)
  366. assert all(f.body_len <= self.max_outbound_frame_size for f in frames)
  367. def _open_streams(self, remainder):
  368. """
  369. A common method of counting number of open streams. Returns the number
  370. of streams that are open *and* that have (stream ID % 2) == remainder.
  371. While it iterates, also deletes any closed streams.
  372. """
  373. count = 0
  374. to_delete = []
  375. for stream_id, stream in self.streams.items():
  376. if stream.open and (stream_id % 2 == remainder):
  377. count += 1
  378. elif stream.closed:
  379. to_delete.append(stream_id)
  380. for stream_id in to_delete:
  381. stream = self.streams.pop(stream_id)
  382. self._closed_streams[stream_id] = stream.closed_by
  383. return count
  384. @property
  385. def open_outbound_streams(self):
  386. """
  387. The current number of open outbound streams.
  388. """
  389. outbound_numbers = int(self.config.client_side)
  390. return self._open_streams(outbound_numbers)
  391. @property
  392. def open_inbound_streams(self):
  393. """
  394. The current number of open inbound streams.
  395. """
  396. inbound_numbers = int(not self.config.client_side)
  397. return self._open_streams(inbound_numbers)
  398. @property
  399. def header_encoding(self):
  400. """
  401. Controls whether the headers emitted by this object in events are
  402. transparently decoded to ``unicode`` strings, and what encoding is used
  403. to do that decoding. For historical reason, this defaults to
  404. ``'utf-8'``. To prevent the decoding of headers (that is, to force them
  405. to be returned as bytestrings), this can be set to ``False`` or the
  406. empty string.
  407. .. versionadded:: 2.3.0
  408. .. deprecated:: 2.5.0
  409. Use :data:`config <h2.connection.H2Connection.config>` instead.
  410. """
  411. return self.config.header_encoding
  412. @header_encoding.setter
  413. def header_encoding(self, value):
  414. """
  415. Setter for header encoding config value.
  416. """
  417. self.config.header_encoding = value
  418. @property
  419. def client_side(self):
  420. """
  421. Whether this object is to be used on the client side of a connection,
  422. or on the server side. Affects the logic used by the state machine, the
  423. default settings values, the allowable stream IDs, and several other
  424. properties. Defaults to ``True``.
  425. .. deprecated:: 2.5.0
  426. Use :data:`config <h2.connection.H2Connection.config>` instead.
  427. """
  428. return self.config.client_side
  429. @property
  430. def inbound_flow_control_window(self):
  431. """
  432. The size of the inbound flow control window for the connection. This is
  433. rarely publicly useful: instead, use :meth:`remote_flow_control_window
  434. <h2.connection.H2Connection.remote_flow_control_window>`. This
  435. shortcut is largely present to provide a shortcut to this data.
  436. """
  437. return self._inbound_flow_control_window_manager.current_window_size
  438. def _begin_new_stream(self, stream_id, allowed_ids):
  439. """
  440. Initiate a new stream.
  441. .. versionchanged:: 2.0.0
  442. Removed this function from the public API.
  443. :param stream_id: The ID of the stream to open.
  444. :param allowed_ids: What kind of stream ID is allowed.
  445. """
  446. self.config.logger.debug(
  447. "Attempting to initiate stream ID %d", stream_id
  448. )
  449. outbound = self._stream_id_is_outbound(stream_id)
  450. highest_stream_id = (
  451. self.highest_outbound_stream_id if outbound else
  452. self.highest_inbound_stream_id
  453. )
  454. if stream_id <= highest_stream_id:
  455. raise StreamIDTooLowError(stream_id, highest_stream_id)
  456. if (stream_id % 2) != int(allowed_ids):
  457. raise ProtocolError(
  458. "Invalid stream ID for peer."
  459. )
  460. s = H2Stream(
  461. stream_id,
  462. config=self.config,
  463. inbound_window_size=self.local_settings.initial_window_size,
  464. outbound_window_size=self.remote_settings.initial_window_size
  465. )
  466. self.config.logger.debug("Stream ID %d created", stream_id)
  467. s.max_inbound_frame_size = self.max_inbound_frame_size
  468. s.max_outbound_frame_size = self.max_outbound_frame_size
  469. self.streams[stream_id] = s
  470. self.config.logger.debug("Current streams: %s", self.streams.keys())
  471. if outbound:
  472. self.highest_outbound_stream_id = stream_id
  473. else:
  474. self.highest_inbound_stream_id = stream_id
  475. return s
  476. def initiate_connection(self):
  477. """
  478. Provides any data that needs to be sent at the start of the connection.
  479. Must be called for both clients and servers.
  480. """
  481. self.config.logger.debug("Initializing connection")
  482. self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS)
  483. if self.config.client_side:
  484. preamble = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
  485. else:
  486. preamble = b''
  487. f = SettingsFrame(0)
  488. for setting, value in self.local_settings.items():
  489. f.settings[setting] = value
  490. self.config.logger.debug(
  491. "Send Settings frame: %s", self.local_settings
  492. )
  493. self._data_to_send += preamble + f.serialize()
  494. def initiate_upgrade_connection(self, settings_header=None):
  495. """
  496. Call to initialise the connection object for use with an upgraded
  497. HTTP/2 connection (i.e. a connection negotiated using the
  498. ``Upgrade: h2c`` HTTP header).
  499. This method differs from :meth:`initiate_connection
  500. <h2.connection.H2Connection.initiate_connection>` in several ways.
  501. Firstly, it handles the additional SETTINGS frame that is sent in the
  502. ``HTTP2-Settings`` header field. When called on a client connection,
  503. this method will return a bytestring that the caller can put in the
  504. ``HTTP2-Settings`` field they send on their initial request. When
  505. called on a server connection, the user **must** provide the value they
  506. received from the client in the ``HTTP2-Settings`` header field to the
  507. ``settings_header`` argument, which will be used appropriately.
  508. Additionally, this method sets up stream 1 in a half-closed state
  509. appropriate for this side of the connection, to reflect the fact that
  510. the request is already complete.
  511. Finally, this method also prepares the appropriate preamble to be sent
  512. after the upgrade.
  513. .. versionadded:: 2.3.0
  514. :param settings_header: (optional, server-only): The value of the
  515. ``HTTP2-Settings`` header field received from the client.
  516. :type settings_header: ``bytes``
  517. :returns: For clients, a bytestring to put in the ``HTTP2-Settings``.
  518. For servers, returns nothing.
  519. :rtype: ``bytes`` or ``None``
  520. """
  521. self.config.logger.debug(
  522. "Upgrade connection. Current settings: %s", self.local_settings
  523. )
  524. frame_data = None
  525. # Begin by getting the preamble in place.
  526. self.initiate_connection()
  527. if self.config.client_side:
  528. f = SettingsFrame(0)
  529. for setting, value in self.local_settings.items():
  530. f.settings[setting] = value
  531. frame_data = f.serialize_body()
  532. frame_data = base64.urlsafe_b64encode(frame_data)
  533. elif settings_header:
  534. # We have a settings header from the client. This needs to be
  535. # applied, but we want to throw away the ACK. We do this by
  536. # inserting the data into a Settings frame and then passing it to
  537. # the state machine, but ignoring the return value.
  538. settings_header = base64.urlsafe_b64decode(settings_header)
  539. f = SettingsFrame(0)
  540. f.parse_body(settings_header)
  541. self._receive_settings_frame(f)
  542. # Set up appropriate state. Stream 1 in a half-closed state:
  543. # half-closed(local) for clients, half-closed(remote) for servers.
  544. # Additionally, we need to set up the Connection state machine.
  545. connection_input = (
  546. ConnectionInputs.SEND_HEADERS if self.config.client_side
  547. else ConnectionInputs.RECV_HEADERS
  548. )
  549. self.config.logger.debug("Process input %s", connection_input)
  550. self.state_machine.process_input(connection_input)
  551. # Set up stream 1.
  552. self._begin_new_stream(stream_id=1, allowed_ids=AllowedStreamIDs.ODD)
  553. self.streams[1].upgrade(self.config.client_side)
  554. return frame_data
  555. def _get_or_create_stream(self, stream_id, allowed_ids):
  556. """
  557. Gets a stream by its stream ID. Will create one if one does not already
  558. exist. Use allowed_ids to circumvent the usual stream ID rules for
  559. clients and servers.
  560. .. versionchanged:: 2.0.0
  561. Removed this function from the public API.
  562. """
  563. try:
  564. return self.streams[stream_id]
  565. except KeyError:
  566. return self._begin_new_stream(stream_id, allowed_ids)
  567. def _get_stream_by_id(self, stream_id):
  568. """
  569. Gets a stream by its stream ID. Raises NoSuchStreamError if the stream
  570. ID does not correspond to a known stream and is higher than the current
  571. maximum: raises if it is lower than the current maximum.
  572. .. versionchanged:: 2.0.0
  573. Removed this function from the public API.
  574. """
  575. try:
  576. return self.streams[stream_id]
  577. except KeyError:
  578. outbound = self._stream_id_is_outbound(stream_id)
  579. highest_stream_id = (
  580. self.highest_outbound_stream_id if outbound else
  581. self.highest_inbound_stream_id
  582. )
  583. if stream_id > highest_stream_id:
  584. raise NoSuchStreamError(stream_id)
  585. else:
  586. raise StreamClosedError(stream_id)
  587. def get_next_available_stream_id(self):
  588. """
  589. Returns an integer suitable for use as the stream ID for the next
  590. stream created by this endpoint. For server endpoints, this stream ID
  591. will be even. For client endpoints, this stream ID will be odd. If no
  592. stream IDs are available, raises :class:`NoAvailableStreamIDError
  593. <h2.exceptions.NoAvailableStreamIDError>`.
  594. .. warning:: The return value from this function does not change until
  595. the stream ID has actually been used by sending or pushing
  596. headers on that stream. For that reason, it should be
  597. called as close as possible to the actual use of the
  598. stream ID.
  599. .. versionadded:: 2.0.0
  600. :raises: :class:`NoAvailableStreamIDError
  601. <h2.exceptions.NoAvailableStreamIDError>`
  602. :returns: The next free stream ID this peer can use to initiate a
  603. stream.
  604. :rtype: ``int``
  605. """
  606. # No streams have been opened yet, so return the lowest allowed stream
  607. # ID.
  608. if not self.highest_outbound_stream_id:
  609. next_stream_id = 1 if self.config.client_side else 2
  610. else:
  611. next_stream_id = self.highest_outbound_stream_id + 2
  612. self.config.logger.debug(
  613. "Next available stream ID %d", next_stream_id
  614. )
  615. if next_stream_id > self.HIGHEST_ALLOWED_STREAM_ID:
  616. raise NoAvailableStreamIDError("Exhausted allowed stream IDs")
  617. return next_stream_id
  618. def send_headers(self, stream_id, headers, end_stream=False,
  619. priority_weight=None, priority_depends_on=None,
  620. priority_exclusive=None):
  621. """
  622. Send headers on a given stream.
  623. This function can be used to send request or response headers: the kind
  624. that are sent depends on whether this connection has been opened as a
  625. client or server connection, and whether the stream was opened by the
  626. remote peer or not.
  627. If this is a client connection, calling ``send_headers`` will send the
  628. headers as a request. It will also implicitly open the stream being
  629. used. If this is a client connection and ``send_headers`` has *already*
  630. been called, this will send trailers instead.
  631. If this is a server connection, calling ``send_headers`` will send the
  632. headers as a response. It is a protocol error for a server to open a
  633. stream by sending headers. If this is a server connection and
  634. ``send_headers`` has *already* been called, this will send trailers
  635. instead.
  636. When acting as a server, you may call ``send_headers`` any number of
  637. times allowed by the following rules, in this order:
  638. - zero or more times with ``(':status', '1XX')`` (where ``1XX`` is a
  639. placeholder for any 100-level status code).
  640. - once with any other status header.
  641. - zero or one time for trailers.
  642. That is, you are allowed to send as many informational responses as you
  643. like, followed by one complete response and zero or one HTTP trailer
  644. blocks.
  645. Clients may send one or two header blocks: one request block, and
  646. optionally one trailer block.
  647. If it is important to send HPACK "never indexed" header fields (as
  648. defined in `RFC 7451 Section 7.1.3
  649. <https://tools.ietf.org/html/rfc7541#section-7.1.3>`_), the user may
  650. instead provide headers using the HPACK library's :class:`HeaderTuple
  651. <hpack:hpack.HeaderTuple>` and :class:`NeverIndexedHeaderTuple
  652. <hpack:hpack.NeverIndexedHeaderTuple>` objects.
  653. This method also allows users to prioritize the stream immediately,
  654. by sending priority information on the HEADERS frame directly. To do
  655. this, any one of ``priority_weight``, ``priority_depends_on``, or
  656. ``priority_exclusive`` must be set to a value that is not ``None``. For
  657. more information on the priority fields, see :meth:`prioritize
  658. <h2.connection.H2Connection.prioritize>`.
  659. .. warning:: In HTTP/2, it is mandatory that all the HTTP/2 special
  660. headers (that is, ones whose header keys begin with ``:``) appear
  661. at the start of the header block, before any normal headers.
  662. If you pass a dictionary to the ``headers`` parameter, it is
  663. unlikely that they will iterate in that order, and your connection
  664. may fail. For this reason, passing a ``dict`` to ``headers`` is
  665. *deprecated*, and will be removed in 3.0.
  666. .. versionchanged:: 2.3.0
  667. Added support for using :class:`HeaderTuple
  668. <hpack:hpack.HeaderTuple>` objects to store headers.
  669. .. versionchanged:: 2.4.0
  670. Added the ability to provide priority keyword arguments:
  671. ``priority_weight``, ``priority_depends_on``, and
  672. ``priority_exclusive``.
  673. :param stream_id: The stream ID to send the headers on. If this stream
  674. does not currently exist, it will be created.
  675. :type stream_id: ``int``
  676. :param headers: The request/response headers to send.
  677. :type headers: An iterable of two tuples of bytestrings or
  678. :class:`HeaderTuple <hpack:hpack.HeaderTuple>` objects.
  679. :param end_stream: Whether this headers frame should end the stream
  680. immediately (that is, whether no more data will be sent after this
  681. frame). Defaults to ``False``.
  682. :type end_stream: ``bool``
  683. :param priority_weight: Sets the priority weight of the stream. See
  684. :meth:`prioritize <h2.connection.H2Connection.prioritize>` for more
  685. about how this field works. Defaults to ``None``, which means that
  686. no priority information will be sent.
  687. :type priority_weight: ``int`` or ``None``
  688. :param priority_depends_on: Sets which stream this one depends on for
  689. priority purposes. See :meth:`prioritize
  690. <h2.connection.H2Connection.prioritize>` for more about how this
  691. field works. Defaults to ``None``, which means that no priority
  692. information will be sent.
  693. :type priority_depends_on: ``int`` or ``None``
  694. :param priority_exclusive: Sets whether this stream exclusively depends
  695. on the stream given in ``priority_depends_on`` for priority
  696. purposes. See :meth:`prioritize
  697. <h2.connection.H2Connection.prioritize>` for more about how this
  698. field workds. Defaults to ``None``, which means that no priority
  699. information will be sent.
  700. :type priority_depends_on: ``bool`` or ``None``
  701. :returns: Nothing
  702. """
  703. self.config.logger.debug(
  704. "Send headers on stream ID %d", stream_id
  705. )
  706. # Check we can open the stream.
  707. if stream_id not in self.streams:
  708. max_open_streams = self.remote_settings.max_concurrent_streams
  709. if (self.open_outbound_streams + 1) > max_open_streams:
  710. raise TooManyStreamsError(
  711. "Max outbound streams is %d, %d open" %
  712. (max_open_streams, self.open_outbound_streams)
  713. )
  714. self.state_machine.process_input(ConnectionInputs.SEND_HEADERS)
  715. stream = self._get_or_create_stream(
  716. stream_id, AllowedStreamIDs(self.config.client_side)
  717. )
  718. frames = stream.send_headers(
  719. headers, self.encoder, end_stream
  720. )
  721. # We may need to send priority information.
  722. priority_present = (
  723. (priority_weight is not None) or
  724. (priority_depends_on is not None) or
  725. (priority_exclusive is not None)
  726. )
  727. if priority_present:
  728. if not self.config.client_side:
  729. raise RFC1122Error("Servers SHOULD NOT prioritize streams.")
  730. headers_frame = frames[0]
  731. headers_frame.flags.add('PRIORITY')
  732. frames[0] = _add_frame_priority(
  733. headers_frame,
  734. priority_weight,
  735. priority_depends_on,
  736. priority_exclusive
  737. )
  738. self._prepare_for_sending(frames)
  739. def send_data(self, stream_id, data, end_stream=False, pad_length=None):
  740. """
  741. Send data on a given stream.
  742. This method does no breaking up of data: if the data is larger than the
  743. value returned by :meth:`local_flow_control_window
  744. <h2.connection.H2Connection.local_flow_control_window>` for this stream
  745. then a :class:`FlowControlError <h2.exceptions.FlowControlError>` will
  746. be raised. If the data is larger than :data:`max_outbound_frame_size
  747. <h2.connection.H2Connection.max_outbound_frame_size>` then a
  748. :class:`FrameTooLargeError <h2.exceptions.FrameTooLargeError>` will be
  749. raised.
  750. Hyper-h2 does this to avoid buffering the data internally. If the user
  751. has more data to send than hyper-h2 will allow, consider breaking it up
  752. and buffering it externally.
  753. :param stream_id: The ID of the stream on which to send the data.
  754. :type stream_id: ``int``
  755. :param data: The data to send on the stream.
  756. :type data: ``bytes``
  757. :param end_stream: (optional) Whether this is the last data to be sent
  758. on the stream. Defaults to ``False``.
  759. :type end_stream: ``bool``
  760. :param pad_length: (optional) Length of the padding to apply to the
  761. data frame. Defaults to ``None`` for no use of padding. Note that
  762. a value of ``0`` results in padding of length ``0``
  763. (with the "padding" flag set on the frame).
  764. .. versionadded:: 2.6.0
  765. :type pad_length: ``int``
  766. :returns: Nothing
  767. """
  768. self.config.logger.debug(
  769. "Send data on stream ID %d with len %d", stream_id, len(data)
  770. )
  771. frame_size = len(data)
  772. if pad_length is not None:
  773. if not isinstance(pad_length, int):
  774. raise TypeError("pad_length must be an int")
  775. if pad_length < 0 or pad_length > 255:
  776. raise ValueError("pad_length must be within range: [0, 255]")
  777. # Account for padding bytes plus the 1-byte padding length field.
  778. frame_size += pad_length + 1
  779. self.config.logger.debug(
  780. "Frame size on stream ID %d is %d", stream_id, frame_size
  781. )
  782. if frame_size > self.local_flow_control_window(stream_id):
  783. raise FlowControlError(
  784. "Cannot send %d bytes, flow control window is %d." %
  785. (frame_size, self.local_flow_control_window(stream_id))
  786. )
  787. elif frame_size > self.max_outbound_frame_size:
  788. raise FrameTooLargeError(
  789. "Cannot send frame size %d, max frame size is %d" %
  790. (frame_size, self.max_outbound_frame_size)
  791. )
  792. self.state_machine.process_input(ConnectionInputs.SEND_DATA)
  793. frames = self.streams[stream_id].send_data(
  794. data, end_stream, pad_length=pad_length
  795. )
  796. self._prepare_for_sending(frames)
  797. self.outbound_flow_control_window -= frame_size
  798. self.config.logger.debug(
  799. "Outbound flow control window size is %d",
  800. self.outbound_flow_control_window
  801. )
  802. assert self.outbound_flow_control_window >= 0
  803. def end_stream(self, stream_id):
  804. """
  805. Cleanly end a given stream.
  806. This method ends a stream by sending an empty DATA frame on that stream
  807. with the ``END_STREAM`` flag set.
  808. :param stream_id: The ID of the stream to end.
  809. :type stream_id: ``int``
  810. :returns: Nothing
  811. """
  812. self.config.logger.debug("End stream ID %d", stream_id)
  813. self.state_machine.process_input(ConnectionInputs.SEND_DATA)
  814. frames = self.streams[stream_id].end_stream()
  815. self._prepare_for_sending(frames)
  816. def increment_flow_control_window(self, increment, stream_id=None):
  817. """
  818. Increment a flow control window, optionally for a single stream. Allows
  819. the remote peer to send more data.
  820. .. versionchanged:: 2.0.0
  821. Rejects attempts to increment the flow control window by out of
  822. range values with a ``ValueError``.
  823. :param increment: The amount to increment the flow control window by.
  824. :type increment: ``int``
  825. :param stream_id: (optional) The ID of the stream that should have its
  826. flow control window opened. If not present or ``None``, the
  827. connection flow control window will be opened instead.
  828. :type stream_id: ``int`` or ``None``
  829. :returns: Nothing
  830. :raises: ``ValueError``
  831. """
  832. if not (1 <= increment <= self.MAX_WINDOW_INCREMENT):
  833. raise ValueError(
  834. "Flow control increment must be between 1 and %d" %
  835. self.MAX_WINDOW_INCREMENT
  836. )
  837. self.state_machine.process_input(ConnectionInputs.SEND_WINDOW_UPDATE)
  838. if stream_id is not None:
  839. stream = self.streams[stream_id]
  840. frames = stream.increase_flow_control_window(
  841. increment
  842. )
  843. else:
  844. self._inbound_flow_control_window_manager.window_opened(increment)
  845. f = WindowUpdateFrame(0)
  846. f.window_increment = increment
  847. frames = [f]
  848. self.config.logger.debug(
  849. "Increase stream ID %d flow control window by %d",
  850. stream_id, increment
  851. )
  852. self._prepare_for_sending(frames)
  853. def push_stream(self, stream_id, promised_stream_id, request_headers):
  854. """
  855. Push a response to the client by sending a PUSH_PROMISE frame.
  856. If it is important to send HPACK "never indexed" header fields (as
  857. defined in `RFC 7451 Section 7.1.3
  858. <https://tools.ietf.org/html/rfc7541#section-7.1.3>`_), the user may
  859. instead provide headers using the HPACK library's :class:`HeaderTuple
  860. <hpack:hpack.HeaderTuple>` and :class:`NeverIndexedHeaderTuple
  861. <hpack:hpack.NeverIndexedHeaderTuple>` objects.
  862. :param stream_id: The ID of the stream that this push is a response to.
  863. :type stream_id: ``int``
  864. :param promised_stream_id: The ID of the stream that the pushed
  865. response will be sent on.
  866. :type promised_stream_id: ``int``
  867. :param request_headers: The headers of the request that the pushed
  868. response will be responding to.
  869. :type request_headers: An iterable of two tuples of bytestrings or
  870. :class:`HeaderTuple <hpack:hpack.HeaderTuple>` objects.
  871. :returns: Nothing
  872. """
  873. self.config.logger.debug(
  874. "Send Push Promise frame on stream ID %d", stream_id
  875. )
  876. if not self.remote_settings.enable_push:
  877. raise ProtocolError("Remote peer has disabled stream push")
  878. self.state_machine.process_input(ConnectionInputs.SEND_PUSH_PROMISE)
  879. stream = self._get_stream_by_id(stream_id)
  880. # We need to prevent users pushing streams in response to streams that
  881. # they themselves have already pushed: see #163 and RFC 7540 § 6.6. The
  882. # easiest way to do that is to assert that the stream_id is not even:
  883. # this shortcut works because only servers can push and the state
  884. # machine will enforce this.
  885. if (stream_id % 2) == 0:
  886. raise ProtocolError("Cannot recursively push streams.")
  887. new_stream = self._begin_new_stream(
  888. promised_stream_id, AllowedStreamIDs.EVEN
  889. )
  890. self.streams[promised_stream_id] = new_stream
  891. frames = stream.push_stream_in_band(
  892. promised_stream_id, request_headers, self.encoder
  893. )
  894. new_frames = new_stream.locally_pushed()
  895. self._prepare_for_sending(frames + new_frames)
  896. def ping(self, opaque_data):
  897. """
  898. Send a PING frame.
  899. :param opaque_data: A bytestring of length 8 that will be sent in the
  900. PING frame.
  901. :returns: Nothing
  902. """
  903. self.config.logger.debug("Send Ping frame")
  904. if not isinstance(opaque_data, bytes) or len(opaque_data) != 8:
  905. raise ValueError("Invalid value for ping data: %r" % opaque_data)
  906. self.state_machine.process_input(ConnectionInputs.SEND_PING)
  907. f = PingFrame(0)
  908. f.opaque_data = opaque_data
  909. self._prepare_for_sending([f])
  910. def reset_stream(self, stream_id, error_code=0):
  911. """
  912. Reset a stream.
  913. This method forcibly closes a stream by sending a RST_STREAM frame for
  914. a given stream. This is not a graceful closure. To gracefully end a
  915. stream, try the :meth:`end_stream
  916. <h2.connection.H2Connection.end_stream>` method.
  917. :param stream_id: The ID of the stream to reset.
  918. :type stream_id: ``int``
  919. :param error_code: (optional) The error code to use to reset the
  920. stream. Defaults to :data:`ErrorCodes.NO_ERROR
  921. <h2.errors.ErrorCodes.NO_ERROR>`.
  922. :type error_code: ``int``
  923. :returns: Nothing
  924. """
  925. self.config.logger.debug("Reset stream ID %d", stream_id)
  926. self.state_machine.process_input(ConnectionInputs.SEND_RST_STREAM)
  927. stream = self._get_stream_by_id(stream_id)
  928. frames = stream.reset_stream(error_code)
  929. self._prepare_for_sending(frames)
  930. def close_connection(self, error_code=0, additional_data=None,
  931. last_stream_id=None):
  932. """
  933. Close a connection, emitting a GOAWAY frame.
  934. .. versionchanged:: 2.4.0
  935. Added ``additional_data`` and ``last_stream_id`` arguments.
  936. :param error_code: (optional) The error code to send in the GOAWAY
  937. frame.
  938. :param additional_data: (optional) Additional debug data indicating
  939. a reason for closing the connection. Must be a bytestring.
  940. :param last_stream_id: (optional) The last stream which was processed
  941. by the sender. Defaults to ``highest_inbound_stream_id``.
  942. :returns: Nothing
  943. """
  944. self.config.logger.debug("Close connection")
  945. self.state_machine.process_input(ConnectionInputs.SEND_GOAWAY)
  946. # Additional_data must be bytes
  947. if additional_data is not None:
  948. assert isinstance(additional_data, bytes)
  949. if last_stream_id is None:
  950. last_stream_id = self.highest_inbound_stream_id
  951. f = GoAwayFrame(
  952. stream_id=0,
  953. last_stream_id=last_stream_id,
  954. error_code=error_code,
  955. additional_data=(additional_data or b'')
  956. )
  957. self._prepare_for_sending([f])
  958. def update_settings(self, new_settings):
  959. """
  960. Update the local settings. This will prepare and emit the appropriate
  961. SETTINGS frame.
  962. :param new_settings: A dictionary of {setting: new value}
  963. """
  964. self.config.logger.debug(
  965. "Update connection settings to %s", new_settings
  966. )
  967. self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS)
  968. self.local_settings.update(new_settings)
  969. s = SettingsFrame(0)
  970. s.settings = new_settings
  971. self._prepare_for_sending([s])
  972. def advertise_alternative_service(self,
  973. field_value,
  974. origin=None,
  975. stream_id=None):
  976. """
  977. Notify a client about an available Alternative Service.
  978. An Alternative Service is defined in `RFC 7838
  979. <https://tools.ietf.org/html/rfc7838>`_. An Alternative Service
  980. notification informs a client that a given origin is also available
  981. elsewhere.
  982. Alternative Services can be advertised in two ways. Firstly, they can
  983. be advertised explicitly: that is, a server can say "origin X is also
  984. available at Y". To advertise like this, set the ``origin`` argument
  985. and not the ``stream_id`` argument. Alternatively, they can be
  986. advertised implicitly: that is, a server can say "the origin you're
  987. contacting on stream X is also available at Y". To advertise like this,
  988. set the ``stream_id`` argument and not the ``origin`` argument.
  989. The explicit method of advertising can be done as long as the
  990. connection is active. The implicit method can only be done after the
  991. client has sent the request headers and before the server has sent the
  992. response headers: outside of those points, Hyper-h2 will forbid sending
  993. the Alternative Service advertisement by raising a ProtocolError.
  994. The ``field_value`` parameter is specified in RFC 7838. Hyper-h2 does
  995. not validate or introspect this argument: the user is required to
  996. ensure that it's well-formed. ``field_value`` corresponds to RFC 7838's
  997. "Alternative Service Field Value".
  998. .. note:: It is strongly preferred to use the explicit method of
  999. advertising Alternative Services. The implicit method of
  1000. advertising Alternative Services has a number of subtleties
  1001. and can lead to inconsistencies between the server and
  1002. client. Hyper-h2 allows both mechanisms, but caution is
  1003. strongly advised.
  1004. .. versionadded:: 2.3.0
  1005. :param field_value: The RFC 7838 Alternative Service Field Value. This
  1006. argument is not introspected by Hyper-h2: the user is responsible
  1007. for ensuring that it is well-formed.
  1008. :type field_value: ``bytes``
  1009. :param origin: The origin/authority to which the Alternative Service
  1010. being advertised applies. Must not be provided at the same time as
  1011. ``stream_id``.
  1012. :type origin: ``bytes`` or ``None``
  1013. :param stream_id: The ID of the stream which was sent to the authority
  1014. for which this Alternative Service advertisement applies. Must not
  1015. be provided at the same time as ``origin``.
  1016. :type stream_id: ``int`` or ``None``
  1017. :returns: Nothing.
  1018. """
  1019. if not isinstance(field_value, bytes):
  1020. raise ValueError("Field must be bytestring.")
  1021. if origin is not None and stream_id is not None:
  1022. raise ValueError("Must not provide both origin and stream_id")
  1023. self.state_machine.process_input(
  1024. ConnectionInputs.SEND_ALTERNATIVE_SERVICE
  1025. )
  1026. if origin is not None:
  1027. # This ALTSVC is sent on stream zero.
  1028. f = AltSvcFrame(stream_id=0)
  1029. f.origin = origin
  1030. f.field = field_value
  1031. frames = [f]
  1032. else:
  1033. stream = self._get_stream_by_id(stream_id)
  1034. frames = stream.advertise_alternative_service(field_value)
  1035. self._prepare_for_sending(frames)
  1036. def prioritize(self, stream_id, weight=None, depends_on=None,
  1037. exclusive=None):
  1038. """
  1039. Notify a server about the priority of a stream.
  1040. Stream priorities are a form of guidance to a remote server: they
  1041. inform the server about how important a given response is, so that the
  1042. server may allocate its resources (e.g. bandwidth, CPU time, etc.)
  1043. accordingly. This exists to allow clients to ensure that the most
  1044. important data arrives earlier, while less important data does not
  1045. starve out the more important data.
  1046. Stream priorities are explained in depth in `RFC 7540 Section 5.3
  1047. <https://tools.ietf.org/html/rfc7540#section-5.3>`_.
  1048. This method updates the priority information of a single stream. It may
  1049. be called well before a stream is actively in use, or well after a
  1050. stream is closed.
  1051. .. warning:: RFC 7540 allows for servers to change the priority of
  1052. streams. However, hyper-h2 **does not** allow server
  1053. stacks to do this. This is because most clients do not
  1054. adequately know how to respond when provided conflicting
  1055. priority information, and relatively little utility is
  1056. provided by making that functionality available.
  1057. .. note:: hyper-h2 **does not** maintain any information about the
  1058. RFC 7540 priority tree. That means that hyper-h2 does not
  1059. prevent incautious users from creating invalid priority
  1060. trees, particularly by creating priority loops. While some
  1061. basic error checking is provided by hyper-h2, users are
  1062. strongly recommended to understand their prioritisation
  1063. strategies before using the priority tools here.
  1064. .. note:: Priority information is strictly advisory. Servers are
  1065. allowed to disregard it entirely. Avoid relying on the idea
  1066. that your priority signaling will definitely be obeyed.
  1067. .. versionadded:: 2.4.0
  1068. :param stream_id: The ID of the stream to prioritize.
  1069. :type stream_id: ``int``
  1070. :param weight: The weight to give the stream. Defaults to ``16``, the
  1071. default weight of any stream. May be any value between ``1`` and
  1072. ``256`` inclusive. The relative weight of a stream indicates what
  1073. proportion of available resources will be allocated to that
  1074. stream.
  1075. :type weight: ``int``
  1076. :param depends_on: The ID of the stream on which this stream depends.
  1077. This stream will only be progressed if it is impossible to
  1078. progress the parent stream (the one on which this one depends).
  1079. Passing the value ``0`` means that this stream does not depend on
  1080. any other. Defaults to ``0``.
  1081. :type depends_on: ``int``
  1082. :param exclusive: Whether this stream is an exclusive dependency of its
  1083. "parent" stream (i.e. the stream given by ``depends_on``). If a
  1084. stream is an exclusive dependency of another, that means that all
  1085. previously-set children of the parent are moved to become children
  1086. of the new exclusively-dependent stream. Defaults to ``False``.
  1087. :type exclusive: ``bool``
  1088. """
  1089. if not self.config.client_side:
  1090. raise RFC1122Error("Servers SHOULD NOT prioritize streams.")
  1091. self.state_machine.process_input(
  1092. ConnectionInputs.SEND_PRIORITY
  1093. )
  1094. frame = PriorityFrame(stream_id)
  1095. frame = _add_frame_priority(frame, weight, depends_on, exclusive)
  1096. self._prepare_for_sending([frame])
  1097. def local_flow_control_window(self, stream_id):
  1098. """
  1099. Returns the maximum amount of data that can be sent on stream
  1100. ``stream_id``.
  1101. This value will never be larger than the total data that can be sent on
  1102. the connection: even if the given stream allows more data, the
  1103. connection window provides a logical maximum to the amount of data that
  1104. can be sent.
  1105. The maximum data that can be sent in a single data frame on a stream
  1106. is either this value, or the maximum frame size, whichever is
  1107. *smaller*.
  1108. :param stream_id: The ID of the stream whose flow control window is
  1109. being queried.
  1110. :type stream_id: ``int``
  1111. :returns: The amount of data in bytes that can be sent on the stream
  1112. before the flow control window is exhausted.
  1113. :rtype: ``int``
  1114. """
  1115. stream = self._get_stream_by_id(stream_id)
  1116. return min(
  1117. self.outbound_flow_control_window,
  1118. stream.outbound_flow_control_window
  1119. )
  1120. def remote_flow_control_window(self, stream_id):
  1121. """
  1122. Returns the maximum amount of data the remote peer can send on stream
  1123. ``stream_id``.
  1124. This value will never be larger than the total data that can be sent on
  1125. the connection: even if the given stream allows more data, the
  1126. connection window provides a logical maximum to the amount of data that
  1127. can be sent.
  1128. The maximum data that can be sent in a single data frame on a stream
  1129. is either this value, or the maximum frame size, whichever is
  1130. *smaller*.
  1131. :param stream_id: The ID of the stream whose flow control window is
  1132. being queried.
  1133. :type stream_id: ``int``
  1134. :returns: The amount of data in bytes that can be received on the
  1135. stream before the flow control window is exhausted.
  1136. :rtype: ``int``
  1137. """
  1138. stream = self._get_stream_by_id(stream_id)
  1139. return min(
  1140. self.inbound_flow_control_window,
  1141. stream.inbound_flow_control_window
  1142. )
  1143. def acknowledge_received_data(self, acknowledged_size, stream_id):
  1144. """
  1145. Inform the :class:`H2Connection <h2.connection.H2Connection>` that a
  1146. certain number of flow-controlled bytes have been processed, and that
  1147. the space should be handed back to the remote peer at an opportune
  1148. time.
  1149. .. versionadded:: 2.5.0
  1150. :param acknowledged_size: The total *flow-controlled size* of the data
  1151. that has been processed. Note that this must include the amount of
  1152. padding that was sent with that data.
  1153. :type acknowledged_size: ``int``
  1154. :param stream_id: The ID of the stream on which this data was received.
  1155. :type stream_id: ``int``
  1156. :returns: Nothing
  1157. :rtype: ``None``
  1158. """
  1159. self.config.logger.debug(
  1160. "Ack received data on stream ID %d with size %d",
  1161. stream_id, acknowledged_size
  1162. )
  1163. if stream_id <= 0:
  1164. raise ValueError(
  1165. "Stream ID %d is not valid for acknowledge_received_data" %
  1166. stream_id
  1167. )
  1168. if acknowledged_size < 0:
  1169. raise ValueError("Cannot acknowledge negative data")
  1170. frames = []
  1171. conn_manager = self._inbound_flow_control_window_manager
  1172. conn_increment = conn_manager.process_bytes(acknowledged_size)
  1173. if conn_increment:
  1174. f = WindowUpdateFrame(0)
  1175. f.window_increment = conn_increment
  1176. frames.append(f)
  1177. try:
  1178. stream = self._get_stream_by_id(stream_id)
  1179. except StreamClosedError:
  1180. # The stream is already gone. We're not worried about incrementing
  1181. # the window in this case.
  1182. pass
  1183. else:
  1184. # No point incrementing the windows of closed streams.
  1185. if stream.open:
  1186. frames.extend(
  1187. stream.acknowledge_received_data(acknowledged_size)
  1188. )
  1189. self._prepare_for_sending(frames)
  1190. def data_to_send(self, amt=None):
  1191. """
  1192. Returns some data for sending out of the internal data buffer.
  1193. This method is analogous to ``read`` on a file-like object, but it
  1194. doesn't block. Instead, it returns as much data as the user asks for,
  1195. or less if that much data is not available. It does not perform any
  1196. I/O, and so uses a different name.
  1197. :param amt: (optional) The maximum amount of data to return. If not
  1198. set, or set to ``None``, will return as much data as possible.
  1199. :type amt: ``int``
  1200. :returns: A bytestring containing the data to send on the wire.
  1201. :rtype: ``bytes``
  1202. """
  1203. if amt is None:
  1204. data = self._data_to_send
  1205. self._data_to_send = b''
  1206. return data
  1207. else:
  1208. data = self._data_to_send[:amt]
  1209. self._data_to_send = self._data_to_send[amt:]
  1210. return data
  1211. def clear_outbound_data_buffer(self):
  1212. """
  1213. Clears the outbound data buffer, such that if this call was immediately
  1214. followed by a call to
  1215. :meth:`data_to_send <h2.connection.H2Connection.data_to_send>`, that
  1216. call would return no data.
  1217. This method should not normally be used, but is made available to avoid
  1218. exposing implementation details.
  1219. """
  1220. self._data_to_send = b''
  1221. def _acknowledge_settings(self):
  1222. """
  1223. Acknowledge settings that have been received.
  1224. .. versionchanged:: 2.0.0
  1225. Removed from public API, removed useless ``event`` parameter, made
  1226. automatic.
  1227. :returns: Nothing
  1228. """
  1229. self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS)
  1230. changes = self.remote_settings.acknowledge()
  1231. if SettingCodes.INITIAL_WINDOW_SIZE in changes:
  1232. setting = changes[SettingCodes.INITIAL_WINDOW_SIZE]
  1233. self._flow_control_change_from_settings(
  1234. setting.original_value,
  1235. setting.new_value,
  1236. )
  1237. # HEADER_TABLE_SIZE changes by the remote part affect our encoder: cf.
  1238. # RFC 7540 Section 6.5.2.
  1239. if SettingCodes.HEADER_TABLE_SIZE in changes:
  1240. setting = changes[SettingCodes.HEADER_TABLE_SIZE]
  1241. self.encoder.header_table_size = setting.new_value
  1242. if SettingCodes.MAX_FRAME_SIZE in changes:
  1243. setting = changes[SettingCodes.MAX_FRAME_SIZE]
  1244. self.max_outbound_frame_size = setting.new_value
  1245. for stream in self.streams.values():
  1246. stream.max_outbound_frame_size = setting.new_value
  1247. f = SettingsFrame(0)
  1248. f.flags.add('ACK')
  1249. return [f]
  1250. def _flow_control_change_from_settings(self, old_value, new_value):
  1251. """
  1252. Update flow control windows in response to a change in the value of
  1253. SETTINGS_INITIAL_WINDOW_SIZE.
  1254. When this setting is changed, it automatically updates all flow control
  1255. windows by the delta in the settings values. Note that it does not
  1256. increment the *connection* flow control window, per section 6.9.2 of
  1257. RFC 7540.
  1258. """
  1259. delta = new_value - old_value
  1260. for stream in self.streams.values():
  1261. stream.outbound_flow_control_window = guard_increment_window(
  1262. stream.outbound_flow_control_window,
  1263. delta
  1264. )
  1265. def _inbound_flow_control_change_from_settings(self, old_value, new_value):
  1266. """
  1267. Update remote flow control windows in response to a change in the value
  1268. of SETTINGS_INITIAL_WINDOW_SIZE.
  1269. When this setting is changed, it automatically updates all remote flow
  1270. control windows by the delta in the settings values.
  1271. """
  1272. delta = new_value - old_value
  1273. for stream in self.streams.values():
  1274. stream._inbound_flow_control_change_from_settings(delta)
  1275. def receive_data(self, data):
  1276. """
  1277. Pass some received HTTP/2 data to the connection for handling.
  1278. :param data: The data received from the remote peer on the network.
  1279. :type data: ``bytes``
  1280. :returns: A list of events that the remote peer triggered by sending
  1281. this data.
  1282. """
  1283. self.config.logger.debug(
  1284. "Process received data on connection. Received data: %r", data
  1285. )
  1286. events = []
  1287. self.incoming_buffer.add_data(data)
  1288. self.incoming_buffer.max_frame_size = self.max_inbound_frame_size
  1289. try:
  1290. for frame in self.incoming_buffer:
  1291. events.extend(self._receive_frame(frame))
  1292. except InvalidPaddingError:
  1293. self._terminate_connection(ErrorCodes.PROTOCOL_ERROR)
  1294. raise ProtocolError("Received frame with invalid padding.")
  1295. except ProtocolError as e:
  1296. # For whatever reason, receiving the frame caused a protocol error.
  1297. # We should prepare to emit a GoAway frame before throwing the
  1298. # exception up further. No need for an event: the exception will
  1299. # do fine.
  1300. self._terminate_connection(e.error_code)
  1301. raise
  1302. return events
  1303. def _receive_frame(self, frame):
  1304. """
  1305. Handle a frame received on the connection.
  1306. .. versionchanged:: 2.0.0
  1307. Removed from the public API.
  1308. """
  1309. try:
  1310. # I don't love using __class__ here, maybe reconsider it.
  1311. frames, events = self._frame_dispatch_table[frame.__class__](frame)
  1312. except StreamClosedError as e:
  1313. # If the stream was closed by RST_STREAM, we just send a RST_STREAM
  1314. # to the remote peer. Otherwise, this is a connection error, and so
  1315. # we will re-raise to trigger one.
  1316. if self._stream_is_closed_by_reset(e.stream_id):
  1317. f = RstStreamFrame(e.stream_id)
  1318. f.error_code = e.error_code
  1319. self._prepare_for_sending([f])
  1320. events = e._events
  1321. else:
  1322. raise
  1323. except StreamIDTooLowError as e:
  1324. # The stream ID seems invalid. This may happen when the closed
  1325. # stream has been cleaned up, or when the remote peer has opened a
  1326. # new stream with a higher stream ID than this one, forcing it
  1327. # closed implicitly.
  1328. #
  1329. # Check how the stream was closed: depending on the mechanism, it
  1330. # is either a stream error or a connection error.
  1331. if self._stream_is_closed_by_reset(e.stream_id):
  1332. # Closed by RST_STREAM is a stream error.
  1333. f = RstStreamFrame(e.stream_id)
  1334. f.error_code = ErrorCodes.STREAM_CLOSED
  1335. self._prepare_for_sending([f])
  1336. events = []
  1337. elif self._stream_is_closed_by_end(e.stream_id):
  1338. # Closed by END_STREAM is a connection error.
  1339. raise StreamClosedError(e.stream_id)
  1340. else:
  1341. # Closed implicitly, also a connection error, but of type
  1342. # PROTOCOL_ERROR.
  1343. raise
  1344. else:
  1345. self._prepare_for_sending(frames)
  1346. return events
  1347. def _terminate_connection(self, error_code):
  1348. """
  1349. Terminate the connection early. Used in error handling blocks to send
  1350. GOAWAY frames.
  1351. """
  1352. f = GoAwayFrame(0)
  1353. f.last_stream_id = self.highest_inbound_stream_id
  1354. f.error_code = error_code
  1355. self.state_machine.process_input(ConnectionInputs.SEND_GOAWAY)
  1356. self._prepare_for_sending([f])
  1357. def _receive_headers_frame(self, frame):
  1358. """
  1359. Receive a headers frame on the connection.
  1360. """
  1361. # If necessary, check we can open the stream. Also validate that the
  1362. # stream ID is valid.
  1363. if frame.stream_id not in self.streams:
  1364. max_open_streams = self.local_settings.max_concurrent_streams
  1365. if (self.open_inbound_streams + 1) > max_open_streams:
  1366. raise TooManyStreamsError(
  1367. "Max outbound streams is %d, %d open" %
  1368. (max_open_streams, self.open_outbound_streams)
  1369. )
  1370. # Let's decode the headers. We handle headers as bytes internally up
  1371. # until we hang them off the event, at which point we may optionally
  1372. # convert them to unicode.
  1373. headers = _decode_headers(self.decoder, frame.data)
  1374. events = self.state_machine.process_input(
  1375. ConnectionInputs.RECV_HEADERS
  1376. )
  1377. stream = self._get_or_create_stream(
  1378. frame.stream_id, AllowedStreamIDs(not self.config.client_side)
  1379. )
  1380. frames, stream_events = stream.receive_headers(
  1381. headers,
  1382. 'END_STREAM' in frame.flags,
  1383. self.config.header_encoding
  1384. )
  1385. if 'PRIORITY' in frame.flags:
  1386. p_frames, p_events = self._receive_priority_frame(frame)
  1387. stream_events[0].priority_updated = p_events[0]
  1388. stream_events.extend(p_events)
  1389. assert not p_frames
  1390. return frames, events + stream_events
  1391. def _receive_push_promise_frame(self, frame):
  1392. """
  1393. Receive a push-promise frame on the connection.
  1394. """
  1395. if not self.local_settings.enable_push:
  1396. raise ProtocolError("Received pushed stream")
  1397. pushed_headers = _decode_headers(self.decoder, frame.data)
  1398. events = self.state_machine.process_input(
  1399. ConnectionInputs.RECV_PUSH_PROMISE
  1400. )
  1401. try:
  1402. stream = self._get_stream_by_id(frame.stream_id)
  1403. except NoSuchStreamError:
  1404. # We need to check if the parent stream was reset by us. If it was
  1405. # then we presume that the PUSH_PROMISE was in flight when we reset
  1406. # the parent stream. Rather than accept the new stream, just reset
  1407. # it.
  1408. #
  1409. # If this was closed naturally, however, we should call this a
  1410. # PROTOCOL_ERROR: pushing a stream on a naturally closed stream is
  1411. # a real problem because it creates a brand new stream that the
  1412. # remote peer now believes exists.
  1413. if (self._stream_closed_by(frame.stream_id) ==
  1414. StreamClosedBy.SEND_RST_STREAM):
  1415. f = RstStreamFrame(frame.promised_stream_id)
  1416. f.error_code = ErrorCodes.REFUSED_STREAM
  1417. return [f], events
  1418. raise ProtocolError("Attempted to push on closed stream.")
  1419. # We need to prevent peers pushing streams in response to streams that
  1420. # they themselves have already pushed: see #163 and RFC 7540 § 6.6. The
  1421. # easiest way to do that is to assert that the stream_id is not even:
  1422. # this shortcut works because only servers can push and the state
  1423. # machine will enforce this.
  1424. if (frame.stream_id % 2) == 0:
  1425. raise ProtocolError("Cannot recursively push streams.")
  1426. try:
  1427. frames, stream_events = stream.receive_push_promise_in_band(
  1428. frame.promised_stream_id,
  1429. pushed_headers,
  1430. self.config.header_encoding,
  1431. )
  1432. except StreamClosedError:
  1433. # The parent stream was reset by us, so we presume that
  1434. # PUSH_PROMISE was in flight when we reset the parent stream.
  1435. # So we just reset the new stream.
  1436. f = RstStreamFrame(frame.promised_stream_id)
  1437. f.error_code = ErrorCodes.REFUSED_STREAM
  1438. return [f], events
  1439. new_stream = self._begin_new_stream(
  1440. frame.promised_stream_id, AllowedStreamIDs.EVEN
  1441. )
  1442. self.streams[frame.promised_stream_id] = new_stream
  1443. new_stream.remotely_pushed(pushed_headers)
  1444. return frames, events + stream_events
  1445. def _receive_data_frame(self, frame):
  1446. """
  1447. Receive a data frame on the connection.
  1448. """
  1449. flow_controlled_length = frame.flow_controlled_length
  1450. events = self.state_machine.process_input(
  1451. ConnectionInputs.RECV_DATA
  1452. )
  1453. self._inbound_flow_control_window_manager.window_consumed(
  1454. flow_controlled_length
  1455. )
  1456. stream = self._get_stream_by_id(frame.stream_id)
  1457. frames, stream_events = stream.receive_data(
  1458. frame.data,
  1459. 'END_STREAM' in frame.flags,
  1460. flow_controlled_length
  1461. )
  1462. return frames, events + stream_events
  1463. def _receive_settings_frame(self, frame):
  1464. """
  1465. Receive a SETTINGS frame on the connection.
  1466. """
  1467. events = self.state_machine.process_input(
  1468. ConnectionInputs.RECV_SETTINGS
  1469. )
  1470. # This is an ack of the local settings.
  1471. if 'ACK' in frame.flags:
  1472. changed_settings = self._local_settings_acked()
  1473. ack_event = SettingsAcknowledged()
  1474. ack_event.changed_settings = changed_settings
  1475. events.append(ack_event)
  1476. return [], events
  1477. # Add the new settings.
  1478. self.remote_settings.update(frame.settings)
  1479. events.append(
  1480. RemoteSettingsChanged.from_settings(
  1481. self.remote_settings, frame.settings
  1482. )
  1483. )
  1484. frames = self._acknowledge_settings()
  1485. return frames, events
  1486. def _receive_window_update_frame(self, frame):
  1487. """
  1488. Receive a WINDOW_UPDATE frame on the connection.
  1489. """
  1490. # Validate the frame.
  1491. if not (1 <= frame.window_increment <= self.MAX_WINDOW_INCREMENT):
  1492. raise ProtocolError(
  1493. "Flow control increment must be between 1 and %d, received %d"
  1494. % (self.MAX_WINDOW_INCREMENT, frame.window_increment)
  1495. )
  1496. events = self.state_machine.process_input(
  1497. ConnectionInputs.RECV_WINDOW_UPDATE
  1498. )
  1499. if frame.stream_id:
  1500. stream = self._get_stream_by_id(frame.stream_id)
  1501. frames, stream_events = stream.receive_window_update(
  1502. frame.window_increment
  1503. )
  1504. else:
  1505. # Increment our local flow control window.
  1506. self.outbound_flow_control_window = guard_increment_window(
  1507. self.outbound_flow_control_window,
  1508. frame.window_increment
  1509. )
  1510. # FIXME: Should we split this into one event per active stream?
  1511. window_updated_event = WindowUpdated()
  1512. window_updated_event.stream_id = 0
  1513. window_updated_event.delta = frame.window_increment
  1514. stream_events = [window_updated_event]
  1515. frames = []
  1516. return frames, events + stream_events
  1517. def _receive_ping_frame(self, frame):
  1518. """
  1519. Receive a PING frame on the connection.
  1520. """
  1521. events = self.state_machine.process_input(
  1522. ConnectionInputs.RECV_PING
  1523. )
  1524. flags = []
  1525. if 'ACK' in frame.flags:
  1526. evt = PingAcknowledged()
  1527. evt.ping_data = frame.opaque_data
  1528. events.append(evt)
  1529. else:
  1530. f = PingFrame(0)
  1531. f.flags = {'ACK'}
  1532. f.opaque_data = frame.opaque_data
  1533. flags.append(f)
  1534. return flags, events
  1535. def _receive_rst_stream_frame(self, frame):
  1536. """
  1537. Receive a RST_STREAM frame on the connection.
  1538. """
  1539. events = self.state_machine.process_input(
  1540. ConnectionInputs.RECV_RST_STREAM
  1541. )
  1542. try:
  1543. stream = self._get_stream_by_id(frame.stream_id)
  1544. except NoSuchStreamError:
  1545. # The stream is missing. That's ok, we just do nothing here.
  1546. stream_frames = []
  1547. stream_events = []
  1548. else:
  1549. stream_frames, stream_events = stream.stream_reset(frame)
  1550. return stream_frames, events + stream_events
  1551. def _receive_priority_frame(self, frame):
  1552. """
  1553. Receive a PRIORITY frame on the connection.
  1554. """
  1555. events = self.state_machine.process_input(
  1556. ConnectionInputs.RECV_PRIORITY
  1557. )
  1558. event = PriorityUpdated()
  1559. event.stream_id = frame.stream_id
  1560. event.depends_on = frame.depends_on
  1561. event.exclusive = frame.exclusive
  1562. # Weight is an integer between 1 and 256, but the byte only allows
  1563. # 0 to 255: add one.
  1564. event.weight = frame.stream_weight + 1
  1565. # A stream may not depend on itself.
  1566. if event.depends_on == frame.stream_id:
  1567. raise ProtocolError(
  1568. "Stream %d may not depend on itself" % frame.stream_id
  1569. )
  1570. events.append(event)
  1571. return [], events
  1572. def _receive_goaway_frame(self, frame):
  1573. """
  1574. Receive a GOAWAY frame on the connection.
  1575. """
  1576. events = self.state_machine.process_input(
  1577. ConnectionInputs.RECV_GOAWAY
  1578. )
  1579. # Clear the outbound data buffer: we cannot send further data now.
  1580. self.clear_outbound_data_buffer()
  1581. # Fire an appropriate ConnectionTerminated event.
  1582. new_event = ConnectionTerminated()
  1583. new_event.error_code = _error_code_from_int(frame.error_code)
  1584. new_event.last_stream_id = frame.last_stream_id
  1585. new_event.additional_data = (frame.additional_data
  1586. if frame.additional_data else None)
  1587. events.append(new_event)
  1588. return [], events
  1589. def _receive_naked_continuation(self, frame):
  1590. """
  1591. A naked CONTINUATION frame has been received. This is always an error,
  1592. but the type of error it is depends on the state of the stream and must
  1593. transition the state of the stream, so we need to pass it to the
  1594. appropriate stream.
  1595. """
  1596. stream = self._get_stream_by_id(frame.stream_id)
  1597. stream.receive_continuation()
  1598. assert False, "Should not be reachable"
  1599. def _receive_alt_svc_frame(self, frame):
  1600. """
  1601. An ALTSVC frame has been received. This frame, specified in RFC 7838,
  1602. is used to advertise alternative places where the same service can be
  1603. reached.
  1604. This frame can optionally be received either on a stream or on stream
  1605. 0, and its semantics are different in each case.
  1606. """
  1607. events = self.state_machine.process_input(
  1608. ConnectionInputs.RECV_ALTERNATIVE_SERVICE
  1609. )
  1610. frames = []
  1611. if frame.stream_id:
  1612. # Given that it makes no sense to receive ALTSVC on a stream
  1613. # before that stream has been opened with a HEADERS frame, the
  1614. # ALTSVC frame cannot create a stream. If the stream is not
  1615. # present, we simply ignore the frame.
  1616. try:
  1617. stream = self._get_stream_by_id(frame.stream_id)
  1618. except (NoSuchStreamError, StreamClosedError):
  1619. pass
  1620. else:
  1621. stream_frames, stream_events = stream.receive_alt_svc(frame)
  1622. frames.extend(stream_frames)
  1623. events.extend(stream_events)
  1624. else:
  1625. # This frame is sent on stream 0. The origin field on the frame
  1626. # must be present, though if it isn't it's not a ProtocolError
  1627. # (annoyingly), we just need to ignore it.
  1628. if not frame.origin:
  1629. return frames, events
  1630. # If we're a server, we want to ignore this (RFC 7838 says so).
  1631. if not self.config.client_side:
  1632. return frames, events
  1633. event = AlternativeServiceAvailable()
  1634. event.origin = frame.origin
  1635. event.field_value = frame.field
  1636. events.append(event)
  1637. return frames, events
  1638. def _receive_unknown_frame(self, frame):
  1639. """
  1640. We have received a frame that we do not understand. This is almost
  1641. certainly an extension frame, though it's impossible to be entirely
  1642. sure.
  1643. RFC 7540 § 5.5 says that we MUST ignore unknown frame types: so we
  1644. do.
  1645. """
  1646. # All we do here is log.
  1647. self.config.logger.debug(
  1648. "Received unknown extension frame (ID %d)", frame.stream_id
  1649. )
  1650. return [], []
  1651. def _local_settings_acked(self):
  1652. """
  1653. Handle the local settings being ACKed, update internal state.
  1654. """
  1655. changes = self.local_settings.acknowledge()
  1656. if SettingCodes.INITIAL_WINDOW_SIZE in changes:
  1657. setting = changes[SettingCodes.INITIAL_WINDOW_SIZE]
  1658. self._inbound_flow_control_change_from_settings(
  1659. setting.original_value,
  1660. setting.new_value,
  1661. )
  1662. if SettingCodes.MAX_HEADER_LIST_SIZE in changes:
  1663. setting = changes[SettingCodes.MAX_HEADER_LIST_SIZE]
  1664. self.decoder.max_header_list_size = setting.new_value
  1665. if SettingCodes.MAX_FRAME_SIZE in changes:
  1666. setting = changes[SettingCodes.MAX_FRAME_SIZE]
  1667. self.max_inbound_frame_size = setting.new_value
  1668. if SettingCodes.HEADER_TABLE_SIZE in changes:
  1669. setting = changes[SettingCodes.HEADER_TABLE_SIZE]
  1670. # This is safe across all hpack versions: some versions just won't
  1671. # respect it.
  1672. self.decoder.max_allowed_table_size = setting.new_value
  1673. return changes
  1674. def _stream_id_is_outbound(self, stream_id):
  1675. """
  1676. Returns ``True`` if the stream ID corresponds to an outbound stream
  1677. (one initiated by this peer), returns ``False`` otherwise.
  1678. """
  1679. return (stream_id % 2 == int(self.config.client_side))
  1680. def _stream_closed_by(self, stream_id):
  1681. """
  1682. Returns how the stream was closed.
  1683. The return value will be either a member of
  1684. ``h2.stream.StreamClosedBy`` or ``None``. If ``None``, the stream was
  1685. closed implicitly by the peer opening a stream with a higher stream ID
  1686. before opening this one.
  1687. """
  1688. if stream_id in self.streams:
  1689. return self.streams[stream_id].closed_by
  1690. if stream_id in self._closed_streams:
  1691. return self._closed_streams[stream_id]
  1692. return None
  1693. def _stream_is_closed_by_reset(self, stream_id):
  1694. """
  1695. Returns ``True`` if the stream was closed by sending or receiving a
  1696. RST_STREAM frame. Returns ``False`` otherwise.
  1697. """
  1698. return self._stream_closed_by(stream_id) in (
  1699. StreamClosedBy.RECV_RST_STREAM, StreamClosedBy.SEND_RST_STREAM
  1700. )
  1701. def _stream_is_closed_by_end(self, stream_id):
  1702. """
  1703. Returns ``True`` if the stream was closed by sending or receiving an
  1704. END_STREAM flag in a HEADERS or DATA frame. Returns ``False``
  1705. otherwise.
  1706. """
  1707. return self._stream_closed_by(stream_id) in (
  1708. StreamClosedBy.RECV_END_STREAM, StreamClosedBy.SEND_END_STREAM
  1709. )
  1710. def _add_frame_priority(frame, weight=None, depends_on=None, exclusive=None):
  1711. """
  1712. Adds priority data to a given frame. Does not change any flags set on that
  1713. frame: if the caller is adding priority information to a HEADERS frame they
  1714. must set that themselves.
  1715. This method also deliberately sets defaults for anything missing.
  1716. This method validates the input values.
  1717. """
  1718. # A stream may not depend on itself.
  1719. if depends_on == frame.stream_id:
  1720. raise ProtocolError(
  1721. "Stream %d may not depend on itself" % frame.stream_id
  1722. )
  1723. # Weight must be between 1 and 256.
  1724. if weight is not None:
  1725. if weight > 256 or weight < 1:
  1726. raise ProtocolError(
  1727. "Weight must be between 1 and 256, not %d" % weight
  1728. )
  1729. else:
  1730. # Weight is an integer between 1 and 256, but the byte only allows
  1731. # 0 to 255: subtract one.
  1732. weight -= 1
  1733. # Set defaults for anything not provided.
  1734. weight = weight if weight is not None else 15
  1735. depends_on = depends_on if depends_on is not None else 0
  1736. exclusive = exclusive if exclusive is not None else False
  1737. frame.stream_weight = weight
  1738. frame.depends_on = depends_on
  1739. frame.exclusive = exclusive
  1740. return frame
  1741. def _decode_headers(decoder, encoded_header_block):
  1742. """
  1743. Decode a HPACK-encoded header block, translating HPACK exceptions into
  1744. sensible hyper-h2 errors.
  1745. This only ever returns bytestring headers: hyper-h2 may emit them as
  1746. unicode later, but internally it processes them as bytestrings only.
  1747. """
  1748. try:
  1749. return decoder.decode(encoded_header_block, raw=True)
  1750. except OversizedHeaderListError as e:
  1751. # This is a symptom of a HPACK bomb attack: the user has
  1752. # disregarded our requirements on how large a header block we'll
  1753. # accept.
  1754. raise DenialOfServiceError("Oversized header block: %s" % e)
  1755. except (HPACKError, IndexError, TypeError, UnicodeDecodeError) as e:
  1756. # We should only need HPACKError here, but versions of HPACK older
  1757. # than 2.1.0 throw all three others as well. For maximum
  1758. # compatibility, catch all of them.
  1759. raise ProtocolError("Error decoding header block: %s" % e)