-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
352 lines (312 loc) · 12.5 KB
/
server.py
File metadata and controls
352 lines (312 loc) · 12.5 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
import socket, threading, queue, os, argparse, time, json, random, string, posixpath
from urllib.parse import unquote
from email.utils import formatdate
from datetime import datetime
# config
host = "127.0.0.1"
port = 8080
threads = 10
backlog = 50
header_max = 8192
keepalive_timeout = 30
keepalive_max = 100
server_name = "Multi-threaded HTTP Server"
allowed_exts = {"html","txt","png","jpg","jpeg"}
# resolve resources dir safely
try:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
except NameError:
BASE_DIR = os.getcwd()
resources_dir = os.path.join(BASE_DIR, "resources")
# tiny logs
def nowstamp(): return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def log(x): print(f"[{nowstamp()}] {x}", flush=True)
def tlog(x): print(f"[{nowstamp()}] [{threading.current_thread().name}] {x}", flush=True)
# http helpers
def http_date(): return formatdate(usegmt=True)
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")
def send_resp(sock, code, headers=None, body=b""):
h = {} if headers is None else dict(headers)
h.setdefault("Date", http_date())
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"
head = "".join(f"{k}: {v}\r\n" for k,v in h.items())
sock.sendall(start.encode("ascii") + head.encode("ascii") + b"\r\n" + (body or b""))
def send_err(sock, code, msg="", common=None):
b = (f"<!doctype html><html><head><meta charset='utf-8'><title>{code} {reason(code)}</title></head>"
f"<body><h1>{code} {reason(code)}</h1><p>{msg}</p></body></html>").encode("utf-8")
hh = {"Content-Type":"text/html; charset=utf-8"}
if common: hh.update(common)
send_resp(sock, code, hh, b)
tlog(f"Response: {code} {reason(code)} ({len(b)} bytes transferred)")
# request reading
def read_headers(sock, limit=header_max):
data = b""
while b"\r\n\r\n" not in data:
chunk = sock.recv(1024)
if not chunk: break
data += chunk
if len(data) > limit:
return None, b""
if b"\r\n\r\n" not in data:
return None, b""
head, leftover = data.split(b"\r\n\r\n", 1)
return head, leftover
def parse_head(head_bytes):
try:
txt = head_bytes.decode("iso-8859-1")
lines = txt.split("\r\n")
p0 = lines[0].split()
if len(p0) != 3: return None
method, path, ver = p0
H = {}
for ln in lines[1:]:
if not ln.strip(): continue
if ":" not in ln: return None
k, v = ln.split(":", 1)
H[k.strip().lower()] = v.strip()
return method, path, ver, H
except:
return None
def conn_policy(ver, H):
c = H.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"
# security + path helpers
def host_ok(host_header, bind_host, bind_port):
ok = {f"localhost:{bind_port}", f"127.0.0.1:{bind_port}"}
if bind_host not in ("0.0.0.0","",None):
ok.add(f"{bind_host}:{bind_port}")
return host_header in ok
def decode_and_norm(pth):
d = unquote(pth or "")
n = posixpath.normpath(d if d else "/")
if not n.startswith("/"): n = "/" + n
return d, n
def looks_bad(decoded_path):
s = decoded_path.lower()
if ("\\" in s or s.startswith("//") or "/./" in s or s.endswith("/.")
or s.startswith("./") or ".." in s):
return True
return False
def safe_join(nrm):
rel = nrm.lstrip("/")
want = os.path.realpath(os.path.join(resources_dir, rel))
base = os.path.realpath(resources_dir)
if not want.startswith(base + os.sep) and want != base:
return None
return want
# handlers
def handle_get(sock, raw_path, common):
dec, nrm = decode_and_norm(raw_path)
if looks_bad(dec):
tlog(f"Security: traversal in path '{dec}' → 403")
send_err(sock, 403, "Path traversal blocked.", common); return
if nrm == "/":
nrm = "/index.html"
fp = safe_join(nrm)
if not fp:
tlog(f"Security: canonicalization escaped resources for '{dec}' → 403")
send_err(sock, 403, "Forbidden.", common); return
if not (os.path.exists(fp) and os.path.isfile(fp)):
send_err(sock, 404, "File not found.", common); return
ext = os.path.splitext(fp)[1].lstrip(".").lower()
if ext not in allowed_exts:
tlog(f"Security: unsupported extension requested ({ext}) → 415")
send_err(sock, 415, "Only .html, .txt, .png, .jpg/.jpeg allowed.", common); return
size = os.path.getsize(fp)
if ext == "html":
hh = {"Content-Type":"text/html; charset=utf-8"}; hh.update(common)
with open(fp, "rb") as f: body = f.read()
send_resp(sock, 200, hh, body)
tlog(f"Response: 200 OK ({len(body)} bytes transferred)")
tlog(f"Connection: {common.get('Connection','')}")
else:
hh = {"Content-Type":"application/octet-stream",
"Content-Disposition": f'attachment; filename="{os.path.basename(fp)}"'}
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"
tlog(f"Sending binary file: {os.path.basename(fp)} ({size} bytes)")
sock.sendall(head.encode("ascii"))
sent = 0
with open(fp, "rb") as f:
while True:
chunk = f.read(8192)
if not chunk: break
sock.sendall(chunk); sent += len(chunk)
tlog(f"Response: 200 OK ({sent} bytes transferred)")
tlog(f"Connection: {common.get('Connection','')}")
def handle_post(sock, raw_path, ver, H, leftover, common):
dec, nrm = decode_and_norm(raw_path)
tlog(f"POST target: {dec}")
if nrm != "/upload":
send_err(sock, 404, "Not Found.", common); return
ct = H.get("content-type","").split(";")[0].strip().lower()
if ct != "application/json":
tlog("Security: wrong Content-Type for POST → 415")
send_err(sock, 415, "Only application/json accepted.", common); return
if "content-length" not in H:
send_err(sock, 411, "Content-Length required.", common); return
try: L = int(H["content-length"])
except: L = -1
if L < 0 or L > 5*1024*1024:
send_err(sock, 413, "Payload Too Large.", common); return
tlog(f"POST Content-Length: {L}")
body = leftover
while len(body) < L:
x = sock.recv(min(8192, L - len(body)))
if not x: break
body += x
try:
json.loads(body.decode("utf-8"))
except:
send_err(sock, 400, "Invalid JSON.", common); return
up = os.path.join(resources_dir, "uploads"); os.makedirs(up, exist_ok=True)
tstr = time.strftime("%Y%m%d_%H%M%S", time.localtime())
rid = "".join(random.choice(string.ascii_lowercase+string.digits) for _ in range(4))
fname = f"upload_{tstr}_{rid}.json"
with open(os.path.join(up, fname), "wb") as f: f.write(body)
out = {"status":"success","message":"File created successfully","filepath":f"/uploads/{fname}"}
jj = json.dumps(out).encode("utf-8")
hh = {"Content-Type":"application/json"}; hh.update(common)
send_resp(sock, 201, hh, jj)
tlog(f"Response: 201 Created ({len(jj)} bytes transferred)")
tlog(f"Connection: {common.get('Connection','')}")
# per-connection loop
def serve_client(conn, addr, bind_host, bind_port):
conn.settimeout(keepalive_timeout)
reqs = 0
try:
while True:
head, rest = read_headers(conn, header_max)
if head is None: return
parsed = parse_head(head)
if not parsed:
send_err(conn, 400, "Malformed request."); return
method, path, ver, H = parsed
tlog(f"Request: {method} {path} {ver}")
hv = H.get("host")
if not hv:
tlog("Host validation: (missing) ✗")
send_err(conn, 400, "Missing Host header."); return
if not host_ok(hv, bind_host, bind_port):
tlog(f"Host validation: {hv} ✗")
send_err(conn, 403, "Invalid Host header."); return
tlog(f"Host validation: {hv} ✓")
policy = conn_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_err(conn, 405, "Only GET and POST are allowed.", common)
except:
send_err(conn, 500, "Server error.", common); return
reqs += 1
if policy != "keep-alive" or reqs >= keepalive_max:
return
except socket.timeout:
tlog("idle timeout")
except:
pass
finally:
try: conn.close()
except: pass
# fixed-size ThreadPool
class ThreadPool:
def __init__(self, n, qmax=100):
self.q = queue.Queue(maxsize=qmax)
self.n = n
self.busy = set()
self.alive = True
self.lock = threading.Lock()
self.workers = []
for i in range(n):
t = threading.Thread(target=self.work, 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()
def work(self):
while self.alive:
try:
c, a, bh, bp = self.q.get(timeout=0.5)
except queue.Empty:
continue
nm = threading.current_thread().name
tlog(f"Connection dequeued, assigned to {nm}")
tlog(f"Connection from {a[0]}:{a[1]}")
with self.lock: self.busy.add(nm)
try:
serve_client(c, a, bh, bp)
finally:
with self.lock: self.busy.discard(nm)
self.q.task_done()
def push(self, item):
try:
if self.count() >= self.n:
log("Warning: Thread pool saturated, queuing connection")
self.q.put_nowait(item)
log("Connection queued")
return True
except queue.Full:
return False
def count(self):
with self.lock: return len(self.busy)
def watch(self):
while self.alive:
time.sleep(30)
log(f"Thread pool status: {self.count()}/{self.n} active")
def stop(self):
self.alive = False
for t in self.workers:
t.join(timeout=1.0)
# main / accept loop
def main():
ap = argparse.ArgumentParser()
ap.add_argument("port", nargs="?", type=int, default=port)
ap.add_argument("host", nargs="?", default=host)
ap.add_argument("threads", nargs="?", type=int, default=threads)
args = ap.parse_args()
bind_host = args.host
bind_port = args.port
max_threads = args.threads if args.threads > 0 else threads
os.makedirs(resources_dir, exist_ok=True)
log(f"HTTP Server started on http://{bind_host}:{bind_port}")
log(f"Thread pool size: {max_threads}")
log(f"Serving files from 'resources' directory")
log(f"Press Ctrl+C to stop the server")
pool = ThreadPool(max_threads)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((bind_host, bind_port)); s.listen(backlog)
while True:
try:
c, ainfo = s.accept()
if not pool.push((c, ainfo, bind_host, bind_port)):
log("Warning: Thread pool saturated, returning 503")
hdrs = {"Content-Type":"text/html; charset=utf-8","Connection":"close","Retry-After":"1"}
bod = (b"<!doctype html><html><body><h1>503 Service Unavailable</h1>"
b"<p>Server is busy. Please try again.</p></body></html>")
try: send_resp(c, 503, hdrs, bod)
except: pass
try: c.close()
except: pass
except KeyboardInterrupt:
break
except:
continue
pool.stop()
if __name__ == "__main__":
main()