-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
277 lines (229 loc) · 9.79 KB
/
server.py
File metadata and controls
277 lines (229 loc) · 9.79 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
import socket
import logging
import signal
import sys
import os
import random
import string
import json
import datetime
from urllib.parse import unquote
from email.utils import formatdate
import time
import threading
from queue import Queue, Full
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='[%(asctime)s] [%(threadName)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Folder from which files will be served
ROOT_DIR = os.path.join(os.getcwd(), "resources")
MAX_THREADS =
CONNECTION_QUEUE = Queue(maxsize=50)
# Function to get proper HTTP Date header
def http_date():
return formatdate(time.time(), usegmt=True)
# Handle each client connection
def handle_client(conn, addr):
try:
data = conn.recv(8192)
if not data:
return
lines = data.decode('utf-8', errors='ignore').split('\r\n')
request_line = lines[0]
logging.info(f"Connection from {addr}")
logging.info(f"Request: {request_line}")
# --- Parse headers ---
headers_dict = {}
for line in lines[1:]:
if ': ' in line:
k, v = line.split(': ', 1)
headers_dict[k.lower()] = v
host_header = headers_dict.get("host", "").strip()
# --- Security: Host header validation ---
if not host_header:
conn.sendall(b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\nMissing Host header")
logging.info("Blocked request with missing Host header")
return
if host_header.lower() not in ("localhost", "127.0.0.1", f"localhost:{PORT}", f"127.0.0.1:{PORT}"):
conn.sendall(b"HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\nForbidden Host")
logging.info(f"Blocked request with invalid Host: {host_header}")
return
parts = request_line.split()
if len(parts) < 3:
conn.sendall(b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n")
return
method, path, version = parts
path = unquote(path.split('?', 1)[0])
# --- GET handling ---
if method == 'GET':
# Reject requests without Host header
if not host_header:
conn.sendall(b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\nMissing Host header")
logging.info("Blocked request with missing Host header")
return
# Reject requests with invalid Host
if host_header.lower() not in ("localhost", "127.0.0.1", f"localhost:{PORT}", f"127.0.0.1:{PORT}"):
conn.sendall(b"HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\nForbidden Host")
logging.info(f"Blocked request with invalid Host: {host_header}")
return
# Resolve file path
if path == '/':
file_path = os.path.join(ROOT_DIR, "index.html")
else:
file_path = os.path.join(ROOT_DIR, path.lstrip('/'))
# Normalize and get absolute path
normalized_path = os.path.realpath(file_path)
# --- Security: Path Traversal Protection ---
root_abs = os.path.realpath(ROOT_DIR)
if os.path.commonpath([normalized_path, root_abs]) != root_abs:
conn.sendall(b"HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\nForbidden")
logging.info(f"Blocked path traversal attempt: {path}")
return
# Check if file exists
if not os.path.isfile(normalized_path):
conn.sendall(b"HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\nFile Not Found")
return
file_path = normalized_path
# Determine file type
ext = os.path.splitext(file_path)[1].lower()
if ext in ['.html']:
filename = os.path.basename(file_path)
content_type = "text/html; charset=utf-8"
with open(file_path, 'rb') as f:
body = f.read()
headers = (
"HTTP/1.1 200 OK\r\n"
f"Content-Type: {content_type}\r\n"
f"Content-Length: {len(body)}\r\n"
f"Content-Disposition: attachment; filename=\"{filename}\"\r\n"
f"Date: {http_date()}\r\n"
"Server: Multi-threaded HTTP Server\r\n"
"Connection: close\r\n"
"\r\n"
).encode('utf-8')
conn.sendall(headers + body)
elif ext in ['.txt', '.png', '.jpg', '.jpeg']:
content_type = "application/octet-stream"
filename = os.path.basename(file_path)
with open(file_path, 'rb') as f:
body = f.read()
logging.info(f"Sending binary file: {filename} ({len(body)} bytes)")
headers = (
"HTTP/1.1 200 OK\r\n"
f"Content-Type: {content_type}\r\n"
f"Content-Length: {len(body)}\r\n"
f"Content-Disposition: attachment; filename=\"{filename}\"\r\n"
f"Date: {http_date()}\r\n"
"Server: Multi-threaded HTTP Server\r\n"
"Connection: close\r\n"
"\r\n"
).encode('utf-8')
conn.sendall(headers + body)
logging.info(f"Response: 200 OK ({len(body)} bytes transferred)")
logging.info("Connection: close")
else:
conn.sendall(b"HTTP/1.1 415 Unsupported Media Type\r\nConnection: close\r\n\r\nUnsupported file type")
# --- POST /upload handling ---
elif method == 'POST':
content_type = headers_dict.get('content-type', '')
if content_type != 'application/json':
conn.sendall(b"HTTP/1.1 415 Unsupported Media Type\r\nConnection: close\r\n\r\nOnly application/json allowed")
return
content_length = int(headers_dict.get('content-length', 0))
body_data = data.split(b'\r\n\r\n', 1)[1]
while len(body_data) < content_length:
body_data += conn.recv(8192)
try:
json_data = json.loads(body_data.decode('utf-8'))
except json.JSONDecodeError:
conn.sendall(b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\nInvalid JSON")
return
# Create uploads directory if not exists
upload_dir = os.path.join(ROOT_DIR, "uploads")
os.makedirs(upload_dir, exist_ok=True)
# Generate filename
timestamp = datetime.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"
file_path = os.path.join(upload_dir, filename)
with open(file_path, 'w') as f:
json.dump(json_data, f, indent=2)
# Respond 201 Created
response_body = json.dumps({
"status": "success",
"message": "File created successfully",
"filepath": f"/uploads/{filename}"
}).encode('utf-8')
headers = (
"HTTP/1.1 201 Created\r\n"
"Content-Type: application/json\r\n"
f"Content-Length: {len(response_body)}\r\n"
f"Date: {http_date()}\r\n"
"Server: Multi-threaded HTTP Server\r\n"
"Connection: close\r\n"
"\r\n"
).encode('utf-8')
conn.sendall(headers + response_body)
else:
conn.sendall(b"HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\n\r\n")
return
except Exception as e:
logging.error(f"Error handling request: {e}")
finally:
conn.close()
# Worker thread for thread pool
def worker():
while True:
conn, addr = CONNECTION_QUEUE.get()
# Log when a connection is dequeued and assigned to this thread
if conn is not None:
logging.info(f"Connection dequeued, assigned to {threading.current_thread().name}")
if conn is None:
break
handle_client(conn, addr)
CONNECTION_QUEUE.task_done()
# Run server
def run(host, port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host, port))
server.listen(50)
logging.info(f"Server started on http://{host}:{port}")
logging.info(f"Thread pool size: {MAX_THREADS}")
logging.info(f"Serving files from '{ROOT_DIR}' directory")
logging.info("Press Ctrl+C to stop the server")
# Start thread pool
threads = []
for _ in range(MAX_THREADS):
t = threading.Thread(target=worker, daemon=True)
t.start()
threads.append(t)
# Graceful shutdown
def shutdown(sig, frame):
logging.info("Shutting down gracefully...")
server.close()
for _ in range(MAX_THREADS):
CONNECTION_QUEUE.put((None, None))
sys.exit(0)
signal.signal(signal.SIGINT, shutdown)
while True:
try:
conn, addr = server.accept()
try:
CONNECTION_QUEUE.put_nowait((conn, addr))
except Full:
logging.warning("Thread pool saturated, queuing connection") # Log when the queue is full
conn.sendall(
b"HTTP/1.1 503 Service Unavailable\r\nRetry-After: 5\r\nConnection: close\r\n\r\nServer busy"
)
conn.close()
except Exception as e:
logging.error(f"Accept error: {e}")
# Entry point
if __name__ == "__main__":
HOST = "127.0.0.1"
PORT = 8080
run(HOST, PORT)