-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
449 lines (364 loc) · 17.9 KB
/
Copy pathserver.py
File metadata and controls
449 lines (364 loc) · 17.9 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#!/usr/bin/env python3
"""
Multi-threaded HTTP Server
Final Completed Version
"""
import socket
import sys
import os
from datetime import datetime
import json
import threading
import queue
import time
from email.utils import formatdate
import random
import string
class HTTPRequest:
"""Class to represent and parse HTTP requests"""
def __init__(self, request_text):
self.method = None
self.path = None
self.version = None
self.headers = {}
self.body = ""
self.is_valid = False
self.parse(request_text)
def parse(self, request_text):
"""Parse the raw HTTP request"""
try:
header_text, self.body = request_text.split('\r\n\r\n', 1)
header_lines = header_text.split('\r\n')
if not header_lines:
return
request_line = header_lines[0].split(' ')
if len(request_line) != 3:
return
self.method, self.path, self.version = request_line
for line in header_lines[1:]:
if ': ' in line:
key, value = line.split(': ', 1)
self.headers[key] = value
self.is_valid = True
except ValueError:
# This can happen if the request is malformed (e.g., no empty line)
# For simple requests without a body, parsing headers only is fine.
try:
lines = request_text.split('\r\n')
if not lines:
return
request_line = lines[0].split(' ')
if len(request_line) != 3:
return
self.method, self.path, self.version = request_line
for line in lines[1:]:
if ': ' in line:
key, value = line.split(': ', 1)
self.headers[key] = value
self.is_valid = True
except Exception:
self.is_valid = False
except Exception:
self.is_valid = False
class HTTPServer:
def __init__(self, port=8080, host='127.0.0.1', max_threads=10):
"""Initialize the HTTP server with configuration parameters"""
self.port = port
self.host = host
self.max_threads = max_threads
self.server_socket = None
self.running = False
self.connection_queue = queue.Queue()
self.threads = []
self.active_threads = 0
self.thread_lock = threading.Lock()
self.resources_dir = os.path.abspath('resources')
if not os.path.exists(self.resources_dir):
os.makedirs(self.resources_dir)
if not os.path.exists(os.path.join(self.resources_dir, 'uploads')):
os.makedirs(os.path.join(self.resources_dir, 'uploads'))
def worker_thread(self, thread_id):
"""Worker thread function to process connections from the queue"""
while self.running:
try:
client_socket, client_address = self.connection_queue.get(timeout=1)
with self.thread_lock:
self.active_threads += 1
self.log(f"Connection dequeued, assigned to Thread-{thread_id}")
self.handle_client(client_socket, client_address, thread_id)
with self.thread_lock:
self.active_threads -= 1
self.connection_queue.task_done()
except queue.Empty:
continue
except Exception as e:
if self.running:
self.log(f"Error in worker thread: {e}", thread_id)
def log(self, message, thread_id=None):
"""Centralized logging with timestamps"""
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if thread_id:
print(f"[{timestamp}] [Thread-{thread_id}] {message}")
else:
print(f"[{timestamp}] {message}")
def validate_host_header(self, request):
"""Validate the Host header"""
host_header = request.headers.get('Host')
if not host_header:
return self.build_error_response(400, "Bad Request", "Missing Host header")
server_address = f"{self.host}:{self.port}"
# Handle cases where server binds to 0.0.0.0
valid_hosts = [server_address, f"127.0.0.1:{self.port}", f"localhost:{self.port}"]
if host_header not in valid_hosts and self.host != "0.0.0.0":
return self.build_error_response(403, "Forbidden", "Mismatched Host header")
return None
def handle_client(self, client_socket, client_address, thread_id=1):
"""Handle a single client connection with persistent connection support"""
try:
keep_alive = True
request_count = 0
max_requests = 100
while keep_alive and request_count < max_requests:
client_socket.settimeout(30)
try:
request_data = client_socket.recv(8192)
if not request_data:
break
request = HTTPRequest(request_data.decode('utf-8'))
if not request.is_valid:
self.log("Received invalid request", thread_id)
response = self.build_error_response(400, "Bad Request", "Malformed request")
client_socket.sendall(response.encode('utf-8'))
break
self.log(f"Request: {request.method} {request.path} {request.version}", thread_id)
# Security: Host Header Validation
error_response = self.validate_host_header(request)
if error_response:
self.log(f"Host validation: {request.headers.get('Host')} ✗", thread_id)
client_socket.sendall(error_response.encode('utf-8'))
break
self.log(f"Host validation: {request.headers.get('Host')} ✓", thread_id)
connection_header = request.headers.get('Connection', '').lower()
if connection_header == 'close':
keep_alive = False
else: # Default to keep-alive for HTTP/1.1
keep_alive = (request.version == 'HTTP/1.1')
if request.method == 'GET':
response = self.handle_get_request(request, thread_id, keep_alive)
elif request.method == 'POST':
response = self.handle_post_request(request, thread_id, keep_alive)
else:
response = self.build_error_response(405, "Method Not Allowed",
f"Method {request.method} not supported",
keep_alive)
if isinstance(response, bytes):
client_socket.sendall(response)
else:
client_socket.sendall(response.encode('utf-8'))
request_count += 1
if not keep_alive:
break
except socket.timeout:
self.log("Connection timeout", thread_id)
break
except Exception as e:
self.log(f"Error processing request: {e}", thread_id)
client_socket.sendall(self.build_error_response(500, "Internal Server Error", str(e)).encode('utf-8'))
break
self.log(f"Connection: {'keep-alive' if keep_alive and request_count < max_requests else 'close'}", thread_id)
except Exception as e:
self.log(f"Error handling client: {e}", thread_id)
finally:
client_socket.close()
def is_path_safe(self, path):
"""Check for path traversal vulnerabilities"""
requested_path = os.path.abspath(os.path.join(self.resources_dir, path))
return requested_path.startswith(self.resources_dir)
def handle_get_request(self, request, thread_id, keep_alive):
"""Handle GET requests"""
if request.path == '/':
request.path = '/index.html'
file_path = request.path.lstrip('/')
if not self.is_path_safe(file_path):
self.log(f"Forbidden path access attempt: {request.path}", thread_id)
return self.build_error_response(403, "Forbidden", "Path traversal attempt detected", keep_alive)
full_path = os.path.join(self.resources_dir, file_path)
if not os.path.exists(full_path) or not os.path.isfile(full_path):
return self.build_error_response(404, "Not Found",
f"Resource {request.path} not found", keep_alive)
_, ext = os.path.splitext(file_path)
if ext == '.html':
return self.serve_html_file(full_path, thread_id, keep_alive)
elif ext in ['.png', '.jpg', '.jpeg', '.txt']:
return self.serve_binary_file(full_path, thread_id, keep_alive)
else:
return self.build_error_response(415, "Unsupported Media Type",
f"File type {ext} not supported", keep_alive)
def serve_html_file(self, file_path, thread_id, keep_alive):
"""Serve HTML file for rendering in browser"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
headers = [
"HTTP/1.1 200 OK",
"Content-Type: text/html; charset=utf-8",
f"Content-Length: {len(content)}",
f"Date: {self.get_http_date()}",
"Server: Multi-threaded HTTP Server"
]
if keep_alive:
headers.extend(["Connection: keep-alive", "Keep-Alive: timeout=30, max=100"])
else:
headers.append("Connection: close")
response = "\r\n".join(headers) + "\r\n\r\n" + content
self.log(f"Response: 200 OK ({len(content)} bytes transferred)", thread_id)
return response
except Exception as e:
return self.build_error_response(500, "Internal Server Error", str(e), keep_alive)
def serve_binary_file(self, file_path, thread_id, keep_alive):
"""Serve binary files (images, text) for download"""
try:
with open(file_path, 'rb') as f:
content = f.read()
filename = os.path.basename(file_path)
self.log(f"Sending binary file: {filename} ({len(content)} bytes)", thread_id)
headers = [
"HTTP/1.1 200 OK",
"Content-Type: application/octet-stream",
f"Content-Length: {len(content)}",
f'Content-Disposition: attachment; filename="{filename}"',
f"Date: {self.get_http_date()}",
"Server: Multi-threaded HTTP Server"
]
if keep_alive:
headers.extend(["Connection: keep-alive", "Keep-Alive: timeout=30, max=100"])
else:
headers.append("Connection: close")
header_bytes = ("\r\n".join(headers) + "\r\n\r\n").encode('utf-8')
response = header_bytes + content
self.log(f"Response: 200 OK ({len(content)} bytes transferred)", thread_id)
return response
except Exception as e:
return self.build_error_response(500, "Internal Server Error", str(e), keep_alive).encode('utf-8')
def handle_post_request(self, request, thread_id, keep_alive):
"""Handle POST requests for JSON uploads"""
if request.headers.get('Content-Type') != 'application/json':
return self.build_error_response(415, "Unsupported Media Type",
"Content-Type must be application/json", keep_alive)
try:
json_data = json.loads(request.body)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
random_id = ''.join(random.choices(string.ascii_lowercase + string.digits, k=4))
filename = f"upload_{timestamp}_{random_id}.json"
filepath = os.path.join(self.resources_dir, 'uploads', filename)
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(json_data, f, indent=4)
self.log(f"File created: {filename}", thread_id)
response_body = {
"status": "success",
"message": "File created successfully",
"filepath": f"/uploads/{filename}"
}
response_json = json.dumps(response_body)
headers = [
"HTTP/1.1 201 Created",
"Content-Type: application/json",
f"Content-Length: {len(response_json)}",
f"Date: {self.get_http_date()}",
"Server: Multi-threaded HTTP Server"
]
if keep_alive:
headers.extend(["Connection: keep-alive", "Keep-Alive: timeout=30, max=100"])
else:
headers.append("Connection: close")
return "\r\n".join(headers) + "\r\n\r\n" + response_json
except json.JSONDecodeError:
return self.build_error_response(400, "Bad Request", "Invalid JSON format", keep_alive)
except Exception as e:
self.log(f"Error during POST file creation: {e}", thread_id)
return self.build_error_response(500, "Internal Server Error", str(e), keep_alive)
def build_error_response(self, code, status, message, keep_alive=False):
"""Build an HTTP error response"""
body = f"<html><body><h1>{code} {status}</h1><p>{message}</p></body></html>"
headers = [
f"HTTP/1.1 {code} {status}",
"Content-Type: text/html; charset=utf-8",
f"Content-Length: {len(body)}",
f"Date: {self.get_http_date()}",
"Server: Multi-threaded HTTP Server"
]
if code == 503:
headers.append("Retry-After: 30")
if keep_alive:
headers.extend(["Connection: keep-alive", "Keep-Alive: timeout=30, max=100"])
else:
headers.append("Connection: close")
return "\r\n".join(headers) + "\r\n\r\n" + body
def get_http_date(self):
"""Get current date in RFC 7231 format"""
return formatdate(timeval=None, localtime=False, usegmt=True)
def start(self):
"""Start the HTTP server"""
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(50)
self.running = True
self.log(f"HTTP Server started on http://{self.host}:{self.port}")
self.log(f"Thread pool size: {self.max_threads}")
self.log("Serving files from 'resources' directory")
self.log("Press Ctrl+C to stop the server")
for i in range(self.max_threads):
thread = threading.Thread(target=self.worker_thread, args=(i + 1,))
thread.daemon = True
thread.start()
self.threads.append(thread)
while self.running:
try:
client_socket, client_address = self.server_socket.accept()
self.log(f"Connection from {client_address[0]}:{client_address[1]}")
if self.connection_queue.qsize() >= self.max_threads:
self.log("Warning: Thread pool saturated, queuing connection")
self.connection_queue.put((client_socket, client_address))
with self.thread_lock:
status_log_interval = 5 # Log status every 5 seconds
if int(time.time()) % status_log_interval == 0:
self.log(f"Thread pool status: {self.active_threads}/{self.max_threads} active")
except OSError: # Socket closed
break
except Exception as e:
if self.running:
self.log(f"Error accepting connection: {e}")
except Exception as e:
self.log(f"Failed to start server: {e}")
sys.exit(1)
finally:
self.stop()
def stop(self):
"""Gracefully stop the server"""
self.running = False
if self.server_socket:
self.server_socket.close()
self.log("\nServer stopped")
def parse_arguments():
"""Parse command-line arguments"""
port = 8080
host = '127.0.0.1'
max_threads = 10
if len(sys.argv) > 1:
try: port = int(sys.argv[1])
except ValueError: print("Invalid port. Using default 8080.")
if len(sys.argv) > 2:
host = sys.argv[2]
if len(sys.argv) > 3:
try: max_threads = int(sys.argv[3])
except ValueError: print("Invalid thread count. Using default 10.")
return port, host, max_threads
if __name__ == "__main__":
port, host, max_threads = parse_arguments()
server = HTTPServer(port, host, max_threads)
try:
server.start()
except KeyboardInterrupt:
server.stop()