aboutsummaryrefslogtreecommitdiffstats
path: root/libmproxy/protocol/rawtcp.py
blob: 9b155412acb60530bc8511f123fbb73efeedb2d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from __future__ import (absolute_import, print_function, division)
import socket
import select
import six
import sys

from OpenSSL import SSL

from netlib.tcp import NetLibError, ssl_read_select
from netlib.utils import cleanBin
from ..exceptions import ProtocolException
from .base import Layer


class RawTCPLayer(Layer):
    chunk_size = 4096

    def __init__(self, ctx, logging=True):
        self.logging = logging
        super(RawTCPLayer, self).__init__(ctx)

    def __call__(self):
        self.connect()

        buf = memoryview(bytearray(self.chunk_size))

        client = self.client_conn.connection
        server = self.server_conn.connection
        conns = [client, server]

        try:
            while True:
                r = ssl_read_select(conns, 10)
                for conn in r:
                    dst = server if conn == client else client

                    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:
                            dst.shutdown(socket.SHUT_WR)

                        if len(conns) == 0:
                            return
                        continue

                    dst.sendall(buf[:size])

                    if self.logging:
                        # log messages are prepended with the client address,
                        # hence the "weird" direction string.
                        if dst == server:
                            direction = "-> tcp -> {}".format(repr(self.server_conn.address))
                        else:
                            direction = "<- tcp <- {}".format(repr(self.server_conn.address))
                        data = cleanBin(buf[:size].tobytes())
                        self.log(
                            "{}\r\n{}".format(direction, data),
                            "info"
                        )

        except (socket.error, NetLibError, SSL.Error) as e:
            six.reraise(
                ProtocolException,
                ProtocolException("TCP connection closed unexpectedly: {}".format(repr(e))),
                sys.exc_info()[2]
            )