-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
177 lines (131 loc) · 4.84 KB
/
server.py
File metadata and controls
177 lines (131 loc) · 4.84 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
import os
import re
import shutil
import socket
class HTTPResponseCode(object):
def __init__(self, response, message=None, error=False):
self.response = response
self.message = message
self.error = error
def __repr__(self):
return self.message
HTTP404 = HTTPResponseCode("404", "<h1>Not Found.</h1>\n", True)
HTTP301 = HTTPResponseCode("301", "Created.\n")
HTTP200 = HTTPResponseCode("200", "Okay.\n")
HTTP500 = HTTPResponseCode("500", "<h1>Bad Gateway.</h1>", True)
HTTP403 = HTTPResponseCode("403", "<h1>Forbidden.</h1>", True)
class SimpleHTTPServer(object):
def __init__(self, address='127.0.0.1', port=8080):
self.location = os.path.dirname(os.path.abspath(__file__))
self.server = socket.socket()
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host = address
self.port = port
self.conn = None
self.addr = None
def run(self):
self.server.bind((self.host, self.port))
self.server.listen(10)
print('Press Ctrl+C to stop server...')
while True:
try:
self.conn, self.addr = self.server.accept()
msg = self.receive_message()
request = self.parse_request(msg)
if request["method"] == 'GET':
r = self.GET(request["resource"])
elif request["method"] == 'POST':
r = self.POST(request["resource"])
elif request["method"] == 'DELETE':
r = self.DELETE(request["resource"])
elif request["method"] == 'PUT':
r = self.PUT(request["resource"])
elif request["method"] == 'OPTIONS':
r = self.OPTIONS(request["resource"])
else:
r = HTTP500
self.conn.send(r.message)
self.conn.close()
except KeyboardInterrupt:
self.server.close()
return None
def parse_request(self, req):
request = {}
line = req.split("\n")
method, path, protocol = line[0].split(" ")
request['method'] = method
request['resource'] = path[1:] if len(path) > 1 else path
request['protocol'] = protocol
parse = re.findall(r"(?P<name>.*?): (?P<value>.*?)\r\n", req)
request['Content-Type'] = 'text/html;'
request['charset'] = 'UTF-8'
for name, value in parse:
request[name] = value
return request
def receive_message(self, buffsize=4096):
msg = ''
while True:
msg_part = self.conn.recv(buffsize)
msg += msg_part
if len(msg_part) < buffsize:
break
self.conn.shutdown(socket.SHUT_RD)
return msg
def HEAD(self, path):
if os.path.exists(path):
return HTTP200
else:
return HTTP404
def DELETE(self, path):
head = self.HEAD(path)
if not head.error:
if(os.path.isdir(path)):
shutil.rmtree(path)
else:
os.remove(path)
return HTTP200
return HTTP404
def GET(self, path):
head = self.HEAD(path)
if not head.error:
if(os.access(path, os.R_OK)): #check if we have privileges
if(os.path.isdir(path)):
self.conn.send(" \n".join(os.listdir(path)))
return HTTP200
else:
if(path[-3:] == ".py" and "server.py" not in path): #only run python files for now
if(os.access(path, os.X_OK)):
os.system("python %s" % path)
return HTTP200
else:
return HTTP500
try:
data = ""
with open(path, 'rb') as f:
data += f.read()
self.conn.sendall(data)
except (TypeError, IOError):
return HTTP500
return HTTP200
else:
return HTTP403
return HTTP404
def OPTIONS(self, path):
head = self.HEAD(path)
if not head.error:
self.conn.send("HEAD, POST, PUT, GET, DELETE")
return HTTP200
return HTTP404
def POST(self, path):
head = self.HEAD(path)
if not head.error:
if os.access(path, os.R_OK): #check if we have privileges
f = os.open(path, os.O_RDWR|os.CREAT)
f.close()
else:
return HTTP403
return HTTP404
def PUT(self, path):
f = os.open(path, os.O_RDWR|os.CREAT)
f.close()
return HTTP200