-
Notifications
You must be signed in to change notification settings - Fork 0
/
https.py
670 lines (628 loc) · 28.9 KB
/
https.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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
import socket
import sys
import os
import datetime
import time
from conf import *
from threading import *
import threading
import concurrent.futures
x = datetime.datetime.now()
x_day = x.strftime("%d")
x_month = x.strftime("%b")
x_nmonth = x.strftime("%m")
x_year = x.strftime("%Y")
x_hour = x.strftime("%H")
x_min = x.strftime("%M")
x_sec = x.strftime("%S")
headers = {
'Date': "%s, %s GMT" % (x.strftime("%A")[:3], x.strftime("%d %b %Y %H:%M:%S")),
'Server': 'CrudeServer',
'Last-Modified': 'Tue, 06 Oct 2020 13:33:34 GMT',
'ETag': "2aa6-5b100a5427dfe",
'Accept-Ranges': 'bytes',
'Content-Length': '10918',
'Vary': 'Accept-Encoding',
'Content-Type': 'text/html',
'Connection': 'close',
'Set-Cookie': 'yummy_cookie=choco',
}
status_codes = {
200: 'OK',
404: 'Not Found',
501: 'Not Implemented',
400: 'Bad Request',
201: 'Created',
202: 'Accepted',
304: 'Not Modified',
414: 'URI Too Long',
408: 'Request Timeout',
411: 'Length Required',
413: 'Payload Too Large',
204: 'No Content',
415: 'Unsupported Media Type',
403: 'Forbidden',
}
def response_line(status_code):
"""Returns response line"""
reason = status_codes[status_code]
return "HTTP/1.1 %s %s\r\n" % (status_code, reason)
def response_headers(time1, l = None,filename = None, extension = None):
header = ""
for h in headers:
if(h == 'Content-Length'):
header += "%s: %s\r\n" % (h, l)
elif(h == 'Date'):
header += "%s: %s, %s GMT" % (h, time1.strftime("%A")[:3], time.strftime("%d %b %Y %H:%M:%S"))
elif(h == 'Last-Modified'):
if(filename != None):
k = time.ctime(os.path.getmtime(filename))
s = ""
if(int(k[9]) < 10):
s += "0" + k[9]
else:
s += k[9]
header += "%s: %s, %s %s %s %s GMT\r\n" % (h, k[0:3], s, k[4:7], k[20:24], k[11:19])
elif(h == 'Set-Cokkie'):
for k in cokkies:
header += "%s: %s=%s\r\n" % (h, k, cokkies[k])
elif(h == 'Content-Type'):
if extension == "html":
header += "%s: %s\r\n" % (h, 'text/html')
elif extension == "png":
header += "%s: %s\r\n" % (h, 'image/png')
elif extension == "txt":
header += "%s: %s\r\n" % (h, 'text/plain')
elif extension == "jpg":
header += "%s: %s\r\n" % (h, 'image/jpg')
elif extension == "jpeg":
header += "%s: %s\r\n" % (h, 'image/jpeg')
elif extension == "mp3":
header += "%s: %s\r\n" % (h, 'audio/mpeg')
elif extension == "mp4":
header += "%s: %s\r\n" % (h, 'video/mp4')
else:
header += "%s: %s\r\n" % (h, headers[h])
return header
def compareDate():
id = headers["Cookie"].split("=")[0]
expiry = sent_cookies[id]
DateTime = datetime.datetime.now()
currDate += DateTime.strftime("%a, %d %B %Y %I:%M:%S")
if expiry > currDate:
return False
return True
def Set_Cookie():
for x in cookies:
if x not in sent_cookies:
id = x
DateTime = (datetime.datetime.now() + datetime.timedelta(days=1))
value=cookies[id]
date = DateTime.strftime("%a, %d %B %Y %I:%M:%S ")
if id not in sent_cookies.keys():
sent_cookies[id] = date
print(sent_cookies)
break
else:
continue
if id:
cookie = "Set-Cookie: "
cookie += id + "="
cookie += value
cookie += "; "
cookie += "Expires="
DateTime = (datetime.datetime.now() + datetime.timedelta(days=1))
cookie += DateTime.strftime("%a, %d %B %Y %I:%M:%S")
cookie += "GMT;"
return cookie
else:
return None
def uri_len(uri):
l = len(uri)
if(l > max_uri_len):
return 1
else:
return 0
def getdate(s):
k = []
p = s.split(" ")
for i in p:
i = i.strip(',')
if(len(i) == 3):
datetime_object = datetime.datetime.strptime(i, "%b")
m_num = datetime_object.month
k.append(int(m_num))
elif(len(i) == 8):
p1 = i.split(":")
k.append(int(p1[0]))
k.append(int(p1[1]))
k.append(int(p1[2]))
else:
k.append(int(i))
return k
def res_ifs(date, filename):
N = getdate(date)
k = time.ctime(os.path.getmtime(filename))
s = ""
if(int(k[9]) < 10):
s += "0" + k[9]
else:
s += k[9]
datetime_object = datetime.datetime.strptime(k[4:7], "%b")
m_num = datetime_object.month
b = datetime.datetime(int(k[20:24]), int(m_num), int(s), int(k[11:13]), int(k[14:16]), int(k[17:19]))
a = datetime.datetime(N[2], N[1], N[0], N[3], N[4], N[5])
return a>b
def logtext(time, filename, st_code, method):
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
# print(st_code)
if(method == "DELETE" and st_code == 200):
text = '%s - - [%s] "%s %s HTTP/1.1" %s 0 "-" "-" \r\n' % (host, date, method, filename, st_code)
elif(st_code == 200 or st_code == 201 or st_code == 304 or st_code == 204 or st_code == 202):
text = '%s - - [%s] "%s %s HTTP/1.1" %s %s "-" "-" \r\n' % (host, date, method, filename, st_code, (os.stat(filename)).st_size)
elif(st_code == 404 or st_code == 501 or st_code == 400 or st_code == 414 or st_code == 408 or st_code == 411 or st_code == 413 or st_code == 415 or st_code == 403):
text = '%s - - [%s] "%s %s HTTP/1.1" %s 0 "-" "-" \r\n' % (host, date, method, filename, st_code)
with open("access.log", "a") as myfile:
myfile.write(text)
if(st_code == 200 or st_code == 501 or st_code == 415 or st_code == 400 or st_code == 404):
text = '%s - - [%s] "%s %s HTTP/1.1" %s 0 "-" "-" \r\n' % (host, date, method, filename, st_code)
with open("error.log", "a") as myfile:
myfile.write(text)
def HTTP_400_Handler(time):
global st_code
responseline = response_line(status_code=400)
st_code = 400
response_body = "<html><head><title>400 Bad Request</title></head><body><h1>400 Bad Request</h1><p>Your browser sent a request that this server could not understand.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
responseheaders = response_headers(time, l)
blank_line = "\r\n"
return responseline, responseheaders, response_body
def HTTP_408_Handler(time):
global st_code
responseline = response_line(status_code=408)
st_code = 408
response_body = "<html><head><title>408 Request Timeout</title></head><body><h1>408 Request Timeout</h1><p>Your browser did'nt send a complete request in time.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
responseheaders = response_headers(time,l)
blank_line = "\r\n"
return responseline, responseheaders, response_body
def HTTP_403_Handler(time):
global st_code
responseline = response_line(status_code=403)
st_code = 403
response_body = "<html><head><title>403 Forbidden</title></head><body><h1>408 Request Timeout</h1><p>You don't have permission to access this file on this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
responseheaders = response_headers(time,l)
blank_line = "\r\n"
return responseline, responseheaders, response_body
def HTTP_414_handler(time):
global st_code
responseline = response_line(status_code=414)
st_code = 414
blank_line = "\r\n"
response_body = "<html><head><title>414 REQUEST-URI Too Long</title></head><body><h1>414 REQUEST-URI Too Long</h1><p>The requested URL is too large to process.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
responseheaders = response_headers(time,l)
return responseline, responseheaders, response_body
def HTTP_411_handler(time):
global st_code
responseline = response_line(status_code=411)
st_code = 411
blank_line = "\r\n"
response_body = "<html><head><title>411 Length Required</title></head><body><h1>411 Length Required</h1><p>The request must be chunked or have a content length.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
responseheaders = response_headers(time,l)
return responseline, responseheaders, response_body
def HTTP_413_handler(time):
global st_code
responseline = response_line(status_code=413)
st_code = 413
blank_line = "\r\n"
response_body = "<html><head><title>413 Request Entity Too Large</title></head><body><h1>413 Request Entity Too Large</h1><p>The request entity is too large.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
responseheaders = response_headers(time,l)
return responseline, responseheaders, response_body
def HTTP_501_handler(time,uri):
global st_code
responseline = response_line(status_code=501)
st_code = 501
blank_line = "\r\n"
response_body = "<html><head><title>501 Not Implemented</title></head><body><h1>501 Not Implemented</h1><p>The server is unable to process your request.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
responseheaders = response_headers(time,l)
return responseline, responseheaders, response_body
def OPTIONS(uri):
responseline = response_line(200)
extra_headers = {'Allow': 'OPTIONS, GET'}
responseheaders = response_headers()
blank_line = "\r\n"
return responseline, responseheaders, response_body
def GET(time,uri, data):
filename = uri.strip('/')
permissions = {
'read_p' : 'False',
'write_p' : 'False',
'exec_p' : 'False',
'exst' : 'False',
}
if(uri != None):
if os.access(filename,os.R_OK):
permissions['read_p'] = "True"
if os.access(filename, os.W_OK) :
permissions['write_p'] = "True"
if os.access(filename, os.X_OK):
permissions['exec_p'] = "True"
if os.access(filename, os.F_OK):
permissions['exst'] = "True"
if permissions['exst'] == "True" and permissions['read_p'] == "False" and uri != None:
responseline, responseheaders, response_body = HTTP_403_Handler(time)
else:
k = data.split("\r\n")
ext_list = filename.split('.')
if len(ext_list) > 1:
extension = ext_list[1]
flag = 0
if extension == "png" or extension == "jpg" or extension == "jpeg" or extension =="mp4" or extension == "mp3" or extension == "html" or extension == "txt":
try:
if extension == "png" or extension == "jpg" or extension == "jpeg" or extension =="mp4" or extension == "mp3":
flag = 1
except(UnboundLocalError):
flag = 0
p = 0
global st_code
for i in k:
if("If-Modified-Since" in i):
p = res_ifs(i[24:43], filename)
if(p):
if os.path.exists(filename):
responseline = response_line(304)
st_code = 304
response_body = ""
date = "%s +0530" % (x.strftime("%d/%b/%Y:%H:%M:%S"))
l = len(response_body)
responseheaders = response_headers(time,l,filename)
# logtext = '%s - - [%s] "GET %s HTTP/1.1" 304 %s "-" "-" \r\n' % (host, date, filename, (os.stat(filename)).st_size)
else:
responseline = response_line(404)
st_code = 404
response_body = "<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested URL was not found on this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (x.strftime("%d/%b/%Y:%H:%M:%S"))
# logtext = '%s - - [%s] "GET %s HTTP/1.1" 404 0 "-" "-" \r\n' % (host, date, filename)
responseheaders = response_headers(time,l)
else:
if os.path.exists(filename):
if flag == 1:
with open(filename, 'rb') as f:
response_body = f.read()
else:
with open(filename, 'r') as f:
response_body = f.read()
responseline = response_line(200)
st_code = 200
l = len(response_body)
# logtext = '%s - - [%s] "GET %s HTTP/1.1" 200 %s "-" "-" \r\n' % (host, date, filename, (os.stat(filename)).st_size)
date = "%s, %s GMT" % (x.strftime("%A")[:3], x.strftime("%d %b %Y %H:%M:%S"))
responseheaders = response_headers(time,l, filename, extension)
else:
responseline = response_line(404)
st_code = 404
response_body = "<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested URL was not found on this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (x.strftime("%d/%b/%Y:%H:%M:%S"))
# logtext = '%s - - [%s] "GET %s HTTP/1.1" 404 0 "-" "-" \r\n' % (host, date, filename)
responseheaders = response_headers(time,l)
else:
responseline = response_line(415)
st_code = 415
response_body = "<html><head><title>415 Unsupported Media Type</title></head><body><h1>415 Unsupported Media Type</h1><p>The server refused the request because the request entity format is not supported by this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
responseheaders = response_headers(time,l)
blank_line = "\r\n"
return responseline, responseheaders, response_body
def POST(time,uri, data):
global st_code
lines = data.split('\r\n')
filename = uri.strip('/')
k = data.split("\r\n")
ext_list = filename.split('.')
if len(ext_list) > 1:
extension = ext_list[1]
if extension == "png" or extension == "jpg" or extension == "jpeg" or extension =="mp4" or extension == "mp3" or extension == "html" or extension == "txt":
if os.path.exists(filename):
responseline = response_line(200)
st_code = 200
l = len(lines[-1])
if(l > max_payload):
responseline, responseheaders, response_body = HTTP_413_handler(time)
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
logtext = '%s - - [%s] "POST %s HTTP/1.1" 413 %s "-" "-"\r\n' % (host, date, filename, (os.stat(filename)).st_size)
with open("access.log", "a") as myfile:
myfile.write(logtext)
return responseline, responseheaders, response_body
responseheaders = response_headers(time,l+1)
blank_line = "\r\n"
response_body = lines[-1]
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
logtext = '%s - - [%s] "POST %s HTTP/1.1" 200 %s "-" "-" %s\r\n' % (host, date, filename, (os.stat(filename)).st_size, lines[-1])
else:
responseline = response_line(404)
st_code = 404
response_body = "<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested URL was not found on this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
# logtext = '%s - - [%s] "GET %s HTTP/1.1" 404 0 "-" "-" \r\n' % (host, date, filename)
responseheaders = response_headers(time,l)
logtext = '%s - - [%s] "POST %s HTTP/1.1" 404 0 "-" "-"\r\n' % (host, date, filename)
else:
responseline = response_line(415)
st_code = 415
response_body = "<html><head><title>415 Unsupported Media Type</title></head><body><h1>415 Unsupported Media Type</h1><p>The server refused the request because the request entity format is not supported by this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
responseheaders = response_headers(time,l)
logtext = '%s - - [%s] "POST %s HTTP/1.1" 415 0 "-" "-"\r\n' % (host, date, filename)
with open("access.log", "a") as myfile:
myfile.write(logtext)
return responseline, responseheaders, response_body
def HEAD(time,uri, data):
global st_code
filename = uri.strip('/')
k = data.split("\r\n")
ext_list = filename.split('.')
if len(ext_list) > 1:
extension = ext_list[1]
if extension == "png" or extension == "jpg" or extension == "jpeg" or extension =="mp4" or extension == "mp3" or extension == "html" or extension == "txt":
if os.path.exists(filename):
responseline = response_line(200)
st_code = 200
with open(filename) as f:
response_body = f.read()
l = len(response_body)
date = "%s +0530" % (x.strftime("%d/%b/%Y:%H:%M:%S"))
# logtext = '%s - - [%s] "HEAD %s HTTP/1.1" 200 %s "-" "-" \r\n' % (host, date, filename, (os.stat(filename)).st_size)
date = "%s, %s GMT" % (x.strftime("%A")[:3], x.strftime("%d %b %Y %H:%M:%S"))
responseheaders = response_headers(time,l)
else:
responseline = response_line(404)
st_code = 404
response_body = "<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested URL was not found on this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (x.strftime("%d/%b/%Y:%H:%M:%S"))
# logtext = '%s - - [%s] "HEAD %s HTTP/1.1" 404 0 "-" "-" \r\n' % (host, date, filename)
responseheaders = response_headers(time,l)
else:
responseline = response_line(415)
st_code = 415
response_body = "<html><head><title>415 Unsupported Media Type</title></head><body><h1>415 Unsupported Media Type</h1><p>The server refused the request because the request entity format is not supported by this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
responseheaders = response_headers(time,l)
blank_line = "\r\n"
return responseline, responseheaders, response_body
def PUT(time,uri, data):
global st_code
data1 = data.split('\r\n')
filename = uri.strip('/')
k = data.split("\r\n")
ext_list = filename.split('.')
if len(ext_list) > 1:
extension = ext_list[1]
k = 0
if extension == "png" or extension == "jpg" or extension == "jpeg" or extension =="mp4" or extension == "mp3" or extension == "html" or extension == "txt":
for i in data1:
if("Content-Length" in i):
k += 1
break
if(k == 1):
data = data.split('\r\n')
i = 0
while(data[i] != '' and i < len(data)):
if(i < len(data) - 2 and data[i+1] == '' and data[i+2] == ''):
i += 3
break
i += 1
if(i < len(data) and data[i] == ''):
i += 1
str = ""
while(i < len(data)):
str += data[i]
if(i != len(data) - 1):
str += '\r\n'
i += 1
if(len(str) > max_payload):
responseline, responseheaders, response_body = HTTP_413_handler(time)
return responseline, responseheaders, response_body
else:
filename = uri.strip('/')
if(os.path.isfile(filename) == False):
f = open(filename,"w+")
f.write(str)
response_body = ""
if(f):
response_body += "<h1>The file was created.</h1>\n"
responseline = response_line(201)
st_code = 201
responseheaders = response_headers(time,len(response_body))
else:
permissions = {
'read_p' : 'False',
'write_p' : 'False',
'exec_p' : 'False',
}
if uri != None:
if os.access(filename,os.R_OK):
permissions['read_p'] = "True"
if os.access(filename, os.W_OK) :
permissions['write_p'] = "True"
if os.access(filename, os.X_OK):
permissions['exec_p'] = "True"
if(permissions['write_p'] == "False"):
responseline, responseheaders, response_body = HTTP_403_Handler(time)
elif(len(str) == 0):
f = open(filename,"w")
f.write(str)
responseline = response_line(204)
st_code = 204
response_body = ""
l = len(response_body)
responseheaders = response_headers(time,l)
else:
f = open(filename,"w")
f.write(str)
responseline = response_line(200)
st_code = 200
response_body = ""
responseheaders = response_headers(time,len(response_body))
""" 204 No Content Status Code Pending """
blank_line = "\r\n"
return responseline, responseheaders, response_body
else:
responseline, responseheaders, response_body = HTTP_411_handler(time)
return responseline, responseheaders, response_body
else:
responseline = response_line(415)
st_code = 415
response_body = "<html><head><title>415 Unsupported Media Type</title></head><body><h1>415 Unsupported Media Type</h1><p>The server refused the request because the request entity format is not supported by this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
responseheaders = response_headers(time,l)
return responseline, responseheaders, response_body
def DELETE(time, uri):
global st_code
filename = uri.strip('/')
ext_list = filename.split('.')
if len(ext_list) > 1:
extension = ext_list[1]
if(extension == "png" or extension == "jpg" or extension == "jpeg" or extension =="mp4" or extension == "mp3" or extension == "html" or extension == "txt"):
filename = uri.strip('/')
if(os.path.isfile(filename) == False):
responseline = response_line(404)
st_code = 404
response_body = "<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested URL was not found on this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
responseheaders = response_headers(time,len(response_body))
else:
os.remove(filename)
responseline = response_line(200)
st_code = 200
response_body = "<html><body><h1>File deleted.</h1></body></html>"
responseheaders = response_headers(time,len(response_body))
else:
responseline = response_line(415)
st_code = 415
response_body = "<html><head><title>415 Unsupported Media Type</title></head><body><h1>415 Unsupported Media Type</h1><p>The server refused the request because the request entity format is not supported by this server.</p><hr><address>My (Ubuntu) Server at 127.0.0.1 Port 12000</address></body></html>\n"
l = len(response_body)
date = "%s +0530" % (time.strftime("%d/%b/%Y:%H:%M:%S"))
responseheaders = response_headers(time,l)
return responseline, responseheaders, response_body
def HTTPRequest(data):
http_version = '1.1' # default to HTTP/1.1 if request doesn't provide a version
headers = {} # a dictionary for headers
lines = data.split('\r\n')
words = lines[0].split(' ')
method = words[0]
try:
uri = words[1]
except(IndexError):
uri = None
if len(words) > 2:
http_version = words[2]
return method, uri, http_version
def handle_request(data):
data = data.decode()
global response
global body
global st_code
# time.sleep(10)
time = datetime.datetime.now()
method, uri, http_version = HTTPRequest(data)
# print(method, uri, http_version)
if(uri_len(uri.strip('/')) == 1):
responseline, responseheaders, response_body = HTTP_414_handler(time)
logtext(time, uri.strip('/'), st_code, method)
elif(method == 'GET'):
if(uri is None or http_version != "HTTP/1.1"):
responseline, responseheaders, response_body = HTTP_400_Handler(time)
else:
responseline, responseheaders, response_body = GET(time,uri, data)
logtext(time, uri.strip('/'), st_code, method)
elif(method == 'HEAD'):
if(uri is None or http_version != "HTTP/1.1"):
responseline, responseheaders, response_body = HTTP_400_Handler(time)
else:
responseline, responseheaders, response_body = HEAD(time,uri, data)
logtext(time, uri.strip('/'), st_code, method)
elif(method == 'POST'):
if(uri is None or http_version != "HTTP/1.1"):
responseline, responseheaders, response_body = HTTP_400_Handler(time)
else:
responseline, responseheaders, response_body = POST(time,uri, data)
elif(method == 'PUT'):
if(uri is None or http_version != "HTTP/1.1"):
responseline, responseheaders, response_body = HTTP_400_Handler(time)
else:
responseline, responseheaders, response_body = PUT(time,uri, data)
logtext(time,uri.strip('/'), st_code, method)
elif(method == 'DELETE'):
if(uri is None or http_version != "HTTP/1.1"):
responseline, responseheaders, response_body = HTTP_400_Handler(time)
else:
responseline, responseheaders, response_body = DELETE(time,uri)
logtext(time, uri.strip('/'), st_code, method)
else:
responseline, responseheaders, response_body = HTTP_501_handler(time,uri)
logtext(time,uri.strip('/'), st_code, method)
# response_h = response_l + response_h + blank_line
response = responseline + responseheaders + '\r\n'
if type(response_body) == str:
body = bytes(response_body,'utf-8')
else:
body = response_body
def stop_server():
while(True):
k = input()
if(k == 'quit'):
print("Thank You! HTTP Server Signing off.....!")
os._exit(os.EX_OK)
host='127.0.0.1'
try:
port=int(sys.argv[1])
except(IndexError):
print("Provide the port number in command line.")
exit(1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(5)
print("Listening at", s.getsockname())
response = None
body = None
st_code = None
n_conn = 0
qt = Thread(target=stop_server)
qt.start()
while True:
conn, addr = s.accept()
if(n_conn < max_conn):
print("Connected by", addr)
n_conn += 1
data = (conn.recv(1024))
start = time.time()
t1 = Thread(target=handle_request, args=(data,))
t1.start()
end = time.time()
while(response is None or body is None):
continue
if(end - start < max_time):
conn.sendall(bytes(response, 'utf-8'))
conn.sendall(body)
else:
response = HTTP_408_Handler()
response = None
conn.close()
n_conn -= 1
else:
text = "CONNECTION REFUSED! The server has reached maximum connections limit.\r\n"
with open("error.log", "a") as myfile:
myfile.write(text)