forked from yinghuocho/ghttproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
287 lines (251 loc) · 9.27 KB
/
server.py
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import logging
import urlparse
import time
from httplib import HTTPConnection
import gevent
from gevent import socket
from gevent.pywsgi import WSGIHandler, WSGIServer
from gevent.pool import Pool
from gevent.event import Event
log = logging.getLogger(__name__)
CHUNKSIZE = 65536
def pipe_socket(client, remote):
def copy(a, b, finish):
while not finish.is_set():
try:
data = a.recv(CHUNKSIZE)
if not data:
break
b.sendall(data)
except:
break
finish.set()
finish = Event()
finish.clear()
threads = [
gevent.spawn(copy, client, remote, finish),
gevent.spawn(copy, remote, client, finish),
]
[t.join() for t in threads]
client.close()
remote.close()
class ProxyHandler(WSGIHandler):
""" override WSGIHandler.handle() to process https proxy
"""
def handle(self):
try:
while self.socket is not None:
self.time_start = time.time()
self.time_finish = 0
result = self.handle_one_request()
if result is None:
break
if result is True:
if self.command == "CONNECT":
break
else:
continue
self.status, response_body = result
self.socket.sendall(response_body)
if self.time_finish == 0:
self.time_finish = time.time()
self.log_request()
break
if self.socket and hasattr(self, 'command') and \
self.command == "CONNECT" and self.environ.get('__ghttproxy.tunnelconn', None):
pipe_socket(self.socket, self.environ.get('__ghttproxy.tunnelconn'))
finally:
if self.socket is not None:
try:
try:
self.socket._sock.recv(16384)
finally:
self.socket._sock.close()
self.socket.close()
except socket.error: # @UndefinedVariable
pass
self.__dict__.pop('socket', None)
self.__dict__.pop('rfile', None)
""" override WSGIHandler.get_environ() to pass raw headers and raw path to environ
"""
def get_environ(self):
env = super(ProxyHandler, self).get_environ()
env['__ghttproxy.rawheaders'] = self.headers.headers
env['PATH_INFO'] = self.path.split('?', 1)[0]
return env
# some of below code are copied and modifed from "meek/wsgi/reflect.py"
# at https://git.torproject.org/pluggable-transports/meek.git
# Limits a file-like object to reading only n bytes. Used to keep limit
# wsgi.input to the Content-Length, otherwise it blocks.
class LimitedReader(object):
def __init__(self, f, n):
self.f = f
self.n = n
def __getattr__(self, name):
return getattr(self.f, name)
def read(self, size=None):
if self.n <= 0:
return ""
if size is not None and size > self.n:
size = self.n
data = self.f.read(size)
self.n -= len(data)
return data
def set_forwarded_for(environ, headers):
if environ['REMOTE_ADDR'] in ('127.0.0.1', '::1') and \
'X-Forwarded-For' not in headers:
# don't add header if we are forwarding localhost,
return
s = headers.get('X-Forwarded-For', '')
if s:
forwarders = s.split(", ")
else:
forwarders = []
addr = environ['REMOTE_ADDR']
if addr:
forwarders.append(addr)
if forwarders:
headers['X-Forwarded-For'] = ", ".join(forwarders)
def reconstruct_url(environ):
path = environ.get('PATH_INFO')
if path.startswith("http://"):
url = path
else:
host = environ.get('HTTP_HOST')
url = 'http://' + host + path
query = environ.get('QUERY_STRING', '')
if query:
url += '?' + query
return url
def get_destination(environ):
if environ["REQUEST_METHOD"] == "CONNECT":
port = 443
else:
port = 80
host = environ.get('HTTP_HOST', '').lower().split(":")
path = environ.get('PATH_INFO', '').lower()
req = urlparse.urlparse(path)
# first process requeset line
if req.scheme:
if req.scheme != "http":
raise Exception('invalid scheme in request line')
netloc = req.netloc.split(":")
if len(netloc) == 2:
return netloc[0], int(netloc[1])
else:
return req.netloc, port
elif req.netloc:
raise Exception('invalid scheme in request line')
# then process host
if len(host) == 2:
return host[0], int(host[1])
else:
return host[0], port
NON_FORWARD_HEADERS = (
'proxy-connection',
'host',
)
def copy_request(environ):
method = environ["REQUEST_METHOD"]
url = reconstruct_url(environ)
headers = []
content_length = environ.get("CONTENT_LENGTH")
if content_length:
body = LimitedReader(environ["wsgi.input"], int(content_length))
else:
body = ""
raw = environ['__ghttproxy.rawheaders']
for header in raw:
key, value = header.split(':', 1)
if not key:
continue
if key.strip().lower() in NON_FORWARD_HEADERS:
continue
headers.append((key.strip(), value.strip()))
headers.append(("Connection", "Keep-Alive"))
headers = dict(headers)
return method, url, body, headers
class ProxyApplication(object):
def __init__(self, timeout=60):
self.timeout = timeout
def http(self, environ, start_response):
try:
host, port = get_destination(environ)
log.info("HTTP request to (%s:%d)" % (host, port))
method, url, body, headers = copy_request(environ)
except Exception, e:
log.error("[Exception][http]: %s" % str(e))
start_response("400 Bad Request", [("Content-Type", "text/plain; charset=utf-8")])
yield "Bad Request"
return
try:
set_forwarded_for(environ, headers)
http_conn = socket.create_connection((host, port), timeout=self.timeout)
conn = HTTPConnection(host, port=port)
conn.sock = http_conn
u = urlparse.urlsplit(url)
path = urlparse.urlunsplit(("", "", u.path, u.query, ""))
# Host header put by conn.request
conn.request(method, path, body, headers)
resp = conn.getresponse()
start_response("%d %s" % (resp.status, resp.reason), resp.getheaders())
while True:
data = resp.read(CHUNKSIZE)
if not data:
break
yield data
conn.close()
except Exception, e:
log.error("[Exception][http]: %s" % str(e))
start_response("500 Internal Server Error", [("Content-Type", "text/plain; charset=utf-8")])
yield "Internal Server Error"
return
def tunnel(self, environ, start_response):
try:
host, port = get_destination(environ)
log.info("CONNECT request to (%s:%d)" % (host, port))
except Exception, e:
log.error("[Exception][tunnel]: %s" % str(e))
start_response("400 Bad Request", [("Content-Type", "text/plain; charset=utf-8")])
return ["Bad Request"]
try:
tunnel_conn = socket.create_connection((host, port), timeout=self.timeout)
environ['__ghttproxy.tunnelconn'] = tunnel_conn
start_response("200 Connection established", [])
return []
except socket.timeout: # @UndefinedVariable
log.error("Connection Timeout")
start_response("504 Gateway Timeout", [("Content-Type", "text/plain; charset=utf-8")])
return ["Gateway Timeout"]
except Exception, e:
log.error("[Exception][https]: %s" % str(e))
start_response("500 Internal Server Error", [("Content-Type", "text/plain; charset=utf-8")])
return ["Internal Server Error"]
def application(self, environ, start_response):
if environ["REQUEST_METHOD"] == "CONNECT":
return self.tunnel(environ, start_response)
else:
return self.http(environ, start_response)
class HTTPProxyServer(object):
def __init__(self, ip, port, app, log='default'):
self.ip = ip
self.port = port
self.app = app
self.server = WSGIServer((self.ip, self.port), log=log,
application=self.app.application, spawn=Pool(500), handler_class=ProxyHandler)
def start(self):
self.server.start()
def run(self):
self.server.serve_forever()
def stop(self):
self.server.stop()
@property
def closed(self):
return self.server.closed
if __name__ == '__main__':
logging.basicConfig(
format='[%(asctime)s][%(name)s][%(levelname)s] - %(message)s',
datefmt='%Y-%d-%m %H:%M:%S',
level=logging.DEBUG,
)
HTTPProxyServer("127.0.0.1", 8000, ProxyApplication()).run()