Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aggvpn
GitHub Repository: aggvpn/ws
Path: blob/main/websocket-python/cdn-ovpn.py
567 views
1
#!/usr/bin/python
2
import socket, threading, thread, select, signal, sys, time, getopt
3
4
# Listen
5
LISTENING_ADDR = '0.0.0.0'
6
LISTENING_PORT = sys.argv[1]
7
8
# Pass
9
PASS = ''
10
11
# CONST
12
BUFLEN = 4096 * 4
13
TIMEOUT = 60
14
DEFAULT_HOST = '127.0.0.1:1194'
15
RESPONSE = 'HTTP/1.1 101 <b><u><font color="blue">Script By Virtual t.me/Virtual_NW</font></b>\r\n\r\nContent-Length: 104857600000\r\n\r\n'
16
17
class Server(threading.Thread):
18
def __init__(self, host, port):
19
threading.Thread.__init__(self)
20
self.running = False
21
self.host = host
22
self.port = port
23
self.threads = []
24
self.threadsLock = threading.Lock()
25
self.logLock = threading.Lock()
26
27
def run(self):
28
self.soc = socket.socket(socket.AF_INET)
29
self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
30
self.soc.settimeout(2)
31
intport = int(self.port)
32
self.soc.bind((self.host, intport))
33
self.soc.listen(0)
34
self.running = True
35
36
try:
37
while self.running:
38
try:
39
c, addr = self.soc.accept()
40
c.setblocking(1)
41
except socket.timeout:
42
continue
43
44
conn = ConnectionHandler(c, self, addr)
45
conn.start()
46
self.addConn(conn)
47
finally:
48
self.running = False
49
self.soc.close()
50
51
def printLog(self, log):
52
self.logLock.acquire()
53
print log
54
self.logLock.release()
55
56
def addConn(self, conn):
57
try:
58
self.threadsLock.acquire()
59
if self.running:
60
self.threads.append(conn)
61
finally:
62
self.threadsLock.release()
63
64
def removeConn(self, conn):
65
try:
66
self.threadsLock.acquire()
67
self.threads.remove(conn)
68
finally:
69
self.threadsLock.release()
70
71
def close(self):
72
try:
73
self.running = False
74
self.threadsLock.acquire()
75
76
threads = list(self.threads)
77
for c in threads:
78
c.close()
79
finally:
80
self.threadsLock.release()
81
82
83
class ConnectionHandler(threading.Thread):
84
def __init__(self, socClient, server, addr):
85
threading.Thread.__init__(self)
86
self.clientClosed = False
87
self.targetClosed = True
88
self.client = socClient
89
self.client_buffer = ''
90
self.server = server
91
self.log = 'Connection: ' + str(addr)
92
93
def close(self):
94
try:
95
if not self.clientClosed:
96
self.client.shutdown(socket.SHUT_RDWR)
97
self.client.close()
98
except:
99
pass
100
finally:
101
self.clientClosed = True
102
103
try:
104
if not self.targetClosed:
105
self.target.shutdown(socket.SHUT_RDWR)
106
self.target.close()
107
except:
108
pass
109
finally:
110
self.targetClosed = True
111
112
def run(self):
113
try:
114
self.client_buffer = self.client.recv(BUFLEN)
115
116
hostPort = self.findHeader(self.client_buffer, 'X-Real-Host')
117
118
if hostPort == '':
119
hostPort = DEFAULT_HOST
120
121
split = self.findHeader(self.client_buffer, 'X-Split')
122
123
if split != '':
124
self.client.recv(BUFLEN)
125
126
if hostPort != '':
127
passwd = self.findHeader(self.client_buffer, 'X-Pass')
128
129
if len(PASS) != 0 and passwd == PASS:
130
self.method_CONNECT(hostPort)
131
elif len(PASS) != 0 and passwd != PASS:
132
self.client.send('HTTP/1.1 400 WrongPass!\r\n\r\n')
133
elif hostPort.startswith('127.0.0.1') or hostPort.startswith('localhost'):
134
self.method_CONNECT(hostPort)
135
else:
136
self.client.send('HTTP/1.1 403 Forbidden!\r\n\r\n')
137
else:
138
print '- No X-Real-Host!'
139
self.client.send('HTTP/1.1 400 NoXRealHost!\r\n\r\n')
140
141
except Exception as e:
142
self.log += ' - error: ' + e.strerror
143
self.server.printLog(self.log)
144
pass
145
finally:
146
self.close()
147
self.server.removeConn(self)
148
149
def findHeader(self, head, header):
150
aux = head.find(header + ': ')
151
152
if aux == -1:
153
return ''
154
155
aux = head.find(':', aux)
156
head = head[aux+2:]
157
aux = head.find('\r\n')
158
159
if aux == -1:
160
return ''
161
162
return head[:aux];
163
164
def connect_target(self, host):
165
i = host.find(':')
166
if i != -1:
167
port = int(host[i+1:])
168
host = host[:i]
169
else:
170
if self.method=='CONNECT':
171
port = 443
172
else:
173
port = sys.argv[1]
174
175
(soc_family, soc_type, proto, _, address) = socket.getaddrinfo(host, port)[0]
176
177
self.target = socket.socket(soc_family, soc_type, proto)
178
self.targetClosed = False
179
self.target.connect(address)
180
181
def method_CONNECT(self, path):
182
self.log += ' - CONNECT ' + path
183
184
self.connect_target(path)
185
self.client.sendall(RESPONSE)
186
self.client_buffer = ''
187
188
self.server.printLog(self.log)
189
self.doCONNECT()
190
191
def doCONNECT(self):
192
socs = [self.client, self.target]
193
count = 0
194
error = False
195
while True:
196
count += 1
197
(recv, _, err) = select.select(socs, [], socs, 3)
198
if err:
199
error = True
200
if recv:
201
for in_ in recv:
202
try:
203
data = in_.recv(BUFLEN)
204
if data:
205
if in_ is self.target:
206
self.client.send(data)
207
else:
208
while data:
209
byte = self.target.send(data)
210
data = data[byte:]
211
212
count = 0
213
else:
214
break
215
except:
216
error = True
217
break
218
if count == TIMEOUT:
219
error = True
220
if error:
221
break
222
223
224
def print_usage():
225
print 'Usage: proxy.py -p <port>'
226
print ' proxy.py -b <bindAddr> -p <port>'
227
print ' proxy.py -b 0.0.0.0 -p 80'
228
229
def parse_args(argv):
230
global LISTENING_ADDR
231
global LISTENING_PORT
232
233
try:
234
opts, args = getopt.getopt(argv,"hb:p:",["bind=","port="])
235
except getopt.GetoptError:
236
print_usage()
237
sys.exit(2)
238
for opt, arg in opts:
239
if opt == '-h':
240
print_usage()
241
sys.exit()
242
elif opt in ("-b", "--bind"):
243
LISTENING_ADDR = arg
244
elif opt in ("-p", "--port"):
245
LISTENING_PORT = int(arg)
246
247
248
def main(host=LISTENING_ADDR, port=LISTENING_PORT):
249
print "\n:-------PythonProxy-------:\n"
250
print "Listening addr: " + LISTENING_ADDR
251
print "Listening port: " + str(LISTENING_PORT) + "\n"
252
print ":-------------------------:\n"
253
server = Server(LISTENING_ADDR, LISTENING_PORT)
254
server.start()
255
while True:
256
try:
257
time.sleep(2)
258
except KeyboardInterrupt:
259
print 'Stopping...'
260
server.close()
261
break
262
263
####### parse_args(sys.argv[1:])
264
if __name__ == '__main__':
265
main()
266