forked from cdhigh/Forwarder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsgi.py
58 lines (51 loc) · 2.07 KB
/
wsgi.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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
""" python网络请求转发器,可以将其部署到任何一个支持WSGI的托管空间。
用法:
http://hostedurl?u=url&k=AUTHKEY&t=timeout
解析:
hostedurl: 你搭建的转发服务器的URL
url: 需要转发到url,需要先使用urllib.quote转义,特别是如果有&符号
AUTHKEY: 为了防止滥用,需要提供一个key,为ALLOW_KEYS里面的任何一个值
timeout: [可选]超时时间,默认为30s
"""
__Version__ = "1.0"
__Author__ = "Arroz"
from wsgiref.util import is_hop_by_hop
import urllib, urllib2, socket, bottle
ALLOW_KEYS = ('xzSlE','ILbou','DukPL')
application = app = bottle.Bottle()
@app.route(r'/')
def Home():
resp = bottle.response
qry = bottle.request.query
url,k,timeout = qry.u, qry.k, int(qry.get('t','30'))
if k and k not in ALLOW_KEYS:
return 'Auth Key is invalid!'
if url and k:
url = urllib.unquote(url)
try:
req = urllib2.Request(url)
req.add_header('User-Agent', "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)")
req.add_header('Accept', "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
ret = urllib2.urlopen(req,timeout=timeout)
content = ret.read()
headers = [(n,v) for n,v in ret.info().items() if not is_hop_by_hop(n)]
cookieadded = False
for n,v in headers:
if n == 'Set-Cookie' and cookieadded:
resp.add_header(n, v)
else:
resp.set_header(n, v)
if n == 'Set-Cookie':
cookieadded = True
return content
except socket.timeout:
pass
except Exception as e:
print("ERR:%s:%s" % (type(e),str(e)))
bottle.abort(400)
else:
return "<html><head><title>Forwarder Url</title></head><body>Forwarder : thisurl?u=url&k=AUTHKEY&t=timeout</body></html>"
if __name__ == '__main__': #for debug
bottle.run(app, reloader=True)