mitmproxy/netlib/http2/protocol.py

229 lines
7.3 KiB
Python
Raw Normal View History

from __future__ import (absolute_import, print_function, division)
import itertools
from hpack.hpack import Encoder, Decoder
from .. import utils
from . import frame
class HTTP2Protocol(object):
ERROR_CODES = utils.BiDi(
NO_ERROR=0x0,
PROTOCOL_ERROR=0x1,
INTERNAL_ERROR=0x2,
FLOW_CONTROL_ERROR=0x3,
SETTINGS_TIMEOUT=0x4,
STREAM_CLOSED=0x5,
FRAME_SIZE_ERROR=0x6,
REFUSED_STREAM=0x7,
CANCEL=0x8,
COMPRESSION_ERROR=0x9,
CONNECT_ERROR=0xa,
ENHANCE_YOUR_CALM=0xb,
INADEQUATE_SECURITY=0xc,
HTTP_1_1_REQUIRED=0xd
)
# "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
2015-06-12 12:41:54 +00:00
CLIENT_CONNECTION_PREFACE =\
'505249202a20485454502f322e300d0a0d0a534d0d0a0d0a'.decode('hex')
ALPN_PROTO_H2 = 'h2'
2015-06-15 11:43:23 +00:00
def __init__(self, tcp_handler, is_server=False, dump_frames=False):
2015-06-11 13:38:32 +00:00
self.tcp_handler = tcp_handler
self.is_server = is_server
self.http2_settings = frame.HTTP2_DEFAULT_SETTINGS.copy()
self.current_stream_id = None
self.encoder = Encoder()
self.decoder = Decoder()
2015-06-12 12:41:54 +00:00
self.connection_preface_performed = False
2015-06-15 11:43:23 +00:00
self.dump_frames = dump_frames
def check_alpn(self):
2015-06-11 13:38:32 +00:00
alp = self.tcp_handler.get_alpn_proto_negotiated()
if alp != self.ALPN_PROTO_H2:
raise NotImplementedError(
"HTTP2Protocol can not handle unknown ALP: %s" % alp)
return True
2015-06-15 11:15:06 +00:00
def _receive_settings(self, hide=False):
frm = self.read_frame(hide)
assert isinstance(frm, frame.SettingsFrame)
2015-06-15 11:15:06 +00:00
def _read_settings_ack(self, hide=False):
settings_ack_frame = self.read_frame(hide)
assert isinstance(settings_ack_frame, frame.SettingsFrame)
assert settings_ack_frame.flags & frame.Frame.FLAG_ACK
assert len(settings_ack_frame.settings) == 0
2015-06-12 12:41:54 +00:00
def perform_server_connection_preface(self, force=False):
if force or not self.connection_preface_performed:
self.connection_preface_performed = True
2015-06-11 13:38:32 +00:00
2015-06-12 12:41:54 +00:00
magic_length = len(self.CLIENT_CONNECTION_PREFACE)
magic = self.tcp_handler.rfile.safe_read(magic_length)
assert magic == self.CLIENT_CONNECTION_PREFACE
2015-06-11 13:38:32 +00:00
2015-06-15 11:15:06 +00:00
self.send_frame(frame.SettingsFrame(state=self), hide=True)
self._receive_settings(hide=True)
2015-06-11 13:38:32 +00:00
2015-06-12 12:41:54 +00:00
def perform_client_connection_preface(self, force=False):
if force or not self.connection_preface_performed:
self.connection_preface_performed = True
self.tcp_handler.wfile.write(self.CLIENT_CONNECTION_PREFACE)
2015-06-15 11:15:06 +00:00
self.send_frame(frame.SettingsFrame(state=self), hide=True)
self._receive_settings(hide=True)
2015-06-11 13:38:32 +00:00
def next_stream_id(self):
if self.current_stream_id is None:
2015-06-12 12:41:54 +00:00
if self.is_server:
# servers must use even stream ids
self.current_stream_id = 2
else:
# clients must use odd stream ids
self.current_stream_id = 1
else:
self.current_stream_id += 2
return self.current_stream_id
2015-06-15 11:15:06 +00:00
def send_frame(self, frm, hide=False):
raw_bytes = frm.to_bytes()
2015-06-11 13:38:32 +00:00
self.tcp_handler.wfile.write(raw_bytes)
self.tcp_handler.wfile.flush()
2015-06-15 11:43:23 +00:00
if not hide and self.dump_frames:
2015-06-15 11:15:06 +00:00
print(frm.human_readable(">>"))
2015-06-15 11:15:06 +00:00
def read_frame(self, hide=False):
2015-06-11 13:38:32 +00:00
frm = frame.Frame.from_file(self.tcp_handler.rfile, self)
2015-06-15 11:43:23 +00:00
if not hide and self.dump_frames:
2015-06-15 11:15:06 +00:00
print(frm.human_readable("<<"))
if isinstance(frm, frame.SettingsFrame) and not frm.flags & frame.Frame.FLAG_ACK:
self._apply_settings(frm.settings, hide)
return frm
2015-06-15 11:15:06 +00:00
def _apply_settings(self, settings, hide=False):
for setting, value in settings.items():
old_value = self.http2_settings[setting]
if not old_value:
old_value = '-'
self.http2_settings[setting] = value
2015-06-08 10:21:08 +00:00
self.send_frame(
frame.SettingsFrame(
state=self,
2015-06-15 11:15:06 +00:00
flags=frame.Frame.FLAG_ACK),
hide)
self._read_settings_ack(hide)
def _create_headers(self, headers, stream_id, end_stream=True):
# TODO: implement max frame size checks and sending in chunks
flags = frame.Frame.FLAG_END_HEADERS
if end_stream:
flags |= frame.Frame.FLAG_END_STREAM
header_block_fragment = self.encoder.encode(headers)
2015-06-15 11:15:06 +00:00
frm = frame.HeadersFrame(
state=self,
flags=flags,
stream_id=stream_id,
2015-06-15 11:15:06 +00:00
header_block_fragment=header_block_fragment)
2015-06-15 11:43:23 +00:00
if self.dump_frames:
2015-06-15 11:15:06 +00:00
print(frm.human_readable(">>"))
return [frm.to_bytes()]
def _create_body(self, body, stream_id):
if body is None or len(body) == 0:
return b''
# TODO: implement max frame size checks and sending in chunks
# TODO: implement flow-control window
2015-06-15 11:15:06 +00:00
frm = frame.DataFrame(
state=self,
flags=frame.Frame.FLAG_END_STREAM,
stream_id=stream_id,
2015-06-15 11:15:06 +00:00
payload=body)
2015-06-15 11:43:23 +00:00
if self.dump_frames:
2015-06-15 11:15:06 +00:00
print(frm.human_readable(">>"))
return [frm.to_bytes()]
def create_request(self, method, path, headers=None, body=None):
if headers is None:
headers = []
2015-06-14 17:17:34 +00:00
authority = self.tcp_handler.sni if self.tcp_handler.sni else self.tcp_handler.address.host
headers = [
(b':method', bytes(method)),
(b':path', bytes(path)),
2015-06-14 17:17:34 +00:00
(b':scheme', b'https'),
(b':authority', authority),
] + headers
stream_id = self.next_stream_id()
return list(itertools.chain(
self._create_headers(headers, stream_id, end_stream=(body is None)),
self._create_body(body, stream_id)))
def read_response(self):
2015-06-11 13:38:32 +00:00
headers, body = self._receive_transmission()
return headers[':status'], headers, body
def read_request(self):
return self._receive_transmission()
def _receive_transmission(self):
body_expected = True
header_block_fragment = b''
body = b''
while True:
frm = self.read_frame()
2015-06-12 12:41:54 +00:00
if isinstance(frm, frame.HeadersFrame)\
or isinstance(frm, frame.ContinuationFrame):
header_block_fragment += frm.header_block_fragment
if frm.flags & frame.Frame.FLAG_END_STREAM:
body_expected = False
2015-06-11 13:38:32 +00:00
if frm.flags & frame.Frame.FLAG_END_HEADERS:
break
2015-06-11 13:38:32 +00:00
while body_expected:
frm = self.read_frame()
if isinstance(frm, frame.DataFrame):
body += frm.payload
2015-06-11 13:38:32 +00:00
if frm.flags & frame.Frame.FLAG_END_STREAM:
break
2015-06-14 17:17:34 +00:00
# TODO: implement window update & flow
headers = {}
for header, value in self.decoder.decode(header_block_fragment):
headers[header] = value
2015-06-11 13:38:32 +00:00
return headers, body
2015-06-12 12:41:54 +00:00
def create_response(self, code, headers=None, body=None):
if headers is None:
headers = []
headers = [(b':status', bytes(str(code)))] + headers
stream_id = self.next_stream_id()
return list(itertools.chain(
self._create_headers(headers, stream_id, end_stream=(body is None)),
self._create_body(body, stream_id)))