-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyhttpsbak.py
More file actions
421 lines (401 loc) · 15 KB
/
myhttpsbak.py
File metadata and controls
421 lines (401 loc) · 15 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import os
import threading
import Queue
import ssl
import socket
import select
import urllib
import time
import logging
EOL1=b'\n\n'
EOL2=b'\n\r\n'
cwd=os.getcwd()
logging.basicConfig(filename = os.path.join(os.getcwd(), 'log.txt'), level = logging.ERROR)
def deal200head(path):
head="HTTP/1.1 200 OK\r\n"
head+="Date:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +"\r\n"
head+="Server:server of qiutian\r\n"
head+="Content-Length:"+str(os.path.getsize(cwd+path))+"\r\n"
return head
def deal400():
f=open("status/400.html","r")
ff=f.read()
f.close()
head="HTTP/1.1 400 Bad Request\r\n"
head+="Date:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +"\r\n"
head+="Server:server of qiutian\r\n"
head+="Content-Length:"+str(os.path.getsize(cwd+"/status/400.html"))+"\r\n"
head+="Content-Type: text/html\r\n\r\n"
return head+ff
def deal404():
f=open("status/404.html","r")
ff=f.read()
f.close()
head="HTTP/1.1 404 Not Found\r\n"
head+="Date:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +"\r\n"
head+="Server:server of qiutian\r\n"
head+="Content-Length:"+str(os.path.getsize(cwd+"/status/404.html"))+"\r\n"
head+="Content-Type: text/html\r\n\r\n"
return head+ff
def deal405():
f=open("status/405.html","r")
ff=f.read()
f.close()
head="HTTP/1.1 405 Method Not Allowed\r\n"
head+="Date:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +"\r\n"
head+="Server:server of qiutian\r\n"
head+="Content-Length:"+str(os.path.getsize(cwd+"/status/405.html"))+"\r\n"
head+="Content-Type: text/html\r\n\r\n"
return head+ff
def deal501():
f=open("status/501.html","r")
ff=f.read()
f.close()
head="HTTP/1.1 501 Not Implemented\r\n"
head+="Date:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +"\r\n"
head+="Server:server of qiutian\r\n"
head+="Content-Length:"+str(os.path.getsize(cwd+"/status/501.html"))+"\r\n"
head+="Content-Type: text/html\r\n\r\n"
return head+ff
def dealdir(path,method="GET"):
ff=os.popen("python dealdir.py "+cwd+' '+path).read()
head="HTTP/1.1 200 OK\r\n"
head+="Date:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +"\r\n"
head+="Server:server of qiutian\r\n"
head+="Content-Length:"+str(len(ff))+"\r\n"
head+="Content-Type: text/html\r\n\r\n"
if method == "HEAD":
return head
else:
return head+ff
def dealnone(path,method="GET"):
print "dead"
f=open(cwd+path,"r")
ff=f.read()
f.close()
head=deal200head(path)
head+="Content-Type: text/none\r\n\r\n"
if method == "HEAD":
return head
else:
return head+ff
def dealhtml(path,method="GET"):
head=deal200head(path)
head+="Content-Type: text/html\r\n\r\n"
f=open(cwd+path,"r")
ff=f.read()
f.close()
if method == "HEAD":
return head
else:
return head+ff
def dealphp(path,c,method="GET"):
ff.popen("php "+cwd+path+" "+c).read()
head=deal200head()
head+="Content-Type: text/html\r\n\r\n"
if method == "HEAD":
return head
else:
return head+ff
def dealcgi(path,types,cgican,method="GET"):
if types == "py":
ff=os.popen("python "+cwd+path+" "+cgican).read()
elif types == "pl" or "pm" or "perl":
ff=os.popen("perl "+cwd+path+" "+cgican).read()
elif types == "php":
ff=os.popen("php "+cwd+path+" "+cgican).read()
else:
try:
ff=os.popen("."+cwd+path+" "+cgican).read()
except Exception,e:
logging.error(e)
f=open(cwd+path,"r")
ff=f.read()
f.close()
head=deal200head(path)
head+="Content-Type: text/html\r\n\r\n"
if method == "HEAD":
return head
else:
return head+ff
def dealresponse(request):
method=request.split(' ')[0]
try:
url=request.split(' ')[1]
if url[0]!='/' or url[0:3]=="/..":
return deal400()
path=url.split('?')[0]
except Exception,e:
logging.error(e)
return deal400()
if method!="GET"and"POST"and"HEAD"and"OPTIONS"and"TRACE":
return deal501()
if url == '/':
f=open(cwd+"/index.html")
ff=f.read()
f.close()
head=deal200head("/index.html")
head+="Content-Type: text/html\r\n\r\n"
return head+ff
#WHEN THR WAY IS "GET" or "HEAD":
if method == "GET" or "HEAD":
if os.path.exists(cwd+path):
print cwd+path
if os.path.isdir(cwd+path) and path!='/':
return dealdir(path,method)
else:
c = ' '
cgican = ' '
if len(url.split('?'))>1 and url.split('?')[1]!='':
can=url.split('?')[1]
cgican=can.replace("&","\&")
cann=can.split('&')
a=[i.split('=')[1] for i in cann]
i=0
while i<len(a):
c=c+' '+a[i]
i=i+1
filename=path.split('/')[-1]
if len(filename.split('.'))>1:
types=filename.split('.')[-1]
print filename.split('.')
else:
types="none"
if len(path)>9 and path[0:9] == "/cgi-bin/":
return dealcgi(path,types,cgican,method)
elif types == "none":
return dealnone(path,method)
elif types == 'html':
return dealhtml(path,method)
elif types == 'php':
return dealphp(path,c,method)
else:
f=open(cwd+path,"r")
ff=f.read()
f.close()
return ff
else:
return deal404()
#WHEN THE WAY IS "POST":
if method == "POST":
if os.path.exists(cwd+path):
print cwd+path
if os.path.isdir(cwd+path) and path!='/':
return dealdir(path)
else:
c = ' '
cgican = ' '
if len(request.split('\n\r\n'))>1 and request.split('\n\r\n')[1]!='':
can=request.split('\n\r\n')[1]
cgican=can.replace("&","\&")
cann=can.split('&')
a=[i.split('=')[1] for i in cann]
i=0
while i<len(a):
c=c+' '+a[i]
i=i+1
filename=path.split('/')[-1]
if len(filename.split('.'))>1:
types=filename.split('.')[-1]
print filename.split('.')
else:
types="none"
if len(path)>9 and path[0:9] == "/cgi-bin/":
return dealcgi(path,types,cgican)
elif types == "none":
return dealnone(path)
elif types == 'html':
return dealhtml(path)
elif types == 'php':
return dealphp(path,c)
else:
f=open(cwd+path,"r")
ff=f.read()
f.close()
return ff
else:
return deal404()
#WHEN THE WAY IS "DELETE":
if method == "DELETE":
if os.path.exists(cwd+path):
try:
if os.path.isdir(cwd+path):
os.system("rm -Rf "+cwd+path)
else:
os.system("rm -f "+cwd+path)
except Exception,e:
logging.error(e)
return deal405()
else:
return deal404()
#WHEN THE WAY IS "TRACE":
if method == "TRACE":
head=deal200head()
head+="Content-Type: message/http"
return head+request
class Thread(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self._queue=queue
def run(self):
while True:
filenoo=self._queue.get()
##WHEN THE WAY IS HTTPS:
if linkway[filenoo] == "https":
while True:
try:
#print filenoo
connections[filenoo].setblocking(1)
connstream[filenoo].setblocking(1)
connstream[filenoo].do_handshake()
print "v"
connections[filenoo].setblocking(0)
connstream[filenoo].setblocking(0)
httprequests[filenoo] = connstream[filenoo].recv(1024)
break
except ssl.SSLWantReadError:
print "wantread"
#logging.error(e)
except:
print "as"
#logging.error(e)
if httprequests[filenoo]=='':
epoll.unregister(filenoo)
if EOL1 in httprequests[filenoo] or EOL2 in httprequests[filenoo]:
print('-'*40 + '\n' + httprequests[filenoo])
try:
httprespones[filenoo]=dealresponse(httprequests[filenoo])
except Exception,e:
logging.error(e)
httprespones[filenoo]=''
print 'c'
try:
connstream[filenoo].do_handshake()
byteswritten = connstream[filenoo].send(httprespones[filenoo])
httprespones[filenoo] = httprespones[filenoo][byteswritten:]
epoll.modify(filenoo, 0)
except ssl.SSLWantWriteError,e:
logging.error(e)
except Exception,e:
logging.error(e)
##WHEN THE WAY IS HTTP:
elif linkway[filenoo] == "http":
try:
httprequests[filenoo] = connections[filenoo].recv(1024)
except Exception,e:
logging.error(e)
print httprequests[filenoo]
if httprequests[filenoo]=='':
epoll.unregister(filenoo)
if EOL1 in httprequests[filenoo] or EOL2 in httprequests[filenoo]:
print('-'*40 + '\n' + httprequests[filenoo])
print threading.current_thread().name
try:
httprespones[filenoo]=dealresponse(httprequests[filenoo])
except Exception,e:
logging.error(e)
httprespones[filenoo]=''
if httprequests[filenoo]=='':
epoll.unregister(filenoo)
try:
byteswritten = connections[filenoo].send(httprespones[filenoo])
httprespones[filenoo] = httprespones[filenoo][byteswritten:]
except Exception,e:
logging.error(e)
try:
epoll.modify(filenoo, 0)
except Exception,e:
logging.error(e)
#SHUTDOWN:
try:
connstream[fileno].shutdown(socket.SHUT_RDWR)
except Exception,e:
logging.error(e)
try:
connections[fileno].shutdown(socket.SHUT_RDWR)
except Exception,e:
logging.error(e)
self._queue.task_done()
if __name__=="__main__":
queue=Queue.Queue()
for i in range(100):
t=Thread(queue)
t.setDaemon(True)
t.start()
context=ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain(certfile='cert.pem', keyfile='key.pem')
serversockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversockets.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversockets.bind(('127.0.0.1', 443))
serversockets.listen(100)
serversockets.setblocking(0)
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind(('127.0.0.1', 80))
serversocket.listen(100)
serversocket.setblocking(0)
epoll = select.epoll()
epoll.register(serversockets.fileno(), select.EPOLLIN)
epoll.register(serversocket.fileno(), select.EPOLLIN)
try:
connections={}
httprequests={}
httprespones={}
connstream={}
linkway={}
while True:
events=epoll.poll(1)
for fileno,event in events:
#print events
if event & select.EPOLLOUT:
pass
elif fileno == serversockets.fileno() or fileno == serversocket.fileno():
print 'a'
if fileno == serversocket.fileno():
connection,address=serversocket.accept()
connection.setblocking(0)
epoll.register(connection.fileno(),select.EPOLLIN)
linkway[connection.fileno()]="http"
connections[connection.fileno()] = connection
httprequests[connection.fileno()] = b''
httprequests[connection.fileno()] = b''
else:
connection,address=serversockets.accept()
epoll.register(connection.fileno(),select.EPOLLIN)
try:
connstream[connection.fileno()] = context.wrap_socket(connection, server_side=True,do_handshake_on_connect=False)
linkway[connection.fileno()]="https"
connection.setblocking(0)
connstream[connection.fileno()].setblocking(0)
connections[connection.fileno()] = connection
httprequests[connection.fileno()] = b''
httprequests[connection.fileno()] = b''
except Exception,e:
logging.error(e)
epoll.modify(connection.fileno(),0)
epoll.unregister(connection.fileno())
connection.shutdown(socket.SHUT_RDWR)
connection.close()
elif event & select.EPOLLIN:
print 'b'
epoll.modify(fileno,select.EPOLLOUT)
queue.put(fileno)
elif event & select.EPOLLHUP:
print 'd'
epoll.unregister(fileno)
try:
connstream[fileno].close()
except Exception,e:
logging.error(e)
connections[fileno].close()
del connections[fileno]
try:
del connstream[fileno]
except Exception,e:
logging.error(e)
del linkway[fileno]
finally:
print 'e'
epoll.unregister(serversockets.fileno())
epoll.close()
serversockets.close()