-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
428 lines (345 loc) · 17 KB
/
server.py
File metadata and controls
428 lines (345 loc) · 17 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
#!/usr/bin/env python3
import socket
import threading
import os
import sys
import json
import time
import datetime
import random
import string
from urllib.parse import unquote
class HTTPServer:
def __init__(self, host='127.0.0.1', port=8080, max_threads=10):
self.host = host
self.port = port
self.max_threads = max_threads
self.resources_dir = 'resources'
self.uploads_dir = os.path.join(self.resources_dir, 'uploads')
self.socket = None
self.thread_pool = []
self.connection_queue = []
self.active_threads = 0
self.lock = threading.Lock()
self.running = False
# Ensure resources and uploads directories exist
os.makedirs(self.resources_dir, exist_ok=True)
os.makedirs(self.uploads_dir, exist_ok=True)
def start(self):
"""Start the HTTP server"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.socket.bind((self.host, self.port))
self.socket.listen(50) # Queue size of at least 50
self.running = True
print(f"[{self._get_timestamp()}] HTTP Server started on http://{self.host}:{self.port}")
print(f"[{self._get_timestamp()}] Thread pool size: {self.max_threads}")
print(f"[{self._get_timestamp()}] Serving files from '{self.resources_dir}' directory")
print(f"[{self._get_timestamp()}] Press Ctrl+C to stop the server")
while self.running:
try:
client_socket, client_address = self.socket.accept()
self._handle_connection(client_socket, client_address)
except socket.error:
if self.running:
print(f"[{self._get_timestamp()}] Socket error occurred")
break
except KeyboardInterrupt:
print(f"[{self._get_timestamp()}] Server shutting down...")
break
except Exception as e:
print(f"[{self._get_timestamp()}] Error starting server: {e}")
finally:
self.stop()
def stop(self):
"""Stop the HTTP server"""
self.running = False
if self.socket:
self.socket.close()
# Wait for all threads to finish
for thread in self.thread_pool:
if thread.is_alive():
thread.join()
print(f"[{self._get_timestamp()}] Server stopped")
def _get_timestamp(self):
"""Get current timestamp in RFC 7231 format"""
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def _handle_connection(self, client_socket, client_address):
"""Handle incoming client connection"""
with self.lock:
if self.active_threads < self.max_threads:
# Create and start a new thread for this connection
thread = threading.Thread(
target=self._process_client,
args=(client_socket, client_address)
)
thread.daemon = True
self.thread_pool.append(thread)
self.active_threads += 1
thread.start()
print(f"[{self._get_timestamp()}] Thread pool status: {self.active_threads}/{self.max_threads} active")
else:
# Queue the connection if all threads are busy
self.connection_queue.append((client_socket, client_address))
print(f"[{self._get_timestamp()}] Warning: Thread pool saturated, queuing connection from {client_address}")
def _process_client(self, client_socket, client_address):
"""Process client requests in a separate thread"""
thread_name = threading.current_thread().name
keep_alive = True
request_count = 0
max_requests = 100
timeout = 30
print(f"[{self._get_timestamp()}] [{thread_name}] Connection from {client_address[0]}:{client_address[1]}")
try:
while keep_alive and request_count < max_requests:
# Set socket timeout
client_socket.settimeout(timeout)
# Receive request
request_data = client_socket.recv(8192)
if not request_data:
break
request_count += 1
print(f"[{self._get_timestamp()}] [{thread_name}] Request #{request_count} received")
# Parse request
request = self._parse_request(request_data.decode('utf-8', errors='ignore'))
if not request:
response = self._create_error_response(400, "Bad Request")
client_socket.sendall(response.encode())
break
print(f"[{self._get_timestamp()}] [{thread_name}] Request: {request['method']} {request['path']} {request['version']}")
# Validate Host header
host_validation = self._validate_host(request['headers'])
if not host_validation[0]:
response = self._create_error_response(host_validation[1], host_validation[2])
client_socket.sendall(response.encode())
break
print(f"[{self._get_timestamp()}] [{thread_name}] Host validation: {request['headers'].get('Host', 'MISSING')} ✓")
# Process based on method
if request['method'] == 'GET':
response = self._handle_get_request(request)
elif request['method'] == 'POST':
response = self._handle_post_request(request)
else:
response = self._create_error_response(405, "Method Not Allowed")
# Send response
client_socket.sendall(response.encode() if isinstance(response, str) else response)
# Check if connection should be kept alive
connection_header = request['headers'].get('Connection', '').lower()
if request['version'] == 'HTTP/1.0':
keep_alive = connection_header == 'keep-alive'
else: # HTTP/1.1
keep_alive = connection_header != 'close'
if not keep_alive:
break
except socket.timeout:
print(f"[{self._get_timestamp()}] [{thread_name}] Connection timed out")
except Exception as e:
print(f"[{self._get_timestamp()}] [{thread_name}] Error processing client: {e}")
try:
error_response = self._create_error_response(500, "Internal Server Error")
client_socket.sendall(error_response.encode())
except:
pass
finally:
client_socket.close()
with self.lock:
self.active_threads -= 1
print(f"[{self._get_timestamp()}] [{thread_name}] Connection closed")
# Process queued connections if any
if self.connection_queue and self.active_threads < self.max_threads:
queued_socket, queued_address = self.connection_queue.pop(0)
print(f"[{self._get_timestamp()}] Connection dequeued, assigned to {thread_name}")
self._handle_connection(queued_socket, queued_address)
def _parse_request(self, request_data):
"""Parse HTTP request"""
lines = request_data.split('\r\n')
if not lines:
return None
# Parse request line
request_line = lines[0].split(' ')
if len(request_line) != 3:
return None
method, path, version = request_line
# Parse headers
headers = {}
for line in lines[1:]:
if ':' in line:
key, value = line.split(':', 1)
headers[key.strip()] = value.strip()
elif line == '': # End of headers
break
# Find body (if any)
body_start = request_data.find('\r\n\r\n')
body = request_data[body_start+4:] if body_start != -1 else ''
return {
'method': method,
'path': path,
'version': version,
'headers': headers,
'body': body
}
def _validate_host(self, headers):
"""Validate Host header for security"""
host = headers.get('Host')
if not host:
return (False, 400, "Bad Request - Missing Host header")
# Check if host matches server's address
if host != f"{self.host}:{self.port}" and host != "localhost:8080":
return (False, 403, "Forbidden - Host mismatch")
return (True, None, None)
def _validate_path(self, path):
"""Validate path to prevent directory traversal attacks"""
# Remove leading slash
path = path.lstrip('/')
# Decode URL encoding
path = unquote(path)
# Check for directory traversal patterns
if '..' in path or path.startswith('/') or '//' in path:
return None
# Construct full path
full_path = os.path.join(self.resources_dir, path)
# Canonicalize path
full_path = os.path.abspath(full_path)
resources_path = os.path.abspath(self.resources_dir)
# Ensure path is within resources directory
if not full_path.startswith(resources_path):
return None
return full_path
def _get_content_type(self, file_path):
"""Determine content type based on file extension"""
_, ext = os.path.splitext(file_path)
ext = ext.lower()
if ext == '.html':
return 'text/html; charset=utf-8'
elif ext in ['.png', '.jpg', '.jpeg', '.txt']:
return 'application/octet-stream'
else:
return None # Unsupported media type
def _create_headers(self, status_code, content_type=None, content_length=0, connection='close'):
"""Create HTTP response headers"""
status_text = {
200: 'OK',
201: 'Created',
400: 'Bad Request',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
415: 'Unsupported Media Type',
500: 'Internal Server Error',
503: 'Service Unavailable'
}
headers = [
f"HTTP/1.1 {status_code} {status_text.get(status_code, 'Unknown')}",
f"Date: {datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S GMT')}",
"Server: Multi-threaded HTTP Server"
]
if content_type:
headers.append(f"Content-Type: {content_type}")
if content_length > 0:
headers.append(f"Content-Length: {content_length}")
headers.append(f"Connection: {connection}")
if connection == 'keep-alive':
headers.append("Keep-Alive: timeout=30, max=100")
return "\r\n".join(headers) + "\r\n\r\n"
def _create_error_response(self, status_code, message):
"""Create error response"""
error_body = f"<html><body><h1>{status_code} {message}</h1></body></html>"
headers = self._create_headers(status_code, 'text/html; charset=utf-8', len(error_body))
return headers + error_body
def _handle_get_request(self, request):
"""Handle GET requests"""
path = request['path']
# Handle root path
if path == '/':
path = '/index.html'
# Validate path
full_path = self._validate_path(path)
if not full_path:
return self._create_error_response(403, "Forbidden")
# Check if file exists
if not os.path.exists(full_path):
return self._create_error_response(404, "Not Found")
# Get content type
content_type = self._get_content_type(full_path)
if not content_type:
return self._create_error_response(415, "Unsupported Media Type")
thread_name = threading.current_thread().name
try:
if content_type == 'text/html; charset=utf-8':
# Serve HTML files as text
with open(full_path, 'r', encoding='utf-8') as f:
content = f.read()
print(f"[{self._get_timestamp()}] [{thread_name}] Sending HTML file: {os.path.basename(full_path)} ({len(content)} bytes)")
headers = self._create_headers(200, content_type, len(content), 'keep-alive')
response = headers + content
print(f"[{self._get_timestamp()}] [{thread_name}] Response: 200 OK ({len(content)} bytes transferred)")
return response
else:
# Serve binary files
with open(full_path, 'rb') as f:
content = f.read()
filename = os.path.basename(full_path)
print(f"[{self._get_timestamp()}] [{thread_name}] Sending binary file: {filename} ({len(content)} bytes)")
headers = self._create_headers(200, content_type, len(content), 'keep-alive')
headers_bytes = headers.encode()
# Add Content-Disposition header for downloads
content_disposition = f"Content-Disposition: attachment; filename=\"{filename}\"\r\n"
headers_bytes = headers_bytes.replace(b"\r\n\r\n", content_disposition.encode() + b"\r\n\r\n", 1)
response = headers_bytes + content
print(f"[{self._get_timestamp()}] [{thread_name}] Response: 200 OK ({len(content)} bytes transferred)")
return response
except Exception as e:
print(f"[{self._get_timestamp()}] [{thread_name}] Error reading file {full_path}: {e}")
return self._create_error_response(500, "Internal Server Error")
def _handle_post_request(self, request):
"""Handle POST requests"""
thread_name = threading.current_thread().name
# Check content type
content_type = request['headers'].get('Content-Type', '')
if content_type != 'application/json':
return self._create_error_response(415, "Unsupported Media Type")
# Validate JSON
try:
json_data = json.loads(request['body'])
except json.JSONDecodeError:
return self._create_error_response(400, "Bad Request - Invalid JSON")
# Create filename with timestamp and random ID
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
random_id = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
filename = f"upload_{timestamp}_{random_id}.json"
file_path = os.path.join(self.uploads_dir, filename)
# Write JSON to file
try:
with open(file_path, 'w') as f:
json.dump(json_data, f, indent=2)
print(f"[{self._get_timestamp()}] [{thread_name}] File created: {file_path}")
# Create success response
response_data = {
"status": "success",
"message": "File created successfully",
"filepath": f"/uploads/{filename}"
}
response_body = json.dumps(response_data)
headers = self._create_headers(201, 'application/json', len(response_body), 'close')
response = headers + response_body
print(f"[{self._get_timestamp()}] [{thread_name}] Response: 201 Created ({len(response_body)} bytes transferred)")
return response
except Exception as e:
print(f"[{self._get_timestamp()}] [{thread_name}] Error creating file: {e}")
return self._create_error_response(500, "Internal Server Error")
def main():
"""Main function to start the server with command line arguments"""
host = '127.0.0.1'
port = 8080
max_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:
max_threads = int(sys.argv[3])
server = HTTPServer(host, port, max_threads)
server.start()
if __name__ == "__main__":
main()