frame.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. # -*- coding: utf-8 -*-
  2. """
  3. hyperframe/frame
  4. ~~~~~~~~~~~~~~~~
  5. Defines framing logic for HTTP/2. Provides both classes to represent framed
  6. data and logic for aiding the connection when it comes to reading from the
  7. socket.
  8. """
  9. import collections
  10. import struct
  11. import binascii
  12. from .exceptions import (
  13. UnknownFrameError, InvalidPaddingError, InvalidFrameError
  14. )
  15. from .flags import Flag, Flags
  16. # The maximum initial length of a frame. Some frames have shorter maximum lengths.
  17. FRAME_MAX_LEN = (2 ** 14)
  18. # The maximum allowed length of a frame.
  19. FRAME_MAX_ALLOWED_LEN = (2 ** 24) - 1
  20. class Frame(object):
  21. """
  22. The base class for all HTTP/2 frames.
  23. """
  24. #: The flags defined on this type of frame.
  25. defined_flags = []
  26. #: The byte used to define the type of the frame.
  27. type = None
  28. # If 'has-stream', the frame's stream_id must be non-zero. If 'no-stream',
  29. # it must be zero. If 'either', it's not checked.
  30. stream_association = None
  31. def __init__(self, stream_id, flags=()):
  32. #: The stream identifier for the stream this frame was received on.
  33. #: Set to 0 for frames sent on the connection (stream-id 0).
  34. self.stream_id = stream_id
  35. #: The flags set for this frame.
  36. self.flags = Flags(self.defined_flags)
  37. #: The frame length, excluding the nine-byte header.
  38. self.body_len = 0
  39. for flag in flags:
  40. self.flags.add(flag)
  41. if self.stream_association == 'has-stream' and not self.stream_id:
  42. raise ValueError('Stream ID must be non-zero')
  43. if self.stream_association == 'no-stream' and self.stream_id:
  44. raise ValueError('Stream ID must be zero')
  45. def __repr__(self):
  46. flags = ", ".join(self.flags) or "None"
  47. body = binascii.hexlify(self.serialize_body()).decode('ascii')
  48. if len(body) > 20:
  49. body = body[:20] + "..."
  50. return (
  51. "{type}(Stream: {stream}; Flags: {flags}): {body}"
  52. ).format(type=type(self).__name__, stream=self.stream_id, flags=flags, body=body)
  53. @staticmethod
  54. def parse_frame_header(header):
  55. """
  56. Takes a 9-byte frame header and returns a tuple of the appropriate
  57. Frame object and the length that needs to be read from the socket.
  58. This populates the flags field, and determines how long the body is.
  59. :raises hyperframe.exceptions.UnknownFrameError: If a frame of unknown
  60. type is received.
  61. """
  62. try:
  63. fields = struct.unpack("!HBBBL", header)
  64. except struct.error:
  65. raise InvalidFrameError("Invalid frame header")
  66. # First 24 bits are frame length.
  67. length = (fields[0] << 8) + fields[1]
  68. type = fields[2]
  69. flags = fields[3]
  70. stream_id = fields[4]
  71. if type not in FRAMES:
  72. raise UnknownFrameError(type, length)
  73. frame = FRAMES[type](stream_id)
  74. frame.parse_flags(flags)
  75. return (frame, length)
  76. def parse_flags(self, flag_byte):
  77. for flag, flag_bit in self.defined_flags:
  78. if flag_byte & flag_bit:
  79. self.flags.add(flag)
  80. return self.flags
  81. def serialize(self):
  82. """
  83. Convert a frame into a bytestring, representing the serialized form of
  84. the frame.
  85. """
  86. body = self.serialize_body()
  87. self.body_len = len(body)
  88. # Build the common frame header.
  89. # First, get the flags.
  90. flags = 0
  91. for flag, flag_bit in self.defined_flags:
  92. if flag in self.flags:
  93. flags |= flag_bit
  94. header = struct.pack(
  95. "!HBBBL",
  96. (self.body_len & 0xFFFF00) >> 8, # Length is spread over top 24 bits
  97. self.body_len & 0x0000FF,
  98. self.type,
  99. flags,
  100. self.stream_id & 0x7FFFFFFF # Stream ID is 32 bits.
  101. )
  102. return header + body
  103. def serialize_body(self):
  104. raise NotImplementedError()
  105. def parse_body(self, data):
  106. """
  107. Given the body of a frame, parses it into frame data. This populates
  108. the non-header parts of the frame: that is, it does not populate the
  109. stream ID or flags.
  110. :param data: A memoryview object containing the body data of the frame.
  111. Must not contain *more* data than the length returned by
  112. :meth:`parse_frame_header
  113. <hyperframe.frame.Frame.parse_frame_header>`.
  114. """
  115. raise NotImplementedError()
  116. class Padding(object):
  117. """
  118. Mixin for frames that contain padding. Defines extra fields that can be
  119. used and set by frames that can be padded.
  120. """
  121. def __init__(self, stream_id, pad_length=0, **kwargs):
  122. super(Padding, self).__init__(stream_id, **kwargs)
  123. #: The length of the padding to use.
  124. self.pad_length = pad_length
  125. def serialize_padding_data(self):
  126. if 'PADDED' in self.flags:
  127. return struct.pack('!B', self.pad_length)
  128. return b''
  129. def parse_padding_data(self, data):
  130. if 'PADDED' in self.flags:
  131. try:
  132. self.pad_length = struct.unpack('!B', data[:1])[0]
  133. except struct.error:
  134. raise InvalidFrameError("Invalid Padding data")
  135. return 1
  136. return 0
  137. @property
  138. def total_padding(self):
  139. return self.pad_length
  140. class Priority(object):
  141. """
  142. Mixin for frames that contain priority data. Defines extra fields that can
  143. be used and set by frames that contain priority data.
  144. """
  145. def __init__(self, stream_id, depends_on=0x0, stream_weight=0x0, exclusive=False, **kwargs):
  146. super(Priority, self).__init__(stream_id, **kwargs)
  147. #: The stream ID of the stream on which this stream depends.
  148. self.depends_on = depends_on
  149. #: The weight of the stream. This is an integer between 0 and 256.
  150. self.stream_weight = stream_weight
  151. #: Whether the exclusive bit was set.
  152. self.exclusive = exclusive
  153. def serialize_priority_data(self):
  154. return struct.pack(
  155. "!LB",
  156. self.depends_on | (int(self.exclusive) << 31),
  157. self.stream_weight
  158. )
  159. def parse_priority_data(self, data):
  160. MASK = 0x80000000
  161. try:
  162. self.depends_on, self.stream_weight = struct.unpack(
  163. "!LB", data[:5]
  164. )
  165. except struct.error:
  166. raise InvalidFrameError("Invalid Priority data")
  167. self.exclusive = bool(self.depends_on & MASK)
  168. self.depends_on &= ~MASK
  169. return 5
  170. class DataFrame(Padding, Frame):
  171. """
  172. DATA frames convey arbitrary, variable-length sequences of octets
  173. associated with a stream. One or more DATA frames are used, for instance,
  174. to carry HTTP request or response payloads.
  175. """
  176. #: The flags defined for DATA frames.
  177. defined_flags = [
  178. Flag('END_STREAM', 0x01),
  179. Flag('PADDED', 0x08),
  180. ]
  181. #: The type byte for data frames.
  182. type = 0x0
  183. stream_association = 'has-stream'
  184. def __init__(self, stream_id, data=b'', **kwargs):
  185. super(DataFrame, self).__init__(stream_id, **kwargs)
  186. #: The data contained on this frame.
  187. self.data = data
  188. def serialize_body(self):
  189. padding_data = self.serialize_padding_data()
  190. padding = b'\0' * self.total_padding
  191. return b''.join([padding_data, self.data, padding])
  192. def parse_body(self, data):
  193. padding_data_length = self.parse_padding_data(data)
  194. self.data = data[padding_data_length:len(data)-self.total_padding].tobytes()
  195. self.body_len = len(data)
  196. if self.total_padding and self.total_padding >= self.body_len:
  197. raise InvalidPaddingError("Padding is too long.")
  198. @property
  199. def flow_controlled_length(self):
  200. """
  201. The length of the frame that needs to be accounted for when considering
  202. flow control.
  203. """
  204. padding_len = self.total_padding + 1 if self.total_padding else 0
  205. return len(self.data) + padding_len
  206. class PriorityFrame(Priority, Frame):
  207. """
  208. The PRIORITY frame specifies the sender-advised priority of a stream. It
  209. can be sent at any time for an existing stream. This enables
  210. reprioritisation of existing streams.
  211. """
  212. #: The flags defined for PRIORITY frames.
  213. defined_flags = []
  214. #: The type byte defined for PRIORITY frames.
  215. type = 0x02
  216. stream_association = 'has-stream'
  217. def serialize_body(self):
  218. return self.serialize_priority_data()
  219. def parse_body(self, data):
  220. self.parse_priority_data(data)
  221. self.body_len = len(data)
  222. class RstStreamFrame(Frame):
  223. """
  224. The RST_STREAM frame allows for abnormal termination of a stream. When sent
  225. by the initiator of a stream, it indicates that they wish to cancel the
  226. stream or that an error condition has occurred. When sent by the receiver
  227. of a stream, it indicates that either the receiver is rejecting the stream,
  228. requesting that the stream be cancelled or that an error condition has
  229. occurred.
  230. """
  231. #: The flags defined for RST_STREAM frames.
  232. defined_flags = []
  233. #: The type byte defined for RST_STREAM frames.
  234. type = 0x03
  235. stream_association = 'has-stream'
  236. def __init__(self, stream_id, error_code=0, **kwargs):
  237. super(RstStreamFrame, self).__init__(stream_id, **kwargs)
  238. #: The error code used when resetting the stream.
  239. self.error_code = error_code
  240. def serialize_body(self):
  241. return struct.pack("!L", self.error_code)
  242. def parse_body(self, data):
  243. if len(data) != 4:
  244. raise InvalidFrameError(
  245. "RST_STREAM must have 4 byte body: actual length %s." %
  246. len(data)
  247. )
  248. try:
  249. self.error_code = struct.unpack("!L", data)[0]
  250. except struct.error: # pragma: no cover
  251. raise InvalidFrameError("Invalid RST_STREAM body")
  252. self.body_len = len(data)
  253. class SettingsFrame(Frame):
  254. """
  255. The SETTINGS frame conveys configuration parameters that affect how
  256. endpoints communicate. The parameters are either constraints on peer
  257. behavior or preferences.
  258. Settings are not negotiated. Settings describe characteristics of the
  259. sending peer, which are used by the receiving peer. Different values for
  260. the same setting can be advertised by each peer. For example, a client
  261. might set a high initial flow control window, whereas a server might set a
  262. lower value to conserve resources.
  263. """
  264. #: The flags defined for SETTINGS frames.
  265. defined_flags = [Flag('ACK', 0x01)]
  266. #: The type byte defined for SETTINGS frames.
  267. type = 0x04
  268. stream_association = 'no-stream'
  269. # We need to define the known settings, they may as well be class
  270. # attributes.
  271. #: The byte that signals the SETTINGS_HEADER_TABLE_SIZE setting.
  272. HEADER_TABLE_SIZE = 0x01
  273. #: The byte that signals the SETTINGS_ENABLE_PUSH setting.
  274. ENABLE_PUSH = 0x02
  275. #: The byte that signals the SETTINGS_MAX_CONCURRENT_STREAMS setting.
  276. MAX_CONCURRENT_STREAMS = 0x03
  277. #: The byte that signals the SETTINGS_INITIAL_WINDOW_SIZE setting.
  278. INITIAL_WINDOW_SIZE = 0x04
  279. #: The byte that signals the SETTINGS_MAX_FRAME_SIZE setting.
  280. MAX_FRAME_SIZE = 0x05
  281. #: The byte that signals the SETTINGS_MAX_HEADER_LIST_SIZE setting.
  282. MAX_HEADER_LIST_SIZE = 0x06
  283. #: The byte that signals the SETTINGS_MAX_FRAME_SIZE setting.
  284. #: .. deprecated:: 3.2.0
  285. #: Use :data:`MAX_FRAME_SIZE <SettingsFrame.MAX_FRAME_SIZE>` instead.
  286. SETTINGS_MAX_FRAME_SIZE = MAX_FRAME_SIZE
  287. #: The byte that signals the SETTINGS_MAX_HEADER_LIST_SIZE setting.
  288. #: .. deprecated:: 3.2.0
  289. # Use :data:`MAX_HEADER_LIST_SIZE <SettingsFrame.MAX_HEADER_LIST_SIZE>` instead.
  290. SETTINGS_MAX_HEADER_LIST_SIZE = MAX_HEADER_LIST_SIZE
  291. def __init__(self, stream_id=0, settings=None, **kwargs):
  292. super(SettingsFrame, self).__init__(stream_id, **kwargs)
  293. if settings and "ACK" in kwargs.get("flags", ()):
  294. raise ValueError("Settings must be empty if ACK flag is set.")
  295. #: A dictionary of the setting type byte to the value of the setting.
  296. self.settings = settings or {}
  297. def serialize_body(self):
  298. settings = [struct.pack("!HL", setting & 0xFF, value)
  299. for setting, value in self.settings.items()]
  300. return b''.join(settings)
  301. def parse_body(self, data):
  302. for i in range(0, len(data), 6):
  303. try:
  304. name, value = struct.unpack("!HL", data[i:i+6])
  305. except struct.error:
  306. raise InvalidFrameError("Invalid SETTINGS body")
  307. self.settings[name] = value
  308. self.body_len = len(data)
  309. class PushPromiseFrame(Padding, Frame):
  310. """
  311. The PUSH_PROMISE frame is used to notify the peer endpoint in advance of
  312. streams the sender intends to initiate.
  313. """
  314. #: The flags defined for PUSH_PROMISE frames.
  315. defined_flags = [
  316. Flag('END_HEADERS', 0x04),
  317. Flag('PADDED', 0x08)
  318. ]
  319. #: The type byte defined for PUSH_PROMISE frames.
  320. type = 0x05
  321. stream_association = 'has-stream'
  322. def __init__(self, stream_id, promised_stream_id=0, data=b'', **kwargs):
  323. super(PushPromiseFrame, self).__init__(stream_id, **kwargs)
  324. #: The stream ID that is promised by this frame.
  325. self.promised_stream_id = promised_stream_id
  326. #: The HPACK-encoded header block for the simulated request on the new
  327. #: stream.
  328. self.data = data
  329. def serialize_body(self):
  330. padding_data = self.serialize_padding_data()
  331. padding = b'\0' * self.total_padding
  332. data = struct.pack("!L", self.promised_stream_id)
  333. return b''.join([padding_data, data, self.data, padding])
  334. def parse_body(self, data):
  335. padding_data_length = self.parse_padding_data(data)
  336. try:
  337. self.promised_stream_id = struct.unpack(
  338. "!L", data[padding_data_length:padding_data_length + 4]
  339. )[0]
  340. except struct.error:
  341. raise InvalidFrameError("Invalid PUSH_PROMISE body")
  342. self.data = data[padding_data_length + 4:].tobytes()
  343. self.body_len = len(data)
  344. if self.total_padding and self.total_padding >= self.body_len:
  345. raise InvalidPaddingError("Padding is too long.")
  346. class PingFrame(Frame):
  347. """
  348. The PING frame is a mechanism for measuring a minimal round-trip time from
  349. the sender, as well as determining whether an idle connection is still
  350. functional. PING frames can be sent from any endpoint.
  351. """
  352. #: The flags defined for PING frames.
  353. defined_flags = [Flag('ACK', 0x01)]
  354. #: The type byte defined for PING frames.
  355. type = 0x06
  356. stream_association = 'no-stream'
  357. def __init__(self, stream_id=0, opaque_data=b'', **kwargs):
  358. super(PingFrame, self).__init__(stream_id, **kwargs)
  359. #: The opaque data sent in this PING frame, as a bytestring.
  360. self.opaque_data = opaque_data
  361. def serialize_body(self):
  362. if len(self.opaque_data) > 8:
  363. raise InvalidFrameError(
  364. "PING frame may not have more than 8 bytes of data, got %s" %
  365. self.opaque_data
  366. )
  367. data = self.opaque_data
  368. data += b'\x00' * (8 - len(self.opaque_data))
  369. return data
  370. def parse_body(self, data):
  371. if len(data) != 8:
  372. raise InvalidFrameError(
  373. "PING frame must have 8 byte length: got %s" % len(data)
  374. )
  375. self.opaque_data = data.tobytes()
  376. self.body_len = len(data)
  377. class GoAwayFrame(Frame):
  378. """
  379. The GOAWAY frame informs the remote peer to stop creating streams on this
  380. connection. It can be sent from the client or the server. Once sent, the
  381. sender will ignore frames sent on new streams for the remainder of the
  382. connection.
  383. """
  384. #: The flags defined for GOAWAY frames.
  385. defined_flags = []
  386. #: The type byte defined for GOAWAY frames.
  387. type = 0x07
  388. stream_association = 'no-stream'
  389. def __init__(self, stream_id=0, last_stream_id=0, error_code=0, additional_data=b'', **kwargs):
  390. super(GoAwayFrame, self).__init__(stream_id, **kwargs)
  391. #: The last stream ID definitely seen by the remote peer.
  392. self.last_stream_id = last_stream_id
  393. #: The error code for connection teardown.
  394. self.error_code = error_code
  395. #: Any additional data sent in the GOAWAY.
  396. self.additional_data = additional_data
  397. def serialize_body(self):
  398. data = struct.pack(
  399. "!LL",
  400. self.last_stream_id & 0x7FFFFFFF,
  401. self.error_code
  402. )
  403. data += self.additional_data
  404. return data
  405. def parse_body(self, data):
  406. try:
  407. self.last_stream_id, self.error_code = struct.unpack(
  408. "!LL", data[:8]
  409. )
  410. except struct.error:
  411. raise InvalidFrameError("Invalid GOAWAY body.")
  412. self.body_len = len(data)
  413. if len(data) > 8:
  414. self.additional_data = data[8:].tobytes()
  415. class WindowUpdateFrame(Frame):
  416. """
  417. The WINDOW_UPDATE frame is used to implement flow control.
  418. Flow control operates at two levels: on each individual stream and on the
  419. entire connection.
  420. Both types of flow control are hop by hop; that is, only between the two
  421. endpoints. Intermediaries do not forward WINDOW_UPDATE frames between
  422. dependent connections. However, throttling of data transfer by any receiver
  423. can indirectly cause the propagation of flow control information toward the
  424. original sender.
  425. """
  426. #: The flags defined for WINDOW_UPDATE frames.
  427. defined_flags = []
  428. #: The type byte defined for WINDOW_UPDATE frames.
  429. type = 0x08
  430. stream_association = 'either'
  431. def __init__(self, stream_id, window_increment=0, **kwargs):
  432. super(WindowUpdateFrame, self).__init__(stream_id, **kwargs)
  433. #: The amount the flow control window is to be incremented.
  434. self.window_increment = window_increment
  435. def serialize_body(self):
  436. return struct.pack("!L", self.window_increment & 0x7FFFFFFF)
  437. def parse_body(self, data):
  438. try:
  439. self.window_increment = struct.unpack("!L", data)[0]
  440. except struct.error:
  441. raise InvalidFrameError("Invalid WINDOW_UPDATE body")
  442. self.body_len = len(data)
  443. class HeadersFrame(Padding, Priority, Frame):
  444. """
  445. The HEADERS frame carries name-value pairs. It is used to open a stream.
  446. HEADERS frames can be sent on a stream in the "open" or "half closed
  447. (remote)" states.
  448. The HeadersFrame class is actually basically a data frame in this
  449. implementation, because of the requirement to control the sizes of frames.
  450. A header block fragment that doesn't fit in an entire HEADERS frame needs
  451. to be followed with CONTINUATION frames. From the perspective of the frame
  452. building code the header block is an opaque data segment.
  453. """
  454. #: The flags defined for HEADERS frames.
  455. defined_flags = [
  456. Flag('END_STREAM', 0x01),
  457. Flag('END_HEADERS', 0x04),
  458. Flag('PADDED', 0x08),
  459. Flag('PRIORITY', 0x20),
  460. ]
  461. #: The type byte defined for HEADERS frames.
  462. type = 0x01
  463. stream_association = 'has-stream'
  464. def __init__(self, stream_id, data=b'', **kwargs):
  465. super(HeadersFrame, self).__init__(stream_id, **kwargs)
  466. #: The HPACK-encoded header block.
  467. self.data = data
  468. def serialize_body(self):
  469. padding_data = self.serialize_padding_data()
  470. padding = b'\0' * self.total_padding
  471. if 'PRIORITY' in self.flags:
  472. priority_data = self.serialize_priority_data()
  473. else:
  474. priority_data = b''
  475. return b''.join([padding_data, priority_data, self.data, padding])
  476. def parse_body(self, data):
  477. padding_data_length = self.parse_padding_data(data)
  478. data = data[padding_data_length:]
  479. if 'PRIORITY' in self.flags:
  480. priority_data_length = self.parse_priority_data(data)
  481. else:
  482. priority_data_length = 0
  483. self.body_len = len(data)
  484. self.data = data[priority_data_length:len(data)-self.total_padding].tobytes()
  485. if self.total_padding and self.total_padding >= self.body_len:
  486. raise InvalidPaddingError("Padding is too long.")
  487. class ContinuationFrame(Frame):
  488. """
  489. The CONTINUATION frame is used to continue a sequence of header block
  490. fragments. Any number of CONTINUATION frames can be sent on an existing
  491. stream, as long as the preceding frame on the same stream is one of
  492. HEADERS, PUSH_PROMISE or CONTINUATION without the END_HEADERS flag set.
  493. Much like the HEADERS frame, hyper treats this as an opaque data frame with
  494. different flags and a different type.
  495. """
  496. #: The flags defined for CONTINUATION frames.
  497. defined_flags = [Flag('END_HEADERS', 0x04),]
  498. #: The type byte defined for CONTINUATION frames.
  499. type = 0x09
  500. stream_association = 'has-stream'
  501. def __init__(self, stream_id, data=b'', **kwargs):
  502. super(ContinuationFrame, self).__init__(stream_id, **kwargs)
  503. #: The HPACK-encoded header block.
  504. self.data = data
  505. def serialize_body(self):
  506. return self.data
  507. def parse_body(self, data):
  508. self.data = data.tobytes()
  509. self.body_len = len(data)
  510. Origin = collections.namedtuple('Origin', ['scheme', 'host', 'port'])
  511. class AltSvcFrame(Frame):
  512. """
  513. The ALTSVC frame is used to advertise alternate services that the current
  514. host, or a different one, can understand.
  515. """
  516. type = 0xA
  517. stream_association = 'no-stream'
  518. def __init__(self, stream_id=0, host=b'', port=0, protocol_id=b'', max_age=0, origin=None, **kwargs):
  519. super(AltSvcFrame, self).__init__(stream_id, **kwargs)
  520. self.host = host
  521. self.port = port
  522. self.protocol_id = protocol_id
  523. self.max_age = max_age
  524. self.origin = origin
  525. def serialize_origin(self):
  526. if self.origin is not None:
  527. if self.origin.port is None:
  528. hostport = self.origin.host
  529. else:
  530. hostport = self.origin.host + b':' + str(self.origin.port).encode('ascii')
  531. return self.origin.scheme + b'://' + hostport
  532. return b''
  533. def parse_origin(self, data):
  534. if len(data) > 0:
  535. data = data.tobytes()
  536. scheme, hostport = data.split(b'://')
  537. host, _, port = hostport.partition(b':')
  538. self.origin = Origin(scheme=scheme, host=host,
  539. port=int(port) if len(port) > 0 else None)
  540. def serialize_body(self):
  541. first = struct.pack("!LHxB", self.max_age, self.port, len(self.protocol_id))
  542. host_length = struct.pack("!B", len(self.host))
  543. return b''.join([first, self.protocol_id, host_length, self.host,
  544. self.serialize_origin()])
  545. def parse_body(self, data):
  546. try:
  547. self.body_len = len(data)
  548. self.max_age, self.port, protocol_id_length = struct.unpack(
  549. "!LHxB", data[:8]
  550. )
  551. pos = 8
  552. self.protocol_id = data[pos:pos+protocol_id_length].tobytes()
  553. pos += protocol_id_length
  554. host_length = struct.unpack("!B", data[pos:pos+1])[0]
  555. pos += 1
  556. self.host = data[pos:pos+host_length].tobytes()
  557. pos += host_length
  558. self.parse_origin(data[pos:])
  559. except (struct.error, ValueError):
  560. raise InvalidFrameError("Invalid ALTSVC frame body.")
  561. class BlockedFrame(Frame):
  562. """
  563. The BLOCKED frame indicates that the sender is unable to send data due to a
  564. closed flow control window.
  565. The BLOCKED frame is used to provide feedback about the performance of flow
  566. control for the purposes of performance tuning and debugging. The BLOCKED
  567. frame can be sent by a peer when flow controlled data cannot be sent due to
  568. the connection- or stream-level flow control. This frame MUST NOT be sent
  569. if there are other reasons preventing data from being sent, either a lack
  570. of available data, or the underlying transport being blocked.
  571. """
  572. type = 0x0B
  573. stream_association = 'both'
  574. defined_flags = []
  575. def serialize_body(self):
  576. return b''
  577. def parse_body(self, data):
  578. pass
  579. _FRAME_CLASSES = [
  580. DataFrame,
  581. HeadersFrame,
  582. PriorityFrame,
  583. RstStreamFrame,
  584. SettingsFrame,
  585. PushPromiseFrame,
  586. PingFrame,
  587. GoAwayFrame,
  588. WindowUpdateFrame,
  589. ContinuationFrame,
  590. AltSvcFrame,
  591. BlockedFrame
  592. ]
  593. #: FRAMES maps the type byte for each frame to the class used to represent that
  594. #: frame.
  595. FRAMES = {cls.type: cls for cls in _FRAME_CLASSES}