-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.py
More file actions
253 lines (210 loc) · 8.91 KB
/
HttpServer.py
File metadata and controls
253 lines (210 loc) · 8.91 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
import socket
import threading
import os
import time
import queue
import json
from datetime import datetime
import random
import string
import sys
import logging
HOST = '127.0.0.1'
PORT = 8080
resources_dir = 'resources'
MAX_THREADS = 10
conn_queue = queue.Queue()
def parse_headers(request_data):
headers = {}
lines = request_data.split('\r\n')
for line in lines[1:]:
if line == "":
break
key, value = line.split(': ', 1)
headers[key.lower()] = value
return headers
#handler for post request
def handle_post_request(client_socket, path, headers, request_body):
#only accept application/json
if headers.get('content-type') != 'application/json':
send_error_response(client_socket, 415, "Unsupported Media Type")
return
try:
data = json.loads(request_body)
except json.JSONDecodeError:
send_error_response(client_socket, 400, "Bad Request: Invalid JSON")
return
#create a unique filename
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"
#ensure the 'uploads' directory exists
uploads_dir = os.path.join(resources_dir, 'uploads')
os.makedirs(uploads_dir, exist_ok=True)
file_path = os.path.join(uploads_dir, filename)
#write the received json data to the file
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4)
logging.info(f"Saved POST data to {file_path}")
response_body = {
"status": "success",
"message": "File created successfully",
"filepath": f"/uploads/{filename}"
}
response_body_json = json.dumps(response_body)
response_headers = [
"HTTP/1.1 201 Created",
"Content-Type: application/json",
f"Content-Length: {len(response_body_json.encode('utf-8'))}",
"Connection: keep-alive",
"Keep-Alive: timeout=30, max=100"
]
response = "\r\n".join(response_headers) + "\r\n\r\n" + response_body_json
client_socket.sendall(response.encode('utf-8'))
logging.info("Response: 201 Created")
#Helper function for GET requests to keep the main handler clean
def handle_get_request(conn, path):
if path == '/':
path = '/index.html'
file_path = os.path.join(resources_dir, path.lstrip('/'))
base_dir = os.path.abspath(resources_dir)
requested_path = os.path.abspath(file_path)
if not requested_path.startswith(base_dir):
logging.warning(f"SECURITY: Path traversal attempt blocked ('{path}').")
send_error_response(conn, 403, "Forbidden")
return
if os.path.exists(requested_path) and os.path.isfile(requested_path):
_, extension = os.path.splitext(requested_path)
content_type = 'application/octet-stream'
read_mode = 'rb'
extra_headers = [f'Content-Disposition: attachment; filename="{os.path.basename(requested_path)}"']
if extension == '.html':
content_type = 'text/html; charset=utf-8'
read_mode = 'r'
extra_headers = []
elif extension == '.ico':
content_type = 'image/x-icon'
extra_headers = []
with open(requested_path, read_mode) as f:
content = f.read()
if isinstance(content, str):
content = content.encode('utf-8')
response_headers = [
"HTTP/1.1 200 OK",
f"Content-Type: {content_type}",
f"Content-Length: {len(content)}",
"Connection: keep-alive",
"Keep-Alive: timeout=30, max=100"
] + extra_headers
response_header_bytes = ("\r\n".join(response_headers) + "\r\n\r\n").encode('utf-8')
conn.sendall(response_header_bytes + content)
logging.info(f"Response: 200 OK for {path}")
else:
send_error_response(conn, 404, "Not Found")
def handle_client_connection(conn, addr):
logging.info(f"Accepted connection from {addr}")
conn.settimeout(30.0)
requests_served = 0
try:
while requests_served < 100:
try:
request_raw = conn.recv(8192)
if not request_raw:
logging.info(f"Client {addr} closed connection.")
break
header_part, _, body_part = request_raw.partition(b'\r\n\r\n')
request_data = header_part.decode('utf-8')
request_lines = request_data.split('\r\n')
if not request_lines or not request_lines[0]:
continue
request_line = request_lines[0]
logging.info(f"Request #{requests_served + 1}: {request_line}")
method, path, version = request_line.split()
headers = parse_headers(request_data)
host_header = headers.get('host')
expected_host = f"{HOST}:{PORT}"
if not host_header or host_header != expected_host:
send_error_response(conn, 403, "Forbidden: Invalid Host Header")
break
if method == 'GET':
handle_get_request(conn, path)
elif method == 'POST':
content_length = int(headers.get('content-length', 0))
while len(body_part) < content_length:
body_part += conn.recv(8192)
handle_post_request(conn, path, headers, body_part.decode('utf-8'))
else:
send_error_response(conn, 405, "Method Not Allowed")
requests_served += 1
if headers.get('connection', 'keep-alive').lower() == 'close':
logging.info("'Connection: close' received. Closing.")
break
except socket.timeout:
logging.info(f"Connection from {addr} timed out. Closing.")
break
except (ValueError, IndexError):
send_error_response(conn, 400, "Bad Request")
break
except Exception as e:
logging.error(f"Error processing request: {e}")
send_error_response(conn, 500, "Internal Server Error")
break
finally:
logging.info(f"Closing connection with {addr} after serving {requests_served} requests.")
conn.close()
def send_error_response(conn, status_code, status_message):
logging.warning(f"Response: {status_code} {status_message}")
error_content = f"<html><body><h1>{status_code} {status_message}</h1></body></html>"
response_header = [
f"HTTP/1.1 {status_code} {status_message}",
"Content-Type: text/html; charset=utf-8",
f"Content-Length: {len(error_content.encode('utf-8'))}",
"Connection: close"
]
response = "\r\n".join(response_header) + "\r\n\r\n" + error_content
conn.sendall(response.encode('utf-8'))
def worker():
while True:
conn, addr = conn_queue.get()
handle_client_connection(conn, addr)
conn_queue.task_done()
def main():
#logging configuration
log_format = '%(asctime)s [%(threadName)s] %(message)s'
date_format = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging.INFO, format=log_format, datefmt=date_format)
global HOST, PORT, MAX_THREADS
if len(sys.argv) > 1:
try:
PORT = int(sys.argv[1])
except ValueError:
logging.error(f"Invalid port '{sys.argv[1]}'. Using default {PORT}.")
if len(sys.argv) > 2:
HOST = sys.argv[2]
if len(sys.argv) > 3:
try:
MAX_THREADS = int(sys.argv[3])
except ValueError:
logging.error(f"Invalid thread count '{sys.argv[3]}'. Using default {MAX_THREADS}.")
for i in range(MAX_THREADS):
# The logger will automatically name threads Thread-1, Thread-2, etc.
thread = threading.Thread(target=worker, name=f"Worker-{i+1}", daemon=True)
thread.start()
logging.info(f"Thread pool with {MAX_THREADS} workers started.")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(50)
logging.info(f"Server started on http://{HOST}:{PORT}")
logging.info(f"Serving files from '{resources_dir}' directory")
logging.info("Press Ctrl+C to stop the server")
try:
while True:
conn, addr = sock.accept()
conn_queue.put((conn, addr))
except KeyboardInterrupt:
logging.info("\nShutting down server.")
finally:
sock.close()
if __name__ == "__main__":
main()