-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponses.py
More file actions
321 lines (269 loc) · 10.3 KB
/
Copy pathresponses.py
File metadata and controls
321 lines (269 loc) · 10.3 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
"""
HTTP Response Module
Contains functions to send various HTTP responses (HTML, JSON, Binary files, Error pages)
Implements proper HTTP/1.1 headers and chunked binary transfer
"""
import json
import logging
import os
import socket
import time
from wsgiref.handlers import format_date_time
# Buffer size for reading and sending binary files in chunks
BUFFER_SIZE = 8192 # 8KB chunks for efficient memory usage
def sendHttpRes(
conn: socket.socket,
status_code: int,
status: str,
content_type: str,
body: str | dict,
headers: dict,
version: str = "1.1",
isBinary: bool = False,
):
"""
Generic function to send HTTP response with custom headers and body
Args:
conn: Socket connection to client
status_code: HTTP status code (e.g., 200, 404, 500)
status: HTTP status message (e.g., "OK", "Not Found")
content_type: MIME type of response (e.g., "text/html")
body: Response body (string, dict, or bytes)
headers: Dictionary of additional headers
version: HTTP version (default: "1.1")
isBinary: Whether body is binary data (default: False)
"""
# Get current time in RFC 7231 format for Date header
current_rfc7231_time = format_date_time(time.time())
# Calculate content length (bytes if binary, encoded string length otherwise)
content_length = len(body) if isBinary else len(body.encode())
# Build HTTP response headers
header_lines = [
f"HTTP/{version} {status_code} {status}", # Status line
f"Content-Type: {content_type}", # Content type
f"Content-Length: {content_length}", # Body size in bytes
f"Date: {current_rfc7231_time}", # Current server time
"Server: Multi-threaded HTTP Server", # Server identifier
]
# Add any additional custom headers
for key, value in headers.items():
header_lines.append(f"{key}: {value}")
# Join headers with CRLF and add blank line before body
response_headers = "\r\n".join(header_lines) + "\r\n\r\n"
response_bytes = response_headers.encode()
# Handle body encoding based on type
if isBinary:
body_bytes = body # Already in bytes
else:
body_bytes = str(body).encode() # Convert to bytes
# Send complete response (headers + body) at once
conn.sendall(response_bytes + body_bytes)
def sendHttpHtml(conn: socket.socket, file_path: str, connection: str = "keep-alive"):
"""
Send HTML file as HTTP response with 200 OK status
Args:
conn: Socket connection to client
file_path: Path to HTML file to serve
connection: Connection header value (default: "keep-alive")
"""
content = ""
# Read entire HTML file into memory
with open(file_path, "r") as file:
content = file.read()
# Send response with HTML content type
sendHttpRes(
conn,
status_code=200,
status="OK",
content_type="text/html; charset=utf-8", # HTML with UTF-8 encoding
body=content,
headers={"Connection": connection}, # Support persistent connections
)
def sendHttpJson(conn: socket.socket, file_path: str, connection: str = "keep-alive"):
"""
Send JSON response indicating successful file upload
Returns 201 Created status with file location information
Args:
conn: Socket connection to client
file_path: Path where uploaded file was saved
connection: Connection header value (default: "keep-alive")
"""
try:
# Create JSON response body with upload success information
content = json.dumps(
{
"status": "success",
"message": "File created successfully",
"filepath": file_path, # Location of uploaded file
}
)
# Send 201 Created response for successful POST request
sendHttpRes(
conn,
status_code=201, # Created - resource successfully created
status="Created",
content_type="application/json", # JSON response
body=content,
headers={"Connection": connection},
)
except Exception as e:
raise e
def sendHttpBin(conn: socket.socket, file_path: str, connection: str = "keep-alive"):
"""
Send binary file (images, text files) in chunks for efficient memory usage
Uses 8KB buffer to handle large files without loading entire file into memory
Args:
conn: Socket connection to client
file_path: Path to binary file to serve
connection: Connection header value (default: "keep-alive")
"""
try:
# Get file size for Content-Length header
file_size = os.path.getsize(file_path)
_, ext = os.path.splitext(file_path)
# Default content type for binary data
content_type = "application/octet-stream"
# Get current time in RFC 7231 format
rfc_date = format_date_time(time.time())
# Build and send HTTP response headers first
response = "HTTP/1.1 200 OK\r\n"
response += f"Content-Type: {content_type}\r\n"
response += f"Content-Length: {file_size}\r\n" # Total file size in bytes
response += f'Content-Disposition: attachment; filename="{os.path.basename(file_path)}"\r\n'
response += f"Date: {rfc_date}\r\n"
response += "Server: Multi-threaded HTTP Server\r\n"
response += f"Connection: {connection}\r\n" # FIXED: Use parameter instead of hardcoded
response += "\r\n" # Blank line separates headers from body
conn.sendall(response.encode())
# Send file body in chunks (efficient for large files)
# Read and send 8KB at a time to optimize memory usage
with open(file_path, "rb") as file:
while True:
chunk = file.read(BUFFER_SIZE) # Read 8KB chunk
if not chunk: # End of file reached
break
conn.sendall(chunk) # Send chunk to client
except Exception as e:
logging.error(f"Error sending binary file: {e}")
raise
def sendHttp500(conn: socket.socket, connection: str = "keep-alive"):
"""
Send 500 Internal Server Error response
Used when server encounters unexpected errors during request processing
Args:
conn: Socket connection to client
connection: Connection header value (default: "keep-alive")
"""
content = ""
# Load the error page template from file
with open("./errorpages/500.html", "r") as file:
content = file.read()
# Send the error response with appropriate status code and content
sendHttpRes(
conn,
status_code=500,
status="Internal Server Error",
content_type="text/html; charset=utf-8",
body=content,
headers={"Connection": connection},
)
def sendHttp400(conn: socket.socket, connection: str = "keep-alive"):
"""
Send 400 Bad Request response
Used when client sends malformed HTTP request (invalid syntax, missing required headers)
Args:
conn: Socket connection to client
connection: Connection header value (default: "keep-alive")
"""
content = ""
with open("./errorpages/400.html", "r") as file:
content = file.read()
# Send the error response for bad request
sendHttpRes(
conn,
status_code=400,
status="Bad Request",
content_type="text/html; charset=utf-8",
body=content,
headers={"Connection": connection},
)
def sendHttp404(conn: socket.socket, connection: str = "keep-alive"):
"""
Send 404 Not Found response
Used when requested file/resource does not exist on server
Args:
conn: Socket connection to client
connection: Connection header value (default: "keep-alive")
"""
content = ""
with open("./errorpages/404.html", "r") as file:
content = file.read()
# Send the error response indicating the requested resource was not found
sendHttpRes(
conn,
status_code=404,
status="Not Found",
content_type="text/html; charset=utf-8",
body=content,
headers={"Connection": connection},
)
def sendHttp403(conn: socket.socket, connection: str = "keep-alive"):
"""
Send 403 Forbidden response
Used when access to resource is denied (path traversal, directory listing, invalid host)
Args:
conn: Socket connection to client
connection: Connection header value (default: "keep-alive")
"""
content = ""
with open("./errorpages/403.html", "r") as file:
content = file.read()
# Send forbidden response indicating access is not allowed
sendHttpRes(
conn,
status_code=403,
status="Forbidden",
content_type="text/html; charset=utf-8",
body=content,
headers={"Connection": connection},
)
def sendHttp405(conn: socket.socket, connection: str = "keep-alive"):
"""
Send 405 Method Not Allowed response
Used when client uses unsupported HTTP method (only GET and POST are supported)
Args:
conn: Socket connection to client
connection: Connection header value (default: "keep-alive")
"""
content = ""
with open("./errorpages/405.html", "r") as file:
content = file.read()
# Send method not allowed response
sendHttpRes(
conn,
status_code=405,
status="Method Not Allowed",
content_type="text/html; charset=utf-8",
body=content,
headers={"Connection": connection},
)
def sendHttp415(conn: socket.socket, connection: str = "keep-alive"):
"""
Send 415 Unsupported Media Type response
Used when requested file type is not in allowed extensions list (.html, .txt, .png, .jpg, .jpeg)
Args:
conn: Socket connection to client
connection: Connection header value (default: "keep-alive")
"""
content = ""
with open("./errorpages/415.html", "r") as file:
content = file.read()
# Send unsupported media type response
sendHttpRes(
conn,
status_code=415,
status="Unsupported Media Type",
content_type="text/html; charset=utf-8",
body=content,
headers={"Connection": connection},
)