-
Notifications
You must be signed in to change notification settings - Fork 0
/
forward.py.org
156 lines (144 loc) · 4.71 KB
/
forward.py.org
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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
import time
import threading
import traceback
import errno
import sys
import base64
def get_headers(data):
header_dict = {}
data = str(data)
header, body = data.split('\r\n\r\n', 1)
header_list = header.split('\r\n')
for i in range(0, len(header_list)):
if i == 0:
if len(header_list[i].split(' ')) == 3:
header_dict['method'], header_dict['url'], header_dict['protocol'] = header_list[i].split(' ')
else:
k, v = header_list[i].split(':', 1)
header_dict[k] = v.strip()
return header_dict
def Thread_RemoteRecv_Fun(conn,remoteSock):
while True:
try:
data = remoteSock.recv(8192)
if not data:
print ('remoteSock:' + str(remoteSock)+' recv 0 will Close.')
break
cliArr = base64.b64encode(data)
conn.send(cliArr)
except Exception as e:
print (str(e))
print (errno.errorcode[e.errno])
print ('format_exc():\r\n',traceback.format_exc())
break
remoteSock.close()
print ('remoteSock.close()')
remoteSock = None
conn.close()
print ('conn.close()')
conn = None
return
def Main_Thread_Fun(conn):
try:
data = conn.recv(1024)
except:
print ('format_exc():\r\n',traceback.format_exc())
conn.close()
return
headers = get_headers(data)
response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \
"Upgrade: websocket\r\n" \
"Connection: Upgrade\r\n" \
"Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=\r\n" \
"\r\n"
#"Sec-WebSocket-Protocol: chat\r\n" \
#"WebSocket-Location: ws://%s%s\r\n"
#response_str = response_tpl % (headers['Host'], headers['url'])
response_str = response_tpl
if '1' == headers['JustTest']:
conn.send(bytes(response_str))
conn.shutdown(socket.SHUT_RDWR)
conn.close()
print ('conn.close()')
conn = None
print ('return')
return
print ('connect')
forwardHost = headers['ForwardHost']
if '1' == headers['Base64Host']:
forwardHost = base64.b64decode(forwardHost)
print ('base64 Host:'+forwardHost)
forwardPort = headers['ForwardPort']
forward_EP = (forwardHost,int(forwardPort))
remoteSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remoteSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
print ('connect'+str(forward_EP))
remoteSock.connect(forward_EP)
print ('remoteSock:' + str(remoteSock.getpeername()))
except Exception as e:
print (str(e))
print (errno.errorcode[e.errno])
print ('format_exc():\r\n',traceback.format_exc())
remoteSock.close()
conn.close()
return
conn.send(bytes(response_str))
remote_thr = threading.Thread(target=Thread_RemoteRecv_Fun,args=(conn,remoteSock,))
remote_thr.daemon = True
remote_thr.start()
while True:
try:
data = conn.recv(8192)
if not data:
print ('conn:' + str(conn)+' recv 0 will Close.')
break
b64Arr = base64.b64decode(data)
remoteSock.send(b64Arr)
except Exception as e:
print (str(e))
print (errno.errorcode[e.errno])
print ('format_exc():\r\n',traceback.format_exc())
break
remoteSock.shutdown(socket.SHUT_RDWR)
remoteSock.close()
print ('remoteSock.close()')
remoteSock = None
conn.shutdown(socket.SHUT_RDWR)
conn.close()
print ('conn.close()')
conn = None
return
def run():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverPort = 36000
try:
sock.bind(('127.0.0.1', serverPort))
sock.listen(5)
print ('listen '+str(sock.getsockname()))
except Exception as e:
print (str(e))
print (errno.errorcode[e.errno])
print ('format_exc():\r\n',traceback.format_exc())
return
while True:
try:
conn, address = sock.accept()
except KeyboardInterrupt:
print ('Input KeyboardInterrupt')
break;
except:
print ('format_exc():\r\n',traceback.format_exc())
continue
mainThr = threading.Thread(target=Main_Thread_Fun,args=(conn,))
mainThr.start()
print ('accept'+ str(address))
print ('close && exit\r\n')
sock.close()
sys.exit()
if __name__ == '__main__':
run()