-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
288 lines (235 loc) · 9.94 KB
/
server.py
File metadata and controls
288 lines (235 loc) · 9.94 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
import os
import sys
import json
import time
import queue
import socket
import traceback
import mimetypes
import argparse
import threading
from datetime import datetime
from urllib.parse import parse_qs, unquote_plus
# Logger Utility
class Logger:
"""Simple timestamped logger for thread-safe console output."""
@staticmethod
def log(message: str):
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{now}] {message}", flush=True)
# File & Security Utilities
class FileUtils:
@staticmethod
def get_mime_type(path: str) -> str:
"""Guess the MIME type based on file extension."""
mime, _ = mimetypes.guess_type(path)
return mime or "application/octet-stream"
@staticmethod
def safe_join(base: str, *paths: str) -> str:
"""Prevent directory traversal attacks."""
final_path = os.path.abspath(os.path.join(base, *paths))
if not final_path.startswith(os.path.abspath(base)):
raise PermissionError("Path traversal attempt detected")
return final_path
# HTTP Response Builder
class HttpResponse:
"""Helper for constructing HTTP responses."""
STATUS_MESSAGES = {
200: "OK",
201: "Created",
400: "Bad Request",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
500: "Internal Server Error",
}
@staticmethod
def build(status_code, body="", headers=None, content_type="text/html"):
reason = HttpResponse.STATUS_MESSAGES.get(status_code, "OK")
response = f"HTTP/1.1 {status_code} {reason}\r\n"
if isinstance(body, str):
body_bytes = body.encode()
else:
body_bytes = body
base_headers = {
"Server": "Python-MTServer/2.0",
"Content-Type": content_type,
"Content-Length": str(len(body_bytes)),
"Connection": "close",
}
if headers:
base_headers.update(headers)
for k, v in base_headers.items():
response += f"{k}: {v}\r\n"
response += "\r\n"
return response.encode() + body_bytes
# Thread Pool
class ThreadPool:
"""A basic fixed-size thread pool."""
def __init__(self, num_threads: int):
self.tasks = queue.Queue()
self.threads = []
for _ in range(num_threads):
t = threading.Thread(target=self.worker, daemon=True)
t.start()
self.threads.append(t)
def worker(self):
while True:
func, args = self.tasks.get()
try:
func(*args)
except Exception:
Logger.log("Worker thread error:")
traceback.print_exc()
finally:
self.tasks.task_done()
def submit(self, func, *args):
self.tasks.put((func, args))
# HTTP Request Handler
class HttpRequestHandler:
"""Handles HTTP GET and POST requests."""
def __init__(self, base_dir: str):
self.base_dir = base_dir
self.upload_dir = os.path.join(base_dir, "uploads")
self.contact_dir = os.path.join(self.upload_dir, "contacts")
os.makedirs(self.upload_dir, exist_ok=True)
os.makedirs(self.contact_dir, exist_ok=True)
def handle_request(self, client_socket, client_addr, request_text: str):
try:
lines = request_text.split("\r\n")
request_line = lines[0].split()
if len(request_line) < 2:
raise ValueError("Malformed request line")
method, path = request_line[0], request_line[1]
Logger.log(f"{client_addr} → {method} {path}")
# Validate Host header
host_header = next((l for l in lines if l.lower().startswith("host:")), None)
if not host_header:
client_socket.sendall(HttpResponse.build(400, "<h1>400 Bad Request</h1>"))
return
if method == "GET":
self._handle_get(client_socket, path)
elif method == "POST":
clean_path = path.rstrip("/").lower()
if clean_path in ["/contact", "/contact.html"]:
self._handle_contact_post(client_socket, request_text)
else:
self._handle_post_json(client_socket, request_text)
else:
client_socket.sendall(HttpResponse.build(405, "<h1>405 Method Not Allowed</h1>"))
except PermissionError:
client_socket.sendall(HttpResponse.build(403, "<h1>403 Forbidden</h1>"))
except FileNotFoundError:
client_socket.sendall(HttpResponse.build(404, "<h1>404 Not Found</h1>"))
except Exception as e:
Logger.log(f"Error handling request: {e}")
traceback.print_exc()
client_socket.sendall(HttpResponse.build(500, "<h1>500 Internal Server Error</h1>"))
finally:
client_socket.close()
def _handle_get(self, client_socket, path: str):
"""Serve static files from /resources directory."""
if path == "/":
path = "/index.html"
file_path = FileUtils.safe_join(self.base_dir, path.lstrip("/"))
if not os.path.exists(file_path):
raise FileNotFoundError
mime = FileUtils.get_mime_type(file_path)
with open(file_path, "rb") as f:
body = f.read()
client_socket.sendall(HttpResponse.build(200, body, content_type=mime))
def _handle_post_json(self, client_socket, request_text: str):
"""Handle simple JSON uploads."""
try:
headers, body = request_text.split("\r\n\r\n", 1)
data = json.loads(body.strip())
filename = data.get("filename", "upload.txt")
content = data.get("content", "")
save_path = FileUtils.safe_join(self.upload_dir, filename)
with open(save_path, "w") as f:
f.write(content)
Logger.log(f"Uploaded: {filename}")
client_socket.sendall(HttpResponse.build(201, f"<h1>File '{filename}' uploaded</h1>"))
except json.JSONDecodeError:
client_socket.sendall(HttpResponse.build(400, "<h1>400 Invalid JSON</h1>"))
def _handle_contact_post(self, client_socket, request_text: str):
"""Handle POST form submissions from contact.html."""
try:
headers, body = request_text.split("\r\n\r\n", 1)
form_data = parse_qs(body)
name = unquote_plus(form_data.get("name", ["Anonymous"])[0])
email = unquote_plus(form_data.get("email", ["unknown@example.com"])[0])
message = unquote_plus(form_data.get("message", [""])[0])
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
file_path = os.path.join(self.contact_dir, f"contact_{timestamp}.json")
with open(file_path, "w", encoding="utf-8") as f:
json.dump({
"name": name,
"email": email,
"message": message,
"timestamp": timestamp
}, f, indent=2)
Logger.log(f"New contact message saved: {file_path}")
response_html = f"""
<html>
<head>
<meta http-equiv="refresh" content="5;url=/index.html">
<title>Message Sent</title>
</head>
<body style='font-family:Poppins,sans-serif;text-align:center;margin-top:50px;'>
<h1>Thank you, {name}!</h1>
<p>Your message has been received. We’ll reply soon at <b>{email}</b>.</p>
<p>You will be redirected to the homepage in 5 seconds.</p>
<a href="/index.html" style="color:#007bff;text-decoration:none;">Return Home</a>
</body>
</html>
"""
client_socket.sendall(HttpResponse.build(200, response_html))
except Exception as e:
Logger.log(f"Contact POST error: {e}")
client_socket.sendall(HttpResponse.build(500, "<h1>500 Internal Server Error</h1>"))
#--http-server--#
class HTTPServer:
"""The core HTTP server managing socket and workers."""
def __init__(self, host: str, port: int, thread_count: int):
self.host = host
self.port = port
self.thread_pool = ThreadPool(thread_count)
self.base_dir = os.path.join(os.getcwd(), "resources")
self.handler = HttpRequestHandler(self.base_dir)
def start(self):
"""Start listening for incoming connections."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((self.host, self.port))
s.listen(5)
Logger.log(f"HTTP Server started at http://{self.host}:{self.port}")
Logger.log(f"Serving files from: {self.base_dir}")
while True:
client_socket, addr = s.accept()
self.thread_pool.submit(self.handle_client, client_socket, addr)
def handle_client(self, client_socket, addr):
"""Read request and delegate to handler."""
try:
request = client_socket.recv(8192).decode(errors="ignore")
if request:
self.handler.handle_request(client_socket, addr, request)
except Exception as e:
Logger.log(f"Client handling error: {e}")
traceback.print_exc()
client_socket.close()
#---main-function---/
def main():
parser = argparse.ArgumentParser(description="Multi-threaded Modular HTTP Server")
parser.add_argument("port", nargs="?", type=int, default=8080)
parser.add_argument("host", nargs="?", type=str, default="127.0.0.1")
parser.add_argument("threads", nargs="?", type=int, default=10)
args = parser.parse_args()
server = HTTPServer(args.host, args.port, args.threads)
try:
server.start()
except KeyboardInterrupt:
Logger.log("Server shutting down gracefully...")
sys.exit(0)
if __name__ == "__main__":
main()