summaryrefslogtreecommitdiff
path: root/proxy.py
blob: 5be43878e0b914e33a34d801fe350c0cd143ad9c (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/python -t
import pwd, os, sys, logging, logging.handlers, string, time
import asynchat, asyncore, socket, httplib, urlparse
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO


ENDPOINTS = [
    ('10.2.2.11', 8888),
    ('10.3.1.2', 8888),
    ('10.1.1.156', 8888),
]

#minimum entity size to start a paralel fetch
KB = 1024
MINIMAL_SIZE = 512 * KB
BLOCKSIZE_FETCH = 2048 * KB
BLOCKSIZE_STEP = 512 * KB

class Fetcher(asynchat.async_chat):
    def __init__(self, reader, endpoint, url, header, range):
        self.reader = reader
        self.proxy = ENDPOINTS(endpoint)
        self.url = url
        self.header = self.header
        self.range = range

        self.start_time = time.time()
        self.endpoint = endpoint

        self.pos = range[0]
        asynchat.async_chat.__init__(self)
        self.set_terminator("\r\n")
        self.http_status = ""
        self.http_header = ""
        self.state = 0 #0=status, 1=header, 2=body
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect(proxy)

    #XXXshould include original request headers
    def handle_connect (self):
        print self,"handle_connect"
        self.send("GET http://%s:%s%s HTTP/1.0\r\n" % ( self.url.hostname, self.url.port or 80, self.url.path ))
        #XXX self.header
        self.send("Range: bytes=%s-%s\r\n" % (self.range[0], self.range[1]))
        self.send("\r\n")
    
    def time(self):
        return self.stop_time - self.start_time

    def collect_incoming_data(self, data):
        if self.state==2: #body
            self.reader.handle_incoming_data(self.pos, data)
            self.pos += len(data)
            if self.pos >= self.range[1]: 
                self.stop_time = time.time()
                self.start_fetcher(endpoint, self.time())
                print self, "finished"
                self.close_when_done()
        elif self.state ==1: #header
            self.http_header += data
        else: #status
            self.http_status += data

    def found_terminator(self):
        if self.state == 0:
            self.state = 1
            self.set_terminator("\r\n\r\n")
            #print "got status line"
        elif self.state == 1:
            self.state = 2
            self.set_terminator(None)
            print self, "header ends now"
            self.reader.handle_incoming_http_header(self.http_header)

    def __str__(self):
        return "<Fetcher proxy=%s url=%s range=%s" % (self.proxy, self.url, self.range)

class MultipleProxyReader(object):
    def __init__(self, channel, url, header, content_length):
        print "MultipleProxyReader url=%s content_length=%s" % (url, content_length)
        self.channel = channel
        self.url = url
        self.header = header
        self.content_length = content_length

        self.header_sent = False
        self.fetch_pos = 0
        self.write_pos = 0
        self.buffer = ""
        self.blocks = dict()

        for i in range(0,len(ENDPOINTS)):
            self.endpoints_time.append(1)
            self.endpoints_blocksize.append(BLOCKSIZE_FETCH)
        
        for i in range(0,len(ENDPOINTS)):
            self.start_fetcher(i,1)

    def handle_incoming_data(self, pos, data):
        self.blocks[pos] = data

        while self.find_next_data():
            pass

    def handle_incoming_http_header(self, header):
        if self.header_sent:
            pass
        else:
            self.header_sent = True

            self.channel.push("HTTP/1.0 200 OK\r\n")
            # Sends header from first response
            headers = httplib.HTTPMessage(StringIO.StringIO(header))
            for key in filter(lambda k: k not in ("content-range", "content-length"), headers.dict.keys()):
                self.channel.push("%s: %s\r\n" % (key, headers.dict[key]))
            self.channel.push("Content-Length: %s" % self.content_length)
            self.channel.push("X-Proxy: Magicproxy (superpower activated)\r\n")
            self.channel.push("\r\n")

    def start_fetcher(self,endpoint,time):
        self.find_next_data()
      
        self.endpoints_time[endpoint] = time
        if max(self.endpoints_times[endpoint]) == time:
            self.endpoint_blocksize[endpoint] += BLOCKSIZE_STEP
        elif min(self.endpoints_times[endpoint]) == time:
            self.endpoint_blocksize[endpoint] -= BLOCKSIZE_STEP

        if self.fetch_pos +1 <self.content_length:
            print self, "start new fetcher"
            start = self.fetch_pos
            if self.fetch_pos+self.endpoint_blocksize[endpoint] < self.content_length:
                self.fetch_pos += self.endpoint_blocksize[endpoint]
            else:
                self.fetch_pos = self.content_length
            range = (start, self.fetch_pos-1)
            Fetcher(self, ENDPOINTS[endpoint], self.url, self.header, range, self.content_length)

    def find_next_data(self):
        if not self.channel.writeable(): # request-side closed the connection
            self.channel.close_when_done()
            #XXX terminate all running fetcher
            return False

        #print self, "expect at %s" % self.write_pos, self.blocks.keys()
        if self.write_pos in self.blocks.keys():
            r=True
            data = self.blocks.pop(self.write_pos)
            self.channel.push(data)
            self.write_pos += len(data)
            return True

        if self.write_pos + 1 >= self.content_length:
            print self, "job done"
            self.channel.close_when_done()

        return False

    def __str__(self):
        return "<MultipleProxyReader >"

class HTTPChannel(asynchat.async_chat):
    def __init__(self, server, sock, addr):
        asynchat.async_chat.__init__(self, sock)
        self.server = server
        self.set_terminator("\r\n\r\n")
        self.request = None
        self.data = StringIO.StringIO()

    def collect_incoming_data(self, data):
        self.data.write(data)
        if self.data.tell() > 16384:
            self.close_when_done()

    def found_terminator(self):
        if not self.request:
            # parse http header
            self.data.seek(0)
            self.request = string.split(self.data.readline(), None, 2)
            if len(self.request) != 3:
                # badly formed request; just shut down
                self.close_when_done()
            else:
                self.server.handle_request(self, self.request[0], self.request[1])
        else:
            pass # ignore body data, for now

class HTTPProxyServer(asyncore.dispatcher):
    def __init__(self):
        asyncore.dispatcher.__init__(self)
        self.port = 8080
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind(("", 8080))
        self.listen(5)

    def handle_accept(self):
        conn, addr = self.accept()
        HTTPChannel(self, conn, addr)

    def handle_request(self, channel, method, path):
        url = urlparse.urlparse(path)
        print method, path
        if method != "GET" or url.query != "":
            print "non-GET or query, bypass"
            #do not handle non-GET or GET with Query (?foo=bla) requests
            return self._bypass_request(channel, method, url)

        #check for content-length header with a HEAD request
        conn = httplib.HTTPConnection(url.hostname, url.port or 80)
        conn.request("HEAD", url.path)
        resp = conn.getresponse()
        content_length = filter(lambda it: it[0] == "content-length", resp.getheaders())
        if len( content_length ) == 0:
            # no content length given, bypass this request
            print "missing content-length, bypass"
            self._bypass_request(channel, "GET", url)
        else:
            content_length = int(content_length[0][1])
            ##XXX
            header = (("foo", "bla"))
            MultipleProxyReader(channel, url, header, content_length)
        
    def _bypass_request(self, channel, method, url):
        print "_bypass request hostname=%s port=%s path=%s" % (url.hostname, url.port or 80, url.path)
        #XXX hier sollte nicht proxy gespielt werden sondern
        #die daten 1-zu-1 durchgereicht werden.
        #Weiterhin sollte sichergestellt werden, dass die requests
        #zu Host X1 immer ueber Proxy Y1 geroutet werden
        # etwa proxy=proxies[ stuff(hostname) % len(proxies) ]
        conn = httplib.HTTPConnection(url.hostname, url.port or 80)
        conn.request(method, url.path)
        resp = conn.getresponse()
        channel.push("HTTP/1.0 200 OK\r\nX-Proxy: Magicproxy (superpower disabled)\r\n")
        channel.push( "\r\n".join(map(lambda k: "%s: %s" % (k[0],k[1]), resp.getheaders())) )
        channel.push("\r\n\r\n")
        channel.push(resp.read())
        channel.close_when_done()

if __name__ == "__main__":
    proxy = HTTPProxyServer()
    asyncore.loop()