-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
377 lines (328 loc) · 13 KB
/
server.py
File metadata and controls
377 lines (328 loc) · 13 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
import socket, threading, queue, os, sys, time, json, random, string, posixpath
from urllib.parse import unquote
from email.utils import formatdate
from datetime import datetime
host = "127.0.0.1"
port = 8080
threads = 10
backlog = 50
header_max = 8192
keepalive_timeout = 30
keepalive_max = 100
resources_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources")
server_name = "Multi-threaded HTTP Server"
allowed_exts = {"html","txt","png","jpg","jpeg"}
# Get current time as string
def stamp():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Print message with time
def say(msg=""):
print(f"[{stamp()}] {msg}", flush=True)
# Print message with time and thread name
def sayt(msg=""):
print(f"[{stamp()}] [{threading.current_thread().name}] {msg}", flush=True)
# Get current HTTP date
def http_now():
return formatdate(usegmt=True)
# Get HTTP status reason
def reason(code):
m = {200:"OK",201:"Created",400:"Bad Request",403:"Forbidden",404:"Not Found",
405:"Method Not Allowed",411:"Length Required",413:"Payload Too Large",
415:"Unsupported Media Type",500:"Internal Server Error",503:"Service Unavailable"}
return m.get(code, "OK")
# Send HTTP response
def send_response(sock, code, headers=None, body=b""):
H = {} if headers is None else dict(headers)
H.setdefault("Date", http_now())
H.setdefault("Server", server_name)
if body is not None:
H["Content-Length"] = str(len(body))
start = f"HTTP/1.1 {code} {reason(code)}\r\n"
txt = start + "".join(f"{k}: {v}\r\n" for k, v in H.items()) + "\r\n"
sock.sendall(txt.encode("ascii") + (body or b""))
# Send HTTP error
def send_error(sock, code, text="", common=None):
body = (f"<!doctype html><html><head><meta charset='utf-8'><title>{code} {reason(code)}</title></head>"
f"<body><h1>{code} {reason(code)}</h1><p>{text}</p></body></html>").encode("utf-8")
hh = {"Content-Type":"text/html; charset=utf-8"}
if common: hh.update(common)
send_response(sock, code, hh, body)
sayt(f"Response: {code} {reason(code)} ({len(body)} bytes transferred)")
# Read HTTP request header
def read_request_head(sock, limit=header_max):
buf = b""
while b"\r\n\r\n" not in buf:
chunk = sock.recv(1024)
if not chunk: break
buf += chunk
if len(buf) > limit: # too big
return None, b""
if b"\r\n\r\n" not in buf:
return None, b""
head, rest = buf.split(b"\r\n\r\n", 1)
return head, rest
# Parse HTTP request
def parse_request(head_bytes):
try:
s = head_bytes.decode("iso-8859-1")
lines = s.split("\r\n")
first = lines[0].split()
if len(first) != 3: return None
method, path, ver = first
headers = {}
for ln in lines[1:]:
if not ln.strip(): continue
if ":" not in ln: return None
k, v = ln.split(":", 1)
headers[k.strip().lower()] = v.strip()
return method, path, ver, headers
except:
return None
# Check keep-alive policy
def keep_policy(ver, headers):
c = headers.get("connection","").lower()
if ver == "HTTP/1.1":
return "keep-alive" if c != "close" else "close"
else:
return "keep-alive" if c == "keep-alive" else "close"
# Validate host header
def ok_host(host_header, bind_host, bind_port):
good = {f"localhost:{bind_port}", f"127.0.0.1:{bind_port}"}
if bind_host not in ("0.0.0.0","",None):
good.add(f"{bind_host}:{bind_port}")
return host_header in good
# Decode and normalize URL path
def url_decode_norm(path_text):
dec = unquote(path_text or "")
norm = posixpath.normpath(dec if dec else "/")
if not norm.startswith("/"): norm = "/" + norm
return dec, norm
# Check for bad path
def smells_bad(decoded):
s = decoded.lower()
if ("\\" in s) or s.startswith("//") or "/./" in s or s.endswith("/.") or s.startswith("./") or ".." in s:
return True
return False
# Join path safely
def join_safe(norm_path):
rel = norm_path.lstrip("/")
real = os.path.realpath(os.path.join(resources_dir, rel))
base = os.path.realpath(resources_dir)
if not real.startswith(base + os.sep) and real != base:
return None
return real
# Handle GET request
def handle_get(sock, raw_path, common):
dec, norm = url_decode_norm(raw_path)
if smells_bad(dec):
sayt(f"Security: traversal in path '{dec}' → 403")
send_error(sock, 403, "Path traversal blocked.", common); return
if norm == "/":
norm = "/index.html"
file_path = join_safe(norm)
if not file_path:
sayt(f"Security: canonicalization escaped resources for '{dec}' → 403")
send_error(sock, 403, "Forbidden.", common); return
if not (os.path.exists(file_path) and os.path.isfile(file_path)):
send_error(sock, 404, "File not found.", common); return
ext = os.path.splitext(file_path)[1].lstrip(".").lower()
if ext not in allowed_exts:
sayt(f"Security: unsupported extension requested ({ext}) → 415")
send_error(sock, 415, "Only .html, .txt, .png, .jpg/.jpeg allowed.", common); return
size = os.path.getsize(file_path)
if ext == "html":
hh = {"Content-Type":"text/html; charset=utf-8"}; hh.update(common)
with open(file_path, "rb") as f: body = f.read()
send_response(sock, 200, hh, body)
sayt(f"Response: 200 OK ({len(body)} bytes transferred)")
sayt(f"Connection: {common.get('Connection','')}")
else:
hh = {"Content-Type":"application/octet-stream",
"Content-Disposition": f'attachment; filename="{os.path.basename(file_path)}"'}
hh.update(common)
head = f"HTTP/1.1 200 {reason(200)}\r\n" + "".join(
f"{k}: {v}\r\n" for k,v in {**hh, "Content-Length": str(size)}.items()
) + "\r\n"
sayt(f"Sending binary file: {os.path.basename(file_path)} ({size} bytes)")
sock.sendall(head.encode("ascii"))
sent = 0
with open(file_path, "rb") as f:
while True:
chunk = f.read(8192)
if not chunk: break
sock.sendall(chunk); sent += len(chunk)
sayt(f"Response: 200 OK ({sent} bytes transferred)")
sayt(f"Connection: {common.get('Connection','')}")
# Generate random 4-char string
def _rand4():
return "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(4))
# Handle POST request
def handle_post(sock, raw_path, ver, headers, leftover, common):
dec, norm = url_decode_norm(raw_path)
sayt(f"POST target: {dec}")
if norm != "/upload":
send_error(sock, 404, "Not Found.", common); return
ct = headers.get("content-type","").split(";")[0].strip().lower()
if ct != "application/json":
sayt("Security: wrong Content-Type for POST → 415")
send_error(sock, 415, "Only application/json accepted.", common); return
if "content-length" not in headers:
send_error(sock, 411, "Content-Length required.", common); return
try: L = int(headers["content-length"])
except: L = -1
if L < 0 or L > 5*1024*1024:
send_error(sock, 413, "Payload Too Large.", common); return
sayt(f"POST Content-Length: {L}")
body = leftover
while len(body) < L:
chunk = sock.recv(min(8192, L - len(body)))
if not chunk: break
body += chunk
try:
json.loads(body.decode("utf-8"))
except:
send_error(sock, 400, "Invalid JSON.", common); return
updir = os.path.join(resources_dir, "uploads"); os.makedirs(updir, exist_ok=True)
tstr = time.strftime("%Y%m%d_%H%M%S", time.localtime())
fn = f"upload_{tstr}_{_rand4()}.json"
with open(os.path.join(updir, fn), "wb") as f:
f.write(body)
resp = {"status":"success","message":"File created successfully","filepath":f"/uploads/{fn}"}
jj = json.dumps(resp).encode("utf-8")
hh = {"Content-Type":"application/json"}; hh.update(common)
send_response(sock, 201, hh, jj)
sayt(f"Response: 201 Created ({len(jj)} bytes transferred)")
sayt(f"Connection: {common.get('Connection','')}")
# Serve client connection
def serve_conn(conn, addr, bind_host, bind_port):
conn.settimeout(keepalive_timeout)
seen = 0
try:
while True:
head, rest = read_request_head(conn, header_max)
if head is None: return
parsed = parse_request(head)
if not parsed:
send_error(conn, 400, "Malformed request."); return
method, path, ver, H = parsed
sayt(f"Request: {method} {path} {ver}")
hv = H.get("host")
if not hv:
sayt("Host validation: (missing) ✗")
send_error(conn, 400, "Missing Host header."); return
if not ok_host(hv, bind_host, bind_port):
sayt(f"Host validation: {hv} ✗")
send_error(conn, 403, "Invalid Host header."); return
sayt(f"Host validation: {hv} ✓")
policy = keep_policy(ver, H)
common = {"Connection": policy, "Keep-Alive": f"timeout={keepalive_timeout}, max={keepalive_max}"}
try:
if method == "GET":
handle_get(conn, path, common)
elif method == "POST":
handle_post(conn, path, ver, H, rest, common)
else:
send_error(conn, 405, "Only GET and POST are allowed.", common)
except:
send_error(conn, 500, "Server error.", common); return
seen += 1
if policy != "keep-alive" or seen >= keepalive_max:
return
except socket.timeout:
sayt("idle timeout")
except:
pass
finally:
try: conn.close()
except: pass
# Thread pool for handling connections
class ThreadPool:
def __init__(self, n, qmax=100):
self.q = queue.Queue(maxsize=qmax)
self.n = n
self.busy = set()
self.lock = threading.Lock()
self.alive = True
self.workers = []
for i in range(n):
t = threading.Thread(target=self.worker, name=f"Thread-{i+1}", daemon=True)
t.start(); self.workers.append(t)
self.mon = threading.Thread(target=self.watch, name="PoolMonitor", daemon=True)
self.mon.start()
# Worker thread loop
def worker(self):
while self.alive:
try:
c, a, bh, bp = self.q.get(timeout=0.5)
except queue.Empty:
continue
nm = threading.current_thread().name
sayt(f"Connection dequeued, assigned to {nm}")
sayt(f"Connection from {a[0]}:{a[1]}")
with self.lock: self.busy.add(nm)
try:
serve_conn(c, a, bh, bp)
finally:
with self.lock: self.busy.discard(nm)
self.q.task_done()
# Add connection to queue
def put(self, item):
try:
if self.count() >= self.n:
say("Warning: Thread pool saturated, queuing connection")
self.q.put_nowait(item)
say("Connection queued")
return True
except queue.Full:
return False
# Count active threads
def count(self):
with self.lock: return len(self.busy)
# Monitor thread pool
def watch(self):
while self.alive:
time.sleep(30)
say(f"Thread pool status: {self.count()}/{self.n} active")
# Stop thread pool
def stop(self):
self.alive = False
for t in self.workers:
t.join(timeout=1.0)
# Main server function
def main():
host = "127.0.0.1"
port = 8080
threads = 10
if(len(sys.argv)>1):
port = int(sys.argv[1])
if(len(sys.argv)>2):
host = sys.argv[2]
if(len(sys.argv)>3):
threads = int(sys.argv[3])
say(f"HTTP Server started on http://{host}:{port}")
say(f"Thread pool size: {threads}")
say(f"Serving files from 'resources' directory")
say(f"Press Ctrl+C to stop the server")
pool = ThreadPool(threads)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind((host, port)); srv.listen(backlog)
while True:
try:
c, addr = srv.accept()
if not pool.put((c, addr, host, port)):
say("Warning: Thread pool saturated, returning 503")
hdr = {"Content-Type":"text/html; charset=utf-8","Connection":"close","Retry-After":"1"}
body = (b"<!doctype html><html><body><h1>503 Service Unavailable</h1>"
b"<p>Server is busy. Please try again.</p></body></html>")
try: send_response(c, 503, hdr, body)
except: pass
try: c.close()
except: pass
except KeyboardInterrupt:
break
except:
continue
pool.stop()
if __name__ == "__main__":
main()