mitmproxy/libmproxy/protocol2/rawtcp.py

67 lines
2.4 KiB
Python
Raw Normal View History

from __future__ import (absolute_import, print_function, division)
2015-08-29 21:08:16 +00:00
import socket
import select
from OpenSSL import SSL
2015-08-14 08:41:11 +00:00
from ..exceptions import ProtocolException
2015-08-29 21:08:16 +00:00
from netlib.tcp import NetLibError
from netlib.utils import cleanBin
2015-07-24 16:29:13 +00:00
from ..protocol.tcp import TCPHandler
2015-07-25 11:31:55 +00:00
from .layer import Layer
2015-07-24 16:29:13 +00:00
2015-08-14 08:41:11 +00:00
class RawTcpLayer(Layer):
2015-08-29 21:08:16 +00:00
chunk_size = 4096
def __init__(self, ctx, logging=True):
self.logging = logging
super(RawTcpLayer, self).__init__(ctx)
2015-07-24 16:29:13 +00:00
def __call__(self):
2015-08-18 13:59:44 +00:00
self.connect()
2015-08-29 21:08:16 +00:00
buf = memoryview(bytearray(self.chunk_size))
client = self.client_conn.connection
server = self.server_conn.connection
conns = [client, server]
try:
2015-08-29 21:08:16 +00:00
while True:
r, _, _ = select.select(conns, [], [], 10)
for conn in r:
size = conn.recv_into(buf, self.chunk_size)
if not size:
conns.remove(conn)
# Shutdown connection to the other peer
if isinstance(conn, SSL.Connection):
# We can't half-close a connection, so we just close everything here.
# Sockets will be cleaned up on a higher level.
return
else:
conn.shutdown(socket.SHUT_WR)
if len(conns) == 0:
return
continue
dst = server if conn == client else client
dst.sendall(buf[:size])
2015-08-29 21:08:16 +00:00
if self.logging:
# log messages are prepended with the client address,
# hence the "weird" direction string.
if dst == server:
direction = "-> tcp -> {!r}".format(self.server_conn.address)
else:
direction = "<- tcp <- {!r}".format(self.server_conn.address)
data = cleanBin(buf[:size].tobytes())
self.log(
"{}\r\n{}".format(direction, data),
"info"
)
2015-07-24 16:29:13 +00:00
2015-08-29 21:08:16 +00:00
except (socket.error, NetLibError, SSL.Error) as e:
raise ProtocolException("TCP connection closed unexpectedly: {}".format(repr(e)), e)