-
Notifications
You must be signed in to change notification settings - Fork 3
/
bsn-proxy.py
131 lines (102 loc) · 3.79 KB
/
bsn-proxy.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
#!/usr/bin/env python
# from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import socket
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import argparse
import os
import random
import sys
from urllib import request as urllib2
def merge_two_dicts(x, y):
z = x.copy() # start with x's keys and values
z.update(y) # modifies z with y's keys and values & returns None
return z
def set_header():
headers = {
# 'Host': hostname
'X-API-KEY': args.api_key
}
return headers
class ProxyHTTPRequestHandler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.0'
def do_HEAD(self):
self.do_GET(body=False)
def do_GET(self, body=True):
req_header = self.parse_headers()
del req_header['Host']
resp = urllib2.Request(url=bsn_url,
headers=merge_two_dicts(dict(req_header), set_header()),
)
r = urllib2.urlopen(resp)
self.send_response(r.getcode())
for k, v in r.getheaders():
self.send_header(k, v)
self.end_headers()
if body:
self.wfile.write(r.read())
return
def do_POST(self, body=True):
print(self.headers)
content_len = int(self.headers['content-length'])
post_body = self.rfile.read(content_len)
req_header = self.parse_headers()
del req_header['Host']
print(bsn_url)
resp = urllib2.Request(url=bsn_url,
headers=merge_two_dicts(dict(req_header), set_header()),
data=post_body)
r = urllib2.urlopen(resp)
sent = True
self.send_response(r.getcode())
for k, v in r.getheaders():
self.send_header(k, v)
self.end_headers()
if body:
self.wfile.write(r.read())
return
def parse_headers(self):
return self.headers
def send_resp_headers(self, resp):
respheaders = resp.headers
for key in respheaders:
if key not in ['Content-Encoding', 'Transfer-Encoding', 'content-encoding', 'transfer-encoding', 'content-length', 'Content-Length']:
# print key, respheaders[key]
self.send_header(key, respheaders[key])
self.send_header('Content-Length', len(resp.content))
self.end_headers()
def parse_args(argv=sys.argv[1:]):
parser = argparse.ArgumentParser(description='Proxy BSN requests')
parser.add_argument('--port', dest='port', type=int, default=9999,
help='serve HTTP requests on specified port (default: 9999)')
parser.add_argument('--bsn-url', dest='bsn_url', required=True,
help='bsn url')
parser.add_argument('--api-key', dest='api_key', required=True,
help='bsn api key')
args = parser.parse_args(argv)
return args
class ServerThread(Thread):
def __init__(self, i):
Thread.__init__(self)
self.i = i
self.daemon = True
self.start()
def run(self):
httpd = HTTPServer(server_address, ProxyHTTPRequestHandler, False)
httpd.socket = sock
httpd.server_bind = self.server_close = lambda self: None
httpd.serve_forever()
if __name__ == '__main__':
args = parse_args(sys.argv[1:])
print('http server is starting on port {}...'.format(args.port))
server_address = ('127.0.0.1', args.port)
bsn_url = args.bsn_url
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(server_address)
sock.listen(5)
[ServerThread(i) for i in range(100)]
print('http server is running as reverse proxy')
while True:
time.sleep(9e9)