-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.py
169 lines (141 loc) · 3.62 KB
/
webserver.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
import threading,urllib
import socket,os
import sys,pprint
import settings
from subprocess import call
import cgi,cgitb
CRLF = "\r\n"
cgitb.enable()
form = cgi.FieldStorage()
def start_server(host,port):
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
server.bind((host,port))
except:
print "Address is already in use"
port = input("Please Enter A New Port NO. : ")
server.bind((host,port))
server.listen(5)
print "server started on %s : %s" %(host,port)
try:
while True:
clientsocket,address = server.accept()
t = threading.Thread(target=handler,args=(clientsocket,))
t.run()
except KeyboardInterrupt:
print "server is shutting down"
server.close()
class Request:
def __init__(self,method,path,f):
self.method = method
self.path = path
self.client = f
self.data = ""
self.headers = {}
def process(self):
if self.method == "GET":
self.processGetRequest()
elif self.method == "POST":
self.processPostRequest()
response = Response()
response.data = self.data
response.headers = self.headers
return response
def processGetRequest(self):
if not hasattr(settings,'SCRIPTALIAS'):
self.execCgi()
else:
self.data = """
<html>
<head><title>python webserver</title></head>
<body>
<form method="POST" action="index.cgi">
<input name='name' type='text'></br>
<input type='submit' value='Add'>
</form>
</body>
</htm>
"""
def processPostRequest(self):
if hasattr(settings,'SCRIPTALIAS'):
pass
#self.execCgi()
#self.headers['Content-type'] = "text/html"
#self.data = self.path
def execCgi(path,f):
scriptPath = getattr(settings,'SCRIPTALIAS')
outfile = open('/tmp/out.txt','w')
if '?' in path:
index = path.index('?')
file = path[1:index]
fullCgiPath = os.path.abspath(os.path.join(scriptPath,file))
if os.path.exists(fullCgiPath):
call([fullCgiPath,path[index+1:]],stdout=outfile)
else:
fullCgiPath = os.path.abspath(os.path.join(scriptPath,path[1:].strip()))
d = dict([(field,form.getvalue(field,'')) for field in form.keys()])
args=""
print d,fullCgiPath
call([fullCgiPath],stdout=outfile)
outfile.close()
data = open('/tmp/out.txt').readlines()
k,v= data[0].strip().split(":")
res = Response()
res.headers[k.strip()] = v.strip()
res.data = "".join(data[1:])
res.send(f)
f.close()
return
class Response:
def __init__(self):
self.http_version = "HTTP/1.1"
self.status = "200 OK"
self.headers = {}
self.data = ""
def send(self,f):
self.headers['Content-Length'] = len(self.data)
f.write("%s:%s\r\n" %(self.http_version,self.status))
header_string = CRLF.join(["%s:%s" %(k,v) for k,v in self.headers.items()])
f.write(header_string)
f.write(CRLF)
f.write(CRLF)
f.write(self.data)
f.close()
class WriteObject:
def __init__(self):
self.content=[]
def write(self,string):
self.content.append(string)
def handler(client):
cgitb.enable()
form = cgi.FieldStorage()
f = client.makefile()
method,path,headers = read_headers(f)
print method,path
pprint.pprint(headers)
if hasattr(settings,'SCRIPTALIAS'):
execCgi(path,f)
else:
request = Request(method,path,f)
response = request.process()
response.send(f)
client.close()
return
def read_headers(f):
method,path,version = f.readline().split()
headers = {}
while True:
data = f.readline()
if data.strip() == "":
break
k,v = data.strip().split(":",1)
headers[k.strip()] = v.strip()
return method,path,headers
if __name__ == "__main__":
if hasattr(settings,'PORT'):
port = getattr(settings,'PORT')
elif len(sys.argv) == 2:
port = int(sys.argv[1])
else:
port = 8080
start_server('localhost',port)